feat(wasm): C2/C3 session boot, wire events, and interact demo
Add BrowserSession with shared entry env, mq_boot/mq_call exports, marqdo wasm build, and a counter page driven only by counter.mq.md. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
fb037022ba
commit
aac896b044
17 files changed
+698
-168
No files matched your search
@@ -5,6 +5,7 @@
|
||||
### Added
|
||||
- **浏览器 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/)。
|
||||
- **C2/C3**:`marqdo wasm build`;会话 `mq_boot`/`mq_call`;GFM wire 表 + `set_text` DOM 回写;[interact.html](examples/browser-hello/interact.html) 计数器示例。
|
||||
|
||||
### Fixed
|
||||
- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。
|
||||
|
||||
@@ -2,12 +2,18 @@
|
||||
|
||||
Raw `cdylib` exports — no `wasm-bindgen` CLI required.
|
||||
|
||||
| Export | Role |
|
||||
|--------|------|
|
||||
| `mq_alloc` / `mq_dealloc` | linear memory |
|
||||
| `mq_run` | one-shot `# main` (C1) |
|
||||
| `mq_boot` / `mq_call` | session + handlers (C3) |
|
||||
| `mq_version` | version C string |
|
||||
|
||||
```bash
|
||||
# from repo root
|
||||
marqdo wasm build -o examples/browser-hello
|
||||
# or:
|
||||
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).
|
||||
+119
-37
@@ -1,16 +1,26 @@
|
||||
//! Browser export surface for Marqdo (ADR 0002 / C1).
|
||||
//! Browser export surface for Marqdo (ADR 0002 / C1–C3).
|
||||
//!
|
||||
//! 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
|
||||
//! Raw `cdylib` ABI (no wasm-bindgen CLI):
|
||||
//! - `mq_alloc` / `mq_dealloc`
|
||||
//! - `mq_run` — one-shot `# main` (C1)
|
||||
//! - `mq_boot` — start session; return value often a `wire` table (C3)
|
||||
//! - `mq_call` — `(name_ptr, name_len, args_ptr, args_len) ->` JSON result (C3)
|
||||
//! - `mq_version`
|
||||
//!
|
||||
//! Result JSON: `{ ok, stdout, error, value }`.
|
||||
//! Packed results: little-endian `u32` length + UTF-8 JSON
|
||||
//! `{ ok, stdout, error, value }`.
|
||||
|
||||
use std::alloc::{alloc, dealloc, Layout};
|
||||
use std::cell::RefCell;
|
||||
use std::ptr;
|
||||
use std::slice;
|
||||
|
||||
use marqdo::{run_source, RunOptions};
|
||||
use marqdo::{run_source, value_as_json, BrowserSession, RunOptions};
|
||||
use serde_json::json;
|
||||
|
||||
thread_local! {
|
||||
static SESSION: RefCell<Option<BrowserSession>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Allocate `size` bytes in WASM linear memory (alignment 1).
|
||||
#[no_mangle]
|
||||
@@ -25,7 +35,7 @@ pub extern "C" fn mq_alloc(size: usize) -> *mut u8 {
|
||||
unsafe { alloc(layout) }
|
||||
}
|
||||
|
||||
/// Free a buffer previously returned by [`mq_alloc`] or [`mq_run`].
|
||||
/// Free a buffer previously returned by [`mq_alloc`], [`mq_run`], [`mq_boot`], or [`mq_call`].
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_dealloc(ptr: *mut u8, size: usize) {
|
||||
if ptr.is_null() || size == 0 {
|
||||
@@ -38,27 +48,84 @@ pub extern "C" fn mq_dealloc(ptr: *mut u8, size: usize) {
|
||||
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`.
|
||||
/// One-shot run (C1). Does not keep a session.
|
||||
#[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,
|
||||
}));
|
||||
}
|
||||
}
|
||||
let source = match read_utf8(ptr, len) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
pack_json(&run_to_json(source))
|
||||
pack_json(&run_to_json(&source))
|
||||
}
|
||||
|
||||
/// Boot a session: run `# main`, keep entry env. Replaces any prior session.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_boot(ptr: *const u8, len: usize) -> *mut u8 {
|
||||
let source = match read_utf8(ptr, len) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
match BrowserSession::boot(&source) {
|
||||
Ok((sess, value)) => {
|
||||
let stdout = String::new();
|
||||
let value_json = match value_as_json(&value) {
|
||||
Ok(j) => j,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
SESSION.with(|s| *s.borrow_mut() = Some(sess));
|
||||
pack_json(&json!({
|
||||
"ok": true,
|
||||
"stdout": stdout,
|
||||
"error": null,
|
||||
"value": value_json,
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
SESSION.with(|s| *s.borrow_mut() = None);
|
||||
pack_json(&err_json(&format!("{e:#}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Call a function in the current session.
|
||||
/// `args` is UTF-8 JSON object of named arguments (may be `{}`).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_call(
|
||||
name_ptr: *const u8,
|
||||
name_len: usize,
|
||||
args_ptr: *const u8,
|
||||
args_len: usize,
|
||||
) -> *mut u8 {
|
||||
let name = match read_utf8(name_ptr, name_len) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
let args = match read_utf8(args_ptr, args_len) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
SESSION.with(|cell| {
|
||||
let mut guard = cell.borrow_mut();
|
||||
let Some(sess) = guard.as_mut() else {
|
||||
return pack_json(&err_json("no session — call mq_boot first"));
|
||||
};
|
||||
match sess.call(&name, &args) {
|
||||
Ok(value) => {
|
||||
let stdout = sess.take_stdout();
|
||||
let value_json = match value_as_json(&value) {
|
||||
Ok(j) => j,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
pack_json(&json!({
|
||||
"ok": true,
|
||||
"stdout": stdout,
|
||||
"error": null,
|
||||
"value": value_json,
|
||||
}))
|
||||
}
|
||||
Err(e) => pack_json(&err_json(&format!("{e:#}"))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Package version (NUL-terminated C string in static memory — do not free).
|
||||
@@ -67,6 +134,14 @@ pub extern "C" fn mq_version() -> *const u8 {
|
||||
concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr()
|
||||
}
|
||||
|
||||
fn read_utf8(ptr: *const u8, len: usize) -> Result<String, String> {
|
||||
if ptr.is_null() || len == 0 {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let bytes = unsafe { slice::from_raw_parts(ptr, len) };
|
||||
String::from_utf8(bytes.to_vec()).map_err(|e| format!("not utf-8: {e}"))
|
||||
}
|
||||
|
||||
fn run_to_json(source: &str) -> serde_json::Value {
|
||||
let mut opts = RunOptions::default();
|
||||
opts.allow_fs_write = false;
|
||||
@@ -75,21 +150,28 @@ fn run_to_json(source: &str) -> serde_json::Value {
|
||||
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,
|
||||
}),
|
||||
Ok(cap) => match value_as_json(&cap.value) {
|
||||
Ok(value) => json!({
|
||||
"ok": true,
|
||||
"stdout": cap.stdout,
|
||||
"error": null,
|
||||
"value": value,
|
||||
}),
|
||||
Err(e) => err_json(&e),
|
||||
},
|
||||
Err(e) => err_json(&format!("{e:#}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn err_json(msg: &str) -> serde_json::Value {
|
||||
json!({
|
||||
"ok": false,
|
||||
"stdout": "",
|
||||
"error": msg,
|
||||
"value": null,
|
||||
})
|
||||
}
|
||||
|
||||
fn pack_json(v: &serde_json::Value) -> *mut u8 {
|
||||
let s = v.to_string();
|
||||
let bytes = s.as_bytes();
|
||||
|
||||
@@ -152,27 +152,47 @@ source: &str (+ optional import map)
|
||||
|
||||
## 6. 交互装配(C3,对称样式装配)
|
||||
|
||||
作者面(示意,关键字以落地时 `ext` 双语名为准;**不在核心发明 `if`/`on` 关键字**):
|
||||
### 6.1 作者面(示例)
|
||||
|
||||
```markdown
|
||||
`交互` =
|
||||
---
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
| 选择器 | 事件 | 调用 |
|
||||
|--------|------|------|
|
||||
| "#btn" | click | handle_click |
|
||||
| ".item" | click | select_item |
|
||||
# main
|
||||
|
||||
*`_`` = > 浏览器.交互装配 表=`交互` *
|
||||
*`count` = 0*
|
||||
|
||||
`wire` =
|
||||
|
||||
| @ | 选择器 | 事件 | 调用 |
|
||||
|---|--------|------|------|
|
||||
| 1 | "#bump" | click | bump |
|
||||
|
||||
**`wire`**
|
||||
|
||||
## bump
|
||||
*`count` = count + 1*
|
||||
*`label` = > str count*
|
||||
*`patch` = > json.set map=None key="#count" value=label*
|
||||
**> json.set map=None key="set_text" value=patch**
|
||||
```
|
||||
|
||||
语义:
|
||||
`# main` 的返回值是 **wire 表**(`@` 行向记录列表)。Loader 调用 `mq_boot`,再 `wireEvents`。
|
||||
|
||||
1. 装配函数把表登记到 WASM 侧 registry。
|
||||
2. Loader 在 DOM 上 `addEventListener`;触发时调用导出 `marqdo_dispatch(event_id, payload_json)`。
|
||||
3. 调用解析为 Marqdo 函数(同页已 `load` 的模块内 `## handle_click`)。
|
||||
4. 返回值约定(C3 最小):`None` / 文本 / Map(如 `{dom:…}` 指令列表)由桥执行,**避免在核心写死 React**。
|
||||
### 6.2 桥约定
|
||||
|
||||
值列含 `/` 的 CSS 等仍遵守 [table-cell-expressions.md](table-cell-expressions.md):**引号优先**(`"16/9"`)。
|
||||
| 步骤 | API |
|
||||
|------|-----|
|
||||
| 启动 | `mq_boot(source)` → `{ ok, value }`;`value` = wire 列表或 `{ wire: [...] }` |
|
||||
| 事件 | Loader `addEventListener` → `mq_call(fn, {"event":"click"})` |
|
||||
| 回写 | 返回 Map 可含 `set_text`: `{ "#sel": "text" }`(仅 `textContent`) |
|
||||
|
||||
行键名认:`选择器`/`selector`、`事件`/`event`、`调用`/`call`。
|
||||
|
||||
含 `/` 的 CSS 等单元格仍 **引号优先**(见 [table-cell-expressions.md](table-cell-expressions.md))。
|
||||
|
||||
L1 `浏览器.交互装配`(ext)可后置;C3 以 bridge + 返回 wire 表即可验收。
|
||||
|
||||
---
|
||||
|
||||
|
||||
+20
-71
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **进行中**(C0–C1 已落地;C2 示例页已有) |
|
||||
| 状态 | **进行中**(C0–C3 已落地) |
|
||||
| 日期 | 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,90 +16,38 @@
|
||||
|
||||
| 阶段 | 内容 | 状态 |
|
||||
|------|------|------|
|
||||
| **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 |
|
||||
|
||||
---
|
||||
|
||||
## C0 — 可移植骨架
|
||||
|
||||
**目标:** native 默认行为不变;存在 `--features wasm-core --no-default-features` 使核心在 `wasm32-unknown-unknown` 上 `cargo check`。
|
||||
|
||||
**已落地:**
|
||||
|
||||
- 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/`)
|
||||
|
||||
**验收:**
|
||||
|
||||
```bash
|
||||
cargo check -p marqdo --target wasm32-unknown-unknown --no-default-features --features wasm-core
|
||||
cargo test --test gold structure_hello
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## C1 — 内存执行闭环
|
||||
|
||||
**目标:** 浏览器/测试调用 `run_source`,跑 `# main` + `> print`,拿回 stdout。
|
||||
|
||||
**已落地:**
|
||||
|
||||
- `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
|
||||
|
||||
**验收:**
|
||||
|
||||
```bash
|
||||
cargo test -p marqdo-wasm
|
||||
cargo test --lib run_source_hello
|
||||
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release
|
||||
```
|
||||
| **C0** | Cargo feature 骨架;`wasm32` check | **done** |
|
||||
| **C1** | `run_source` + `mq_run` | **done** |
|
||||
| **C2** | loader + `examples/browser-hello` + `marqdo wasm build` | **done** |
|
||||
| **C3** | 会话 `mq_boot`/`mq_call`;wire 表;`set_text` DOM 回写 | **done** |
|
||||
| **C4** | `fetch`/定时器异步模型 | pending |
|
||||
| **C5** | bytecode / 体积 / view 调试 | pending |
|
||||
|
||||
---
|
||||
|
||||
## C2 — 示例页与挂载
|
||||
|
||||
**目标:** 静态 HTML 打开即可跑 Marqdo。
|
||||
|
||||
**已有:** `examples/browser-hello/`(`index.html` + `loader.js` + README)。
|
||||
**仍缺:** `marqdo wasm build` CLI 糖;`page.head` 文档示例挂载。
|
||||
```bash
|
||||
marqdo wasm build -o examples/browser-hello
|
||||
cd examples/browser-hello && python3 -m http.server 8765
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## C3 — 交互装配
|
||||
|
||||
**目标:** 无手写业务 JS 的点击 → Marqdo 函数 → 改页面。
|
||||
- `BrowserSession` + `Interpreter::invoke_in_entry`
|
||||
- ABI:`mq_boot` / `mq_call`
|
||||
- 示例:`interact.html` + `counter.mq.md`
|
||||
- Bridge:`wireEvents` / `applyDomPatch`
|
||||
|
||||
(见设计 §6)
|
||||
**验收:** 打开 interact 页,点「加一」计数递增;源码仅为 `.mq.md` + 官方 bridge。
|
||||
|
||||
---
|
||||
|
||||
## C4 — 异步 I/O
|
||||
## C4 / C5
|
||||
|
||||
**目标:** 受控 `fetch`(及 sleep)不阻塞语言谎言。
|
||||
|
||||
---
|
||||
|
||||
## C5 — 硬化
|
||||
|
||||
**目标:** bytecode、体积、`view` 调试对齐。
|
||||
|
||||
---
|
||||
|
||||
## 依赖关系
|
||||
|
||||
```
|
||||
C0 ──► C1 ──► C2 ──► C3 ──► C4
|
||||
│ │
|
||||
└──── C5 ◄─────┘
|
||||
```
|
||||
见设计文 §7 / §12。
|
||||
|
||||
---
|
||||
|
||||
@@ -107,4 +55,5 @@ C0 ──► C1 ──► C2 ──► C3 ──► C4
|
||||
|
||||
| 日期 | 记录 |
|
||||
|------|------|
|
||||
| 2026-09-01 | ADR 0002 + 设计锁定;C0 feature-gate;C1 `run_source` + `marqdo-wasm` + browser-hello |
|
||||
| 2026-09-01 | ADR 0002;C0–C1 |
|
||||
| 2026-09-01 | C2 `wasm build`;C3 session + interact 示例 |
|
||||
@@ -1,16 +1,21 @@
|
||||
# browser-hello(WASM C1)
|
||||
# browser-hello(WASM C1–C3)
|
||||
|
||||
在浏览器里跑 Marqdo `print`(路线 C)。
|
||||
浏览器内跑 Marqdo(路线 C)。
|
||||
|
||||
```bash
|
||||
# 仓库根目录
|
||||
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release
|
||||
cp target/wasm32-unknown-unknown/release/marqdo_wasm.wasm examples/browser-hello/
|
||||
cargo build -p marqdo --release
|
||||
./target/release/marqdo wasm build -o examples/browser-hello
|
||||
|
||||
cd examples/browser-hello
|
||||
python3 -m http.server 8765
|
||||
# 打开 http://127.0.0.1:8765/
|
||||
```
|
||||
|
||||
- `loader.js` 仅为官方宿主桥(分配内存 / 调 `mq_run`),不是业务语言。
|
||||
| 页 | 说明 |
|
||||
|----|------|
|
||||
| [/](http://127.0.0.1:8765/) | C1:编辑源码 → `mq_run` 打印 |
|
||||
| [/interact.html](http://127.0.0.1:8765/interact.html) | C3:`counter.mq.md` 交互表 → 点击改 DOM |
|
||||
|
||||
- `marqdo-bridge.js`:官方宿主桥(`boot` / `call` / `wireEvents` / `applyDomPatch`)
|
||||
- `counter.mq.md`:作者面只有 `.mq.md`(业务逻辑)
|
||||
- 设计:[browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md)
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
title: browser counter (C3)
|
||||
description: wire table + shared entry env; click updates DOM via set_text
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*`count` = 0*
|
||||
|
||||
`wire` =
|
||||
|
||||
| @ | 选择器 | 事件 | 调用 |
|
||||
|---|--------|------|------|
|
||||
| 1 | "#bump" | click | bump |
|
||||
| 2 | "#reset" | click | reset |
|
||||
|
||||
**`wire`**
|
||||
|
||||
## bump
|
||||
*`count` = count + 1*
|
||||
*`label` = > str count*
|
||||
*`patch` = > json.set map=None key="#count" value=label*
|
||||
**> json.set map=None key="set_text" value=patch**
|
||||
|
||||
## reset
|
||||
*`count` = 0*
|
||||
*`patch` = > json.set map=None key="#count" value="0"*
|
||||
**> json.set map=None key="set_text" value=patch**
|
||||
@@ -67,7 +67,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">浏览器内 WASM 解释器(路线 C / C1):源码是 <code>.mq.md</code>,无业务手写 JS。</p>
|
||||
<p class="lead">浏览器内 WASM 解释器(路线 C / C1):源码是 <code>.mq.md</code>,无业务手写 JS。<a href="./interact.html">交互示例 (C3)</a></p>
|
||||
<label for="src">程序</label>
|
||||
<textarea id="src"># main
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hans">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Marqdo · 交互装配 (C3)</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(900px 500px at 90% 0%, #cfe0d2 0%, transparent 50%),
|
||||
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;
|
||||
}
|
||||
.lead { color: var(--muted); margin: 0 0 1.5rem; max-width: 36rem; }
|
||||
#count {
|
||||
font-family: "IBM Plex Serif", serif;
|
||||
font-size: 4rem;
|
||||
line-height: 1;
|
||||
margin: 1rem 0 1.25rem;
|
||||
letter-spacing: -0.04em;
|
||||
}
|
||||
button {
|
||||
margin-right: 0.5rem;
|
||||
padding: 0.55rem 1.1rem;
|
||||
border: 0;
|
||||
background: var(--accent);
|
||||
color: #f5faf6;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.secondary { background: #3a4740; }
|
||||
pre {
|
||||
margin-top: 1.5rem;
|
||||
width: min(40rem, 100%);
|
||||
padding: 0.9rem 1rem;
|
||||
background: #122018;
|
||||
color: #d7eadc;
|
||||
overflow: auto;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.err { color: #ffb4a8; }
|
||||
a { color: var(--accent); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">C3:GFM 交互表装配事件;点击由 WASM 会话里的 Marqdo 函数处理并回写 DOM。<a href="./">打印示例</a></p>
|
||||
<div id="count">0</div>
|
||||
<button id="bump" type="button" disabled>加一</button>
|
||||
<button id="reset" class="secondary" type="button" disabled>清零</button>
|
||||
<pre id="log">loading…</pre>
|
||||
<script type="module" src="./interact.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
applyDomPatch,
|
||||
boot,
|
||||
loadWasm,
|
||||
readCString,
|
||||
wireEvents,
|
||||
} from "./marqdo-bridge.js";
|
||||
|
||||
async function main() {
|
||||
const log = document.getElementById("log");
|
||||
const bump = document.getElementById("bump");
|
||||
const reset = document.getElementById("reset");
|
||||
|
||||
let exports;
|
||||
try {
|
||||
exports = await loadWasm("./marqdo_wasm.wasm");
|
||||
} catch (e) {
|
||||
log.classList.add("err");
|
||||
log.textContent = String(e);
|
||||
return;
|
||||
}
|
||||
|
||||
const srcRes = await fetch("./counter.mq.md");
|
||||
if (!srcRes.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = `failed to load counter.mq.md (${srcRes.status})`;
|
||||
return;
|
||||
}
|
||||
const source = await srcRes.text();
|
||||
const result = boot(exports, source);
|
||||
if (!result.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = result.error || "boot failed";
|
||||
return;
|
||||
}
|
||||
|
||||
const n = wireEvents(exports, result.value, {
|
||||
onError: (err) => {
|
||||
log.classList.add("err");
|
||||
log.textContent = err;
|
||||
},
|
||||
});
|
||||
// Ensure initial display matches Marqdo state.
|
||||
applyDomPatch({ set_text: { "#count": "0" } });
|
||||
|
||||
const ver = readCString(exports.memory, exports.mq_version());
|
||||
log.classList.remove("err");
|
||||
log.textContent = `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: counter.mq.md`;
|
||||
bump.disabled = false;
|
||||
reset.disabled = false;
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,54 +1,28 @@
|
||||
/**
|
||||
* Thin loader for marqdo_wasm.wasm (C1 raw ABI).
|
||||
* Not application logic — only host bridge.
|
||||
*/
|
||||
import {
|
||||
loadWasm,
|
||||
readCString,
|
||||
runSource,
|
||||
} from "./marqdo-bridge.js";
|
||||
|
||||
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) {
|
||||
let exports;
|
||||
try {
|
||||
exports = await loadWasm("./marqdo_wasm.wasm");
|
||||
} catch (e) {
|
||||
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/`;
|
||||
out.textContent = String(e);
|
||||
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`;
|
||||
@@ -60,7 +34,9 @@ async function main() {
|
||||
out.classList.toggle("err", !result.ok);
|
||||
out.textContent = result.ok
|
||||
? (result.stdout || "(empty stdout)") +
|
||||
(result.value && result.value !== "None" ? `\n[return] ${result.value}` : "")
|
||||
(result.value != null && result.value !== "None"
|
||||
? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}`
|
||||
: "")
|
||||
: result.error || "error";
|
||||
} catch (e) {
|
||||
out.classList.add("err");
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Official Marqdo browser bridge (route C). Host glue only — not app logic.
|
||||
*
|
||||
* ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version
|
||||
* Packed results: u32le length + UTF-8 JSON { ok, stdout, error, value }
|
||||
*/
|
||||
|
||||
export 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 decodePacked(exports, outPtr) {
|
||||
if (!outPtr) throw new Error("null wasm result pointer");
|
||||
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);
|
||||
}
|
||||
|
||||
function writeUtf8(exports, text) {
|
||||
const encoded = new TextEncoder().encode(text);
|
||||
const ptr = exports.mq_alloc(encoded.length || 1);
|
||||
if (!ptr) throw new Error("mq_alloc failed");
|
||||
new Uint8Array(exports.memory.buffer, ptr, encoded.length).set(encoded);
|
||||
return { ptr, len: encoded.length };
|
||||
}
|
||||
|
||||
export function runSource(exports, source) {
|
||||
const { ptr, len } = writeUtf8(exports, source);
|
||||
const outPtr = exports.mq_run(ptr, len);
|
||||
exports.mq_dealloc(ptr, len || 1);
|
||||
return decodePacked(exports, outPtr);
|
||||
}
|
||||
|
||||
export function boot(exports, source) {
|
||||
const { ptr, len } = writeUtf8(exports, source);
|
||||
const outPtr = exports.mq_boot(ptr, len);
|
||||
exports.mq_dealloc(ptr, len || 1);
|
||||
return decodePacked(exports, outPtr);
|
||||
}
|
||||
|
||||
export function call(exports, name, argsObj = {}) {
|
||||
const n = writeUtf8(exports, name);
|
||||
const a = writeUtf8(exports, JSON.stringify(argsObj ?? {}));
|
||||
const outPtr = exports.mq_call(n.ptr, n.len, a.ptr, a.len);
|
||||
exports.mq_dealloc(n.ptr, n.len || 1);
|
||||
exports.mq_dealloc(a.ptr, a.len || 1);
|
||||
return decodePacked(exports, outPtr);
|
||||
}
|
||||
|
||||
export async function loadWasm(url = "./marqdo_wasm.wasm") {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
`failed to fetch ${url} (${res.status}). Build with: marqdo wasm build -o .`,
|
||||
);
|
||||
}
|
||||
const { instance } = await WebAssembly.instantiateStreaming(res, {});
|
||||
return instance.exports;
|
||||
}
|
||||
|
||||
/** Apply C3 return patches: { set_text: { "#id": "…" } } */
|
||||
export function applyDomPatch(value) {
|
||||
if (!value || typeof value !== "object") return;
|
||||
const setText = value.set_text || value.setText;
|
||||
if (setText && typeof setText === "object") {
|
||||
for (const [sel, text] of Object.entries(setText)) {
|
||||
const el = document.querySelector(sel);
|
||||
if (el) el.textContent = String(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire events from `# main` return value.
|
||||
* Accepts a list of row maps, or `{ wire: [...] }`.
|
||||
* Row keys: 选择器|selector, 事件|event, 调用|call
|
||||
*/
|
||||
export function wireEvents(exports, bootValue, { onError } = {}) {
|
||||
let rows = [];
|
||||
if (Array.isArray(bootValue)) rows = bootValue;
|
||||
else if (bootValue && Array.isArray(bootValue.wire)) rows = bootValue.wire;
|
||||
|
||||
for (const row of rows) {
|
||||
const sel = row["选择器"] || row.selector || row.sel;
|
||||
const ev = row["事件"] || row.event || "click";
|
||||
const fn = row["调用"] || row.call || row.fn;
|
||||
if (!sel || !fn) continue;
|
||||
const nodes = document.querySelectorAll(sel);
|
||||
nodes.forEach((node) => {
|
||||
node.addEventListener(ev, () => {
|
||||
try {
|
||||
const result = call(exports, fn, { event: ev });
|
||||
if (!result.ok) {
|
||||
if (onError) onError(result.error);
|
||||
else console.error(result.error);
|
||||
return;
|
||||
}
|
||||
applyDomPatch(result.value);
|
||||
if (result.stdout) console.log(result.stdout);
|
||||
} catch (e) {
|
||||
if (onError) onError(String(e));
|
||||
else console.error(e);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
return rows.length;
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! In-memory browser / WASM session: boot `# main`, then call handlers with shared entry env.
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
|
||||
use crate::ast::Module;
|
||||
use crate::host::json::{json_to_value, value_to_json};
|
||||
use crate::host::{HostCaps, HostContext};
|
||||
use crate::interp::Interpreter;
|
||||
use crate::load::load_module_from_source;
|
||||
use crate::value::Value;
|
||||
|
||||
/// Persistent Marqdo program for the browser host bridge.
|
||||
pub struct BrowserSession {
|
||||
module: Module,
|
||||
interp: Interpreter,
|
||||
}
|
||||
|
||||
impl BrowserSession {
|
||||
/// Parse source, run `# main`, keep entry bindings for later [`Self::call`].
|
||||
pub fn boot(source: &str) -> Result<(Self, Value)> {
|
||||
if source.trim().is_empty() {
|
||||
bail!("source is empty");
|
||||
}
|
||||
let module = load_module_from_source(source)?;
|
||||
let caps = HostCaps {
|
||||
fs_write: false,
|
||||
exec: false,
|
||||
net: false,
|
||||
plugin: false,
|
||||
};
|
||||
let mut host = HostContext::for_capture(None, caps);
|
||||
host.set_entry_source(None, source);
|
||||
host.sleep_limit_ms = Some(0);
|
||||
let mut interp = Interpreter::with_capture(None, false).with_host(host);
|
||||
let value = interp.run_module(&module)?;
|
||||
Ok((Self { module, interp }, value))
|
||||
}
|
||||
|
||||
/// Invoke `name` with optional JSON object of named args; updates entry bindings.
|
||||
pub fn call(&mut self, name: &str, args_json: &str) -> Result<Value> {
|
||||
let args = parse_named_args(args_json)?;
|
||||
self.interp.captured_stdout.clear();
|
||||
self.interp.invoke_in_entry(&self.module, name, &args)
|
||||
}
|
||||
|
||||
pub fn take_stdout(&mut self) -> String {
|
||||
std::mem::take(&mut self.interp.captured_stdout)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_named_args(args_json: &str) -> Result<Vec<(String, Value)>> {
|
||||
let t = args_json.trim();
|
||||
if t.is_empty() || t == "{}" || t == "null" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let v: serde_json::Value =
|
||||
serde_json::from_str(t).map_err(|e| anyhow::anyhow!("call args json: {e}"))?;
|
||||
match v {
|
||||
serde_json::Value::Object(map) => {
|
||||
let mut out = Vec::new();
|
||||
for (k, j) in map {
|
||||
out.push((k, json_to_value(&j).map_err(|e| anyhow::anyhow!(e))?));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
serde_json::Value::Null => Ok(Vec::new()),
|
||||
_ => bail!("call args must be a JSON object"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize a runtime [`Value`] to JSON (for WASM bridge responses).
|
||||
pub fn value_as_json(v: &Value) -> Result<serde_json::Value, String> {
|
||||
value_to_json(v)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn boot_and_call_share_count() {
|
||||
let src = r##"---
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*`count` = 0*
|
||||
|
||||
`wire` =
|
||||
|
||||
| @ | 选择器 | 事件 | 调用 |
|
||||
|---|--------|------|------|
|
||||
| 1 | "#btn" | click | bump |
|
||||
|
||||
**`wire`**
|
||||
|
||||
## bump
|
||||
*`count` = count + 1*
|
||||
*`label` = > str count*
|
||||
*`patch` = > json.set map=None key="#out" value=label*
|
||||
**> json.set map=None key="set_text" value=patch**
|
||||
"##;
|
||||
let (mut sess, wire) = BrowserSession::boot(src).expect("boot");
|
||||
assert!(matches!(wire, Value::List(_)), "wire={wire:?}");
|
||||
let _v1 = sess.call("bump", "{}").expect("call1");
|
||||
let v2 = sess.call("bump", "{}").expect("call2");
|
||||
let j2 = value_as_json(&v2).unwrap();
|
||||
assert_eq!(j2["set_text"]["#out"], "2");
|
||||
}
|
||||
}
|
||||
@@ -151,6 +151,27 @@ impl Interpreter {
|
||||
self.run_function(module, fun, Env::new(), args, false)
|
||||
}
|
||||
|
||||
/// Call a function using (and updating) [`Self::entry_bindings`] from `# main`.
|
||||
/// Used by browser WASM sessions so handlers share state with the entry object.
|
||||
pub fn invoke_in_entry(
|
||||
&mut self,
|
||||
module: &Module,
|
||||
name: &str,
|
||||
args: &[(String, Value)],
|
||||
) -> Result<Value> {
|
||||
let fun = find_function_anywhere(module, name)
|
||||
.ok_or_else(|| self.err(format!("unknown function `{name}`")))?;
|
||||
let mut env = Env::new();
|
||||
for (k, v) in &self.entry_bindings {
|
||||
env.set(k.clone(), v.clone());
|
||||
}
|
||||
let prev = self.site_module;
|
||||
self.site_module = Some(module as *const Module);
|
||||
let result = self.run_function(module, fun, env, args, true);
|
||||
self.site_module = prev;
|
||||
result
|
||||
}
|
||||
|
||||
pub fn run_module(&mut self, module: &Module) -> Result<Value> {
|
||||
let prev = self.site_module;
|
||||
self.site_module = Some(module as *const Module);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
pub mod aliases;
|
||||
pub mod ast;
|
||||
pub mod browser_session;
|
||||
pub mod builtin;
|
||||
pub mod bytecode;
|
||||
pub mod capture;
|
||||
@@ -29,6 +30,8 @@ pub mod value;
|
||||
pub mod version_check;
|
||||
#[cfg(feature = "view")]
|
||||
pub mod view;
|
||||
#[cfg(feature = "cli")]
|
||||
pub mod wasm_cli;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
@@ -42,6 +45,8 @@ use crate::interp::Interpreter;
|
||||
use crate::lex::{classify_source, format_lines_dump};
|
||||
use crate::load::{load_module, load_module_from_source};
|
||||
|
||||
pub use browser_session::{value_as_json, BrowserSession};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum Backend {
|
||||
#[default]
|
||||
|
||||
+21
@@ -124,6 +124,11 @@ enum Commands {
|
||||
#[arg(long)]
|
||||
check: bool,
|
||||
},
|
||||
/// Build browser WASM artifact (route C)
|
||||
Wasm {
|
||||
#[command(subcommand)]
|
||||
action: WasmAction,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
@@ -142,6 +147,16 @@ enum ExtAction {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum WasmAction {
|
||||
/// `cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release` and copy `.wasm`
|
||||
Build {
|
||||
/// Destination directory (default: examples/browser-hello)
|
||||
#[arg(short = 'o', long = "out", default_value = "examples/browser-hello")]
|
||||
out: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum ViewAction {
|
||||
/// Write static HTML documentation site
|
||||
@@ -282,5 +297,11 @@ fn try_main() -> Result<i32> {
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
Commands::Wasm { action } => match action {
|
||||
WasmAction::Build { out } => {
|
||||
marqdo::wasm_cli::build_wasm(&out)?;
|
||||
Ok(0)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! `marqdo wasm build` — compile `marqdo-wasm` and copy the `.wasm` artifact.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
|
||||
/// Build release wasm32 artifact and copy `marqdo_wasm.wasm` into `out_dir`.
|
||||
pub fn build_wasm(out_dir: &Path) -> Result<()> {
|
||||
let status = Command::new("cargo")
|
||||
.args([
|
||||
"build",
|
||||
"-p",
|
||||
"marqdo-wasm",
|
||||
"--target",
|
||||
"wasm32-unknown-unknown",
|
||||
"--release",
|
||||
])
|
||||
.status()
|
||||
.context("failed to spawn cargo (is it on PATH?)")?;
|
||||
if !status.success() {
|
||||
bail!("cargo build -p marqdo-wasm failed with {status}");
|
||||
}
|
||||
|
||||
let artifact = find_wasm_artifact()?;
|
||||
std::fs::create_dir_all(out_dir)
|
||||
.with_context(|| format!("create {}", out_dir.display()))?;
|
||||
let dest = out_dir.join("marqdo_wasm.wasm");
|
||||
std::fs::copy(&artifact, &dest).with_context(|| {
|
||||
format!(
|
||||
"copy {} → {}",
|
||||
artifact.display(),
|
||||
dest.display()
|
||||
)
|
||||
})?;
|
||||
println!("wrote {}", dest.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_wasm_artifact() -> Result<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
if let Ok(td) = std::env::var("CARGO_TARGET_DIR") {
|
||||
candidates.push(
|
||||
PathBuf::from(td)
|
||||
.join("wasm32-unknown-unknown/release/marqdo_wasm.wasm"),
|
||||
);
|
||||
}
|
||||
candidates.push(PathBuf::from(
|
||||
"target/wasm32-unknown-unknown/release/marqdo_wasm.wasm",
|
||||
));
|
||||
// Workspace may place target next to crates when invoked oddly — still try root.
|
||||
for c in &candidates {
|
||||
if c.is_file() {
|
||||
return Ok(c.clone());
|
||||
}
|
||||
}
|
||||
bail!(
|
||||
"built wasm not found; tried: {}",
|
||||
candidates
|
||||
.iter()
|
||||
.map(|p| p.display().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user