Compare commits
11
Commits
ext-v1.3.2
...
v1.4.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bb16dd6db | ||
|
|
58ec2172d6 | ||
|
|
66926e9e0a | ||
|
|
dcf4c05663 | ||
|
|
f47a1e143a | ||
|
|
9cf98a98b5 | ||
|
|
f99d552d87 | ||
|
|
7d49c358c1 | ||
|
|
a32c0cd78f | ||
|
|
0a8f76d9b4 | ||
|
|
4e2419b598 |
No files matched your search
@@ -113,8 +113,10 @@ printf '%s\n' '{"id":5,"method":"repair_targets","params":{"code":"contract.arg_
|
|||||||
| `****` / whole-line `**` / `*None*` | Return `None` and end function body |
|
| `****` / whole-line `**` / `*None*` | Return `None` and end function body |
|
||||||
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
|
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
|
||||||
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
|
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
|
||||||
| `- [item](coll)` | Foreach (unchanged) |
|
| `` ```lang `` | Foreign code block (via `lib/foreign`); bind with `` `name` = `` then fence |
|
||||||
| `` ```lang `` | Foreign code block (via `lib/foreign`) |
|
| `$$` + `% marqdo: var=name` | Block formula bind (TeX comment; prefer over empty RHS) |
|
||||||
|
| `- [item](coll)` | Foreach (**preferred**, nestable). Sugar: `- 对`coll`的每一项`item`` / `- for each `item` in `coll`` |
|
||||||
|
| `` | Image writeback form (validated stem.ext / URL); text writeback stays HTML comment |
|
||||||
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
|
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
|
||||||
| Unmarked prose | Comment |
|
| Unmarked prose | Comment |
|
||||||
|
|
||||||
@@ -138,20 +140,19 @@ Chinese builtins (same functions, no import):
|
|||||||
|
|
||||||
## Functions, calls, end-body
|
## Functions, calls, end-body
|
||||||
|
|
||||||
|
Prefer **body-inferred params** and **prose-unified** wording (v0.3). `` + `name` `` still works, but teach the inferred form first:
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# main
|
# main
|
||||||
|
|
||||||
> greet who=Marqdo
|
**greet who="Marqdo"**
|
||||||
|
|
||||||
## greet
|
## greet
|
||||||
+ `who`
|
|
||||||
|
|
||||||
> print text=Hello, `who`!
|
When we meet`who`, we **print text="Hello, `who`!"** and close with*None*.
|
||||||
|
|
||||||
*None*
|
|
||||||
```
|
```
|
||||||
|
|
||||||
- Call: `> name key=value` or `> name value`.
|
- Call: `**fn key="text"**` (bold; quote text literals) or `> fn key=text` (standalone `>`; bare words are text).
|
||||||
- Nested helpers use deeper `#` (`##`, `###`, …).
|
- Nested helpers use deeper `#` (`##`, `###`, …).
|
||||||
- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped).
|
- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped).
|
||||||
- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`).
|
- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`).
|
||||||
@@ -163,9 +164,8 @@ Chinese builtins (same functions, no import):
|
|||||||
**y = x + 2**
|
**y = x + 2**
|
||||||
|
|
||||||
## add_one
|
## add_one
|
||||||
+ `n`
|
|
||||||
|
|
||||||
*n + 1*
|
For input`n`, do **n = n + 1** and return*n*.
|
||||||
```
|
```
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
|
|||||||
@@ -126,6 +126,12 @@ jobs:
|
|||||||
## Marqdo ${{ github.ref_name }}
|
## Marqdo ${{ github.ref_name }}
|
||||||
|
|
||||||
### 亮点 / Highlights
|
### 亮点 / Highlights
|
||||||
|
- **v1.4.1**:view 标注连线——SVG mid→mid(underline 底中 → chip 顶中)· 帧 chip id 对齐 · L→R 密度
|
||||||
|
- **v1.4.1**: View annot leaders — SVG mid→mid (mark bottom-center → chip top-center), frame chip id unify, L→R density
|
||||||
|
- **v1.4.0**:叙述统一——`% marqdo: var=` · 臂/循环体叙述 · foreach 中英糖 · 图片自写回 · view 推断形参
|
||||||
|
- **v1.4.0**: Prose-unified control flow — formula meta bind, arm/loop narrative, foreach sugar, image writeback, inferred-param view
|
||||||
|
- **v1.3.3**:view 文档面 Structure——叙述保真 · 标记面 · 调用/循环帧 · `#mq-view-trace` · 静态站同源
|
||||||
|
- **v1.3.3**: Browse document-surface Structure — narration, markers, call/loop frames, `#mq-view-trace`, static site parity
|
||||||
- **v1.3.0**:Engineering Knowledge Compiler——L0–L4 · `reuse`/`find`/`duplicate` · Agent preflight(REUSE→ADAPT→CREATE)
|
- **v1.3.0**:Engineering Knowledge Compiler——L0–L4 · `reuse`/`find`/`duplicate` · Agent preflight(REUSE→ADAPT→CREATE)
|
||||||
- **v1.3.0**: Engineering Knowledge Compiler — L0–L4 catalog, reuse/find/duplicate, Agent preflight (REUSE→ADAPT→CREATE)
|
- **v1.3.0**: Engineering Knowledge Compiler — L0–L4 catalog, reuse/find/duplicate, Agent preflight (REUSE→ADAPT→CREATE)
|
||||||
- **v1.2.0**:Web Artifact(ADR 0007)——Document/Endpoint · `web.serve`/`render`/`inspect` · `ext/data|security|net` · 移除 `compose_*`/`configure`
|
- **v1.2.0**:Web Artifact(ADR 0007)——Document/Endpoint · `web.serve`/`render`/`inspect` · `ext/data|security|net` · 移除 `compose_*`/`configure`
|
||||||
|
|||||||
@@ -8,6 +8,91 @@
|
|||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
|
## v1.4.1 — 2026-10-15
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
**view 叙述标注连线**:Browse / `view output` 中 underline→chip 改为 SVG 正交连线(描述底边中点 → 轨道 → 短竖线 → 值顶边中点);同跨度多帧 chip 共用 annot id;可见 chip 按锚点 L→R;帧切换后重算密度。设计:[view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md)。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout v1.4.1 && cargo build --release
|
||||||
|
marqdo view public/00-welcome.mq.md --no-open
|
||||||
|
marqdo view output public -o /tmp/mq-public
|
||||||
|
# Ubuntu: sudo apt update && sudo apt install marqdo
|
||||||
|
marqdo ext add web # CDN latest → 1.4.1
|
||||||
|
```
|
||||||
|
|
||||||
|
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(view 标注几何与帧 chip 对齐),不触碰语言标记。
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- 设计缺口文档 [view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md):叙述 fence 卡、帧感知 chip 密度、L-leader 几何约定。
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- view L-leader:id 与 mark 错配、chip 逆序交叉、border 无色变黑碎段、横线穿过 chip 文字;现为 mid→mid SVG path。
|
||||||
|
- 叙述 fence / 代码卡单层渲染;静态页隐藏 Run;主文函数引用 call chip + leader。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- CLI / wasm / `ext/VERSION` **同步 1.4.1**。
|
||||||
|
|
||||||
|
## v1.4.0 — 2026-10-15
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
**叙述统一 + 公式 meta + 图片自写回**:块公式 `% marqdo: var=`;分支/循环体与函数体同权叙述;foreach 中英糖;自写回图片 ``(扩展名校验)与 view/静态站同源标记;view 展示推断形参实值;欢迎页迁到 v0.3 叙述面。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout v1.4.0 && cargo build --release
|
||||||
|
marqdo run tests/markup-v03/formula-meta-var.mq.md
|
||||||
|
marqdo run tests/markup-v03/foreach-narrative.mq.md
|
||||||
|
marqdo view tests/view/document-annot-demo.mq.md --no-open
|
||||||
|
# Ubuntu: sudo apt update && sudo apt install marqdo
|
||||||
|
marqdo ext add web # CDN latest → 1.4.0
|
||||||
|
```
|
||||||
|
|
||||||
|
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。Language 层在既有 `formula` / `branch-list` / `loop-list` 上扩展语义(块公式 TeX 注释绑定、臂/循环体叙述、foreach 糖);Runtime:自写回图片形态 + view 推断形参展示。设计:[fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md)。
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **块公式 meta 绑定**:`$$` 内 `% marqdo: var=<ident>`(剥离后解析;可无空 RHS);金样 `tests/markup-v03/formula-meta-var.mq.md`。
|
||||||
|
- **控制流叙述统一**:臂/循环体 `parse_indented_body` 与函数体同权;分支条件行支持叙述前缀与行内 `**…**`;foreach 糖 `- 对…的每一项…` / `- for each … in …`。
|
||||||
|
- **图片自写回**:路径/URL 且扩展名合法 → ``;文本仍 HTML 注释;view / `view output` 同源样式卡与 `<img>`。
|
||||||
|
- **view 推断形参实值**:Browse 展示 body-inferred 参数绑定值;欢迎页 EN/ZH 迁 v0.3 叙述。
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- `ext/net/url.encode`:经 `lib/net` 包装,不再直接 `host_*`(金样 `ext_mq_md_never_calls_host`)。
|
||||||
|
- PPA 源包:`ppa-build-source.sh` 本地 `.orig` 已在 build-area 时跳过重复 `cp`。
|
||||||
|
- view:嵌套调用欢迎页与公式/代码卡渲染清理。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- CLI / wasm / `ext/VERSION` **同步 1.4.0**;词法评论段遇有序分支臂 / 循环头 / 图片自写回标记时断开,避免吞掉控制流行。
|
||||||
|
|
||||||
|
## v1.3.3 — 2026-10-15
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
**view 文档面 Structure**:Browse 保真叙述与标记面(变量/语句/返回无源码定界符);表/循环/分支结构块;语句后绑定值、分支命中臂、函数多调用与循环迭代下拉(默认末帧);`#mq-view-trace` AI JSON。静态 `marqdo view output` 与 live view **同源渲染**(含用户站 `public/` → gh-pages)。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout v1.3.3 && cargo build --release
|
||||||
|
marqdo view tests/view/document-annot-demo.mq.md --no-open
|
||||||
|
marqdo view output public -o public
|
||||||
|
# Ubuntu: sudo apt update && sudo apt install marqdo
|
||||||
|
marqdo ext add web # CDN latest → 1.3.3
|
||||||
|
```
|
||||||
|
|
||||||
|
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(view 文档面 + 帧选择),不触碰语言标记。
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Browse Structure 文档面**(`src/view/document.rs` · `annot.rs`):叙述保真、标记面、GFM 表 / `doc-loop` / `doc-branch`、CSS L-leader 标注带。
|
||||||
|
- **StmtEvent / CallFrame / LoopFrame** 静默轨迹:post-stmt 绑定、分支 `call_id`、循环 `分 = 分数表[i] · value`;调用/迭代 picker(源码常显,只滤 chip)。
|
||||||
|
- **`ViewExecutionReport`** JSON(`#mq-view-trace` · `/api/view-trace` · SSE `trace_json`)。
|
||||||
|
- 设计:[view-document-annotations.md](doc/design/view-document-annotations.md) · [view-execution-trace.md](doc/design/view-execution-trace.md) · [view-frame-selection.md](doc/design/view-frame-selection.md);样例 `tests/view/document-annot-demo.mq.md`。
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- 多调用分支 taken 混叠;调用切换误藏未执行臂源码;循环头重复 chip。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- CLI / wasm / `ext/VERSION` **同步 1.3.3**;静态导出与 live view 共用 `build_file_view` → 文档面。
|
||||||
|
|
||||||
## Ext pack v1.3.2 — 2026-10-13
|
## Ext pack v1.3.2 — 2026-10-13
|
||||||
|
|
||||||
### Highlights
|
### Highlights
|
||||||
|
|||||||
Generated
+2
-2
@@ -572,7 +572,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo"
|
name = "marqdo"
|
||||||
version = "1.3.0"
|
version = "1.4.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"assert_cmd",
|
"assert_cmd",
|
||||||
@@ -603,7 +603,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-wasm"
|
name = "marqdo-wasm"
|
||||||
version = "1.3.0"
|
version = "1.4.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"marqdo",
|
"marqdo",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "marqdo"
|
name = "marqdo"
|
||||||
version = "1.3.0"
|
version = "1.4.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
description = "Marqdo — Markdown markers as an interpreted programming language"
|
description = "Marqdo — Markdown markers as an interpreted programming language"
|
||||||
|
|||||||
@@ -149,15 +149,18 @@ marqdo catalog public -o .marqdo
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 现状(v1.3.0)
|
## 现状(v1.4.1)
|
||||||
|
|
||||||
|
- **view 标注连线(v1.4.1)**:underline→chip SVG mid→mid(底边中点→轨道→短竖线→顶边中点)· 帧 chip 共用 id · L→R 密度 · [view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md)
|
||||||
|
- **叙述统一 / 公式 meta / 图片自写回(v1.4.0)**:`% marqdo: var=` 块公式绑定 · 臂/循环体叙述与 foreach 中英糖 · `` 图片自写回 · view 推断形参实值 · [fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md)
|
||||||
|
- **view 文档面(v1.3.3)**:Browse Structure 叙述保真 · 标记面 · 分支/循环帧下拉 · AI `#mq-view-trace` · 静态 `view output` / gh-pages 同源 · [view-document-annotations.md](doc/design/view-document-annotations.md)
|
||||||
- **Engineering Knowledge(v1.3.0)**:EKC L0–L4 · `marqdo knowledge|find|reuse|duplicate|verify|…` · Agent `preflight` / REUSE→ADAPT→CREATE · [engineering-knowledge.md](doc/design/engineering-knowledge.md)
|
- **Engineering Knowledge(v1.3.0)**:EKC L0–L4 · `marqdo knowledge|find|reuse|duplicate|verify|…` · Agent `preflight` / REUSE→ADAPT→CREATE · [engineering-knowledge.md](doc/design/engineering-knowledge.md)
|
||||||
- **Web Artifact(v1.2.0 · ADR 0007)**:Document/Endpoint 一等公民(`type: web|endpoint`)· facade `page`/`route`/`serve`/`render`/`inspect`/`use` · Resource 拆到 `ext/data`/`security`/`net` · 统一 View 表 · 破坏性移除 `compose_*`/`configure`
|
- **Web Artifact(v1.2.0 · ADR 0007)**:Document/Endpoint 一等公民(`type: web|endpoint`)· facade `page`/`route`/`serve`/`render`/`inspect`/`use` · Resource 拆到 `ext/data`/`security`/`net` · 统一 View 表 · 破坏性移除 `compose_*`/`configure`
|
||||||
- **AI 栈(v1.1.1)**:`ext/ai/llm` 语义 `ask`/`stream`/`collect` · Artifact Metadata Binding(`${env|arg|sys|secret}`)· Agent Skill Compilation + Adaptive Routing · MCP stdio 客户端 + resume 检查点 · 可选 `plugins/llm` Transport ABI
|
- **AI 栈(v1.1.1)**:`ext/ai/llm` 语义 `ask`/`stream`/`collect` · Artifact Metadata Binding(`${env|arg|sys|secret}`)· Agent Skill Compilation + Adaptive Routing · MCP stdio 客户端 + resume 检查点 · 可选 `plugins/llm` Transport ABI
|
||||||
- **AI 原生闭环(v1.1.0)**:核心表面守卫(19 构造,单边改动 CI 必红)· **渐进式契约**(文档内嵌 `参数`/`返回`/`字段` 表 + 四边界校验 + `marqdo check` 防漂移)· **MLSP for AI**(`marqdo mlsp`:`locate`/`syntax`/`validate`/`repair_targets`/`repair_apply`/`schema`,AI 按需查语法而非背诵)· **结构化诊断**(`run --json`,错误即数据);验证见 [perf-validation-report-2026-09-23.md](doc/roadmap/perf-validation-report-2026-09-23.md)
|
- **AI 原生闭环(v1.1.0)**:核心表面守卫(19 构造,单边改动 CI 必红)· **渐进式契约**(文档内嵌 `参数`/`返回`/`字段` 表 + 四边界校验 + `marqdo check` 防漂移)· **MLSP for AI**(`marqdo mlsp`:`locate`/`syntax`/`validate`/`repair_targets`/`repair_apply`/`schema`,AI 按需查语法而非背诵)· **结构化诊断**(`run --json`,错误即数据);验证见 [perf-validation-report-2026-09-23.md](doc/roadmap/perf-validation-report-2026-09-23.md)
|
||||||
- 映射与解释器:**v0.3 语法宪法**(`**` 代码 / `*` 返回 / 叙述声明);Phase I 树遍历 + 字节码后端;金样例在 `tests/` 与 `tests/markup-v03/`
|
- 映射与解释器:**v0.3 语法宪法**(`**` 代码 / `*` 返回 / 叙述声明);Phase I 树遍历 + 字节码后端;金样例在 `tests/` 与 `tests/markup-v03/`
|
||||||
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
|
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
|
||||||
- **`marqdo view`**:文档浏览器(Structure + 函数大纲/搜索 + Execution + Variables 浮窗)
|
- **`marqdo view`**:文档浏览器(**文档面** Structure + 标注 / 调用·循环帧 + 函数大纲/搜索 + Execution + Variables 浮窗;`view output` 同构)
|
||||||
- **`marqdo debug`**:独立调试页(断点 / 单步 / locals;默认端口 7430;页面 favicon / 品牌使用官方 Logo)
|
- **`marqdo debug`**:独立调试页(断点 / 单步 / locals;默认端口 7430;页面 favicon / 品牌使用官方 Logo)
|
||||||
- **`marqdo catalog` / `sync`**:OKF 风格 YAML + 模块概念页(默认挂钩 EKC)
|
- **`marqdo catalog` / `sync`**:OKF 风格 YAML + 模块概念页(默认挂钩 EKC)
|
||||||
- **`marqdo knowledge` / `find` / `reuse` / `impact` / `conflicts` / `stale` / `duplicate` / `verify`**:Engineering Knowledge Compiler([engineering-knowledge.md](doc/design/engineering-knowledge.md))
|
- **`marqdo knowledge` / `find` / `reuse` / `impact` / `conflicts` / `stale` / `duplicate` / `verify`**:Engineering Knowledge Compiler([engineering-knowledge.md](doc/design/engineering-knowledge.md))
|
||||||
@@ -176,7 +179,7 @@ marqdo catalog public -o .marqdo
|
|||||||
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md))
|
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md))
|
||||||
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md)
|
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md)
|
||||||
|
|
||||||
### 如何使用最新 Marqdo(v1.3.0)
|
### 如何使用最新 Marqdo(v1.4.1)
|
||||||
|
|
||||||
**安装解释器(任选其一)**
|
**安装解释器(任选其一)**
|
||||||
|
|
||||||
@@ -191,7 +194,7 @@ marqdo catalog public -o .marqdo
|
|||||||
```bash
|
```bash
|
||||||
# 1) 源码安装(跟 tag 或 main)
|
# 1) 源码安装(跟 tag 或 main)
|
||||||
git clone https://github.com/cflmy/marqdo.git && cd marqdo
|
git clone https://github.com/cflmy/marqdo.git && cd marqdo
|
||||||
git checkout v1.3.0 # 或留在 main
|
git checkout v1.4.1 # 或留在 main
|
||||||
cargo build --release
|
cargo build --release
|
||||||
export PATH="$PWD/target/release:$PATH"
|
export PATH="$PWD/target/release:$PATH"
|
||||||
marqdo version
|
marqdo version
|
||||||
@@ -230,7 +233,7 @@ marqdo wasm build
|
|||||||
# → dist/wasm/ … 见 examples/browser-hello/
|
# → dist/wasm/ … 见 examples/browser-hello/
|
||||||
|
|
||||||
# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip
|
# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip
|
||||||
# https://github.com/cflmy/marqdo/releases/tag/v1.3.0
|
# https://github.com/cflmy/marqdo/releases/tag/v1.4.1
|
||||||
```
|
```
|
||||||
|
|
||||||
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
|
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "marqdo-wasm"
|
name = "marqdo-wasm"
|
||||||
version = "1.3.0"
|
version = "1.4.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
|
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
|
||||||
|
|||||||
Vendored
+23
@@ -1,3 +1,26 @@
|
|||||||
|
marqdo (1.4.1-1ppa1) noble; urgency=medium
|
||||||
|
|
||||||
|
* Marqdo 1.4.1: View annot leaders — SVG mid-to-mid (mark bottom-center
|
||||||
|
to chip top-center), unify frame chip ids, L-to-R chip density.
|
||||||
|
|
||||||
|
-- cflmy <pingan@cflmy.cn> Thu, 15 Oct 2026 20:40:00 +0800
|
||||||
|
|
||||||
|
marqdo (1.4.0-1ppa1) noble; urgency=medium
|
||||||
|
|
||||||
|
* Marqdo 1.4.0: Prose-unified control flow — block formula % marqdo: var=,
|
||||||
|
arm/loop narrative + foreach sugar, image writeback ,
|
||||||
|
view inferred-param values; welcome pages on v0.3 prose surface.
|
||||||
|
|
||||||
|
-- cflmy <pingan@cflmy.cn> Wed, 15 Oct 2026 15:53:00 +0800
|
||||||
|
|
||||||
|
marqdo (1.3.3-1ppa1) noble; urgency=medium
|
||||||
|
|
||||||
|
* Marqdo 1.3.3: Browse document-surface Structure — narration-preserving
|
||||||
|
markers, branch/loop frame pickers, ViewExecutionReport JSON; static
|
||||||
|
view output / gh-pages share the same render path as live view.
|
||||||
|
|
||||||
|
-- cflmy <pingan@cflmy.cn> Wed, 15 Oct 2026 13:20:00 +0800
|
||||||
|
|
||||||
marqdo (1.3.0-1ppa1) noble; urgency=medium
|
marqdo (1.3.0-1ppa1) noble; urgency=medium
|
||||||
|
|
||||||
* Marqdo 1.3.0: Engineering Knowledge Compiler (EKC) — L0–L4 catalog,
|
* Marqdo 1.3.0: Engineering Knowledge Compiler (EKC) — L0–L4 catalog,
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# 块公式元数据绑定 · 控制流叙述统一
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 状态 | Active |
|
||||||
|
| 日期 | 2026-10-15 |
|
||||||
|
| 相关 | [stdlib-math.md](stdlib-math.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 块公式 `% marqdo: var=`
|
||||||
|
|
||||||
|
在 `$$…$$` 块内用 **TeX 行注释**声明绑定名(渲染通常不可见;运行时剥离后解析公式体):
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
$$
|
||||||
|
% marqdo: var=f
|
||||||
|
x^2 - 2
|
||||||
|
$$
|
||||||
|
```
|
||||||
|
|
||||||
|
- 指令:`% marqdo:` + 空白 + `var=<ident>`;未知键 → Error。
|
||||||
|
- 可无前置 `` `f` = ``;若同时写空 RHS 与 `var=`,**同名允许、异名 Error**。
|
||||||
|
- **保留**旧空 RHS + 后随 `$$`。
|
||||||
|
- **不做**:行内 `$% marqdo:…$`;\`\`\` 代码围栏内语言注释 meta(本波)。
|
||||||
|
- 行内公式继续传统绑定:`` `g` = $x+1$ ``(单 `$…$` → `formula`)或 `` `g` = $$x+1$$ ``。
|
||||||
|
|
||||||
|
无名叙述区 `$$` 仍仅展示;可执行区裸块既无空 RHS 又无 `var=` → Error。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 臂 / 循环体叙述(与函数体同权)
|
||||||
|
|
||||||
|
`parse_indented_body` 与函数体相同:消费 `` `名` `` / `**代码**` / `*返回*`;纯叙述跳过。
|
||||||
|
斜体返回结束**当前臂或当前循环体**,不结束外层函数。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 循环头
|
||||||
|
|
||||||
|
| 面 | 写法 | 说明 |
|
||||||
|
|----|------|------|
|
||||||
|
| **推荐** | `- [项](xs)` / `- [`项`](`xs`)` | 支持嵌套 |
|
||||||
|
| 中文糖 | `- 对`xs`的每一项`项`` | 可选后缀「遍历」 |
|
||||||
|
| 英文糖 | `- for each `item` in `xs`` | 大小写不敏感 `for each` / `in` |
|
||||||
|
|
||||||
|
糖与链接头语义相同,可混用嵌套。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 分支条件行叙述
|
||||||
|
|
||||||
|
结构行仍以 `1.` / `2.` 开头。条件提取顺序:
|
||||||
|
|
||||||
|
1. 整段可解析为表达式(现状);
|
||||||
|
2. 行内粗体代码条件 `**`n` > 0**`;
|
||||||
|
3. 剥离「当/若/如果/when/if」与「时/则」后,将「大于/小于/等于…」映射为运算符再解析。
|
||||||
|
|
||||||
|
else:`N. *`(可夹「否则」等叙述,条件位仍为 `*`)。
|
||||||
|
禁止无标记自然语言整句当条件。
|
||||||
@@ -215,7 +215,9 @@ v0.3:
|
|||||||
| 表达式 `[键](集合)` | **取元**(与 foreach 同形;见 [collection-access-link.md](collection-access-link.md)) |
|
| 表达式 `[键](集合)` | **取元**(与 foreach 同形;见 [collection-access-link.md](collection-access-link.md)) |
|
||||||
| `修饰… [函数名] 实参…` | **方括号标记调用**(前置修饰 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md)) |
|
| `修饰… [函数名] 实参…` | **方括号标记调用**(前置修饰 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md)) |
|
||||||
| `` 集合[^键] `` | **过渡**:旧脚注取元(仍可用) |
|
| `` 集合[^键] `` | **过渡**:旧脚注取元(仍可用) |
|
||||||
| ` ```lang ` | 外联(不变) |
|
| ` ```lang ` | 外联(不变;绑定仍用 `` `名` = `` + 围栏) |
|
||||||
|
| `$$` 内 `% marqdo: var=名` | 块公式绑定([fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)) |
|
||||||
|
| `- 对`集`的每一项`项`` / `for each` | foreach 叙述糖;推荐 `- [项](集)` |
|
||||||
| 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) |
|
| 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) |
|
||||||
| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) |
|
| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) |
|
||||||
|
|
||||||
|
|||||||
@@ -34,7 +34,16 @@
|
|||||||
|
|
||||||
### 2.2 文档中的 `$$` = 公式赋值(与表格同构)
|
### 2.2 文档中的 `$$` = 公式赋值(与表格同构)
|
||||||
|
|
||||||
在可执行面用 **空 RHS 赋值** 后跟展示数学块,把公式绑到变量(与 `` `xs` = `` 后跟表格一致):
|
**推荐(块内元数据)**:在 `$$` 体内用 TeX 注释声明变量(见 [fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)):
|
||||||
|
|
||||||
|
````markdown
|
||||||
|
$$
|
||||||
|
% marqdo: var=f
|
||||||
|
sin(x) + x
|
||||||
|
$$
|
||||||
|
````
|
||||||
|
|
||||||
|
**兼容**:空 RHS 赋值后跟展示数学块(与 `` `xs` = `` 后跟表格一致):
|
||||||
|
|
||||||
````markdown
|
````markdown
|
||||||
# main
|
# main
|
||||||
@@ -52,13 +61,14 @@ $$
|
|||||||
也支持:
|
也支持:
|
||||||
|
|
||||||
- 单行围栏:下一行 `$$x^2 - 2$$`
|
- 单行围栏:下一行 `$$x^2 - 2$$`
|
||||||
- 同行 compact:`*`f` = $$x^2 - 2$$ *`
|
- 同行 compact:`*`f` = $$x^2 - 2$$ *`(历史面)
|
||||||
|
- 行内:`` `g` = $x+1$ `` 或 `` `g` = $$x+1$$ ``
|
||||||
|
|
||||||
**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。
|
**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。
|
||||||
|
|
||||||
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区若出现未挂在赋值上的裸 `$$` 围栏 → 报错,提示使用 `` `name` = `` + 围栏。
|
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区裸 `$$` 若既无空 RHS 又无 `% marqdo: var=` → 报错。
|
||||||
|
|
||||||
**行内 `$…$`:** v1 不做绑定;需要时用 `> formula text=…` 显式构造。
|
**行内 `$…$`:** 传统绑定 `` `名` = $…$ `` → `formula`;**不**使用 `$% marqdo:…$`(会破坏 Markdown/TeX 识别)。
|
||||||
|
|
||||||
### 2.3 从文本构造
|
### 2.3 从文本构造
|
||||||
|
|
||||||
|
|||||||
@@ -8,9 +8,11 @@
|
|||||||
|
|
||||||
## 定位
|
## 定位
|
||||||
|
|
||||||
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` 的 `<!-- marqdo-out … -->` → `marqdo view` 在对应语句下显示 **output-card**。普通 Markdown 预览不显示该区域。
|
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` → `marqdo view`(及静态 `view output`)在对应语句下显示 **output-card**,并在源码面用 **writeback** 样式标出块本身。
|
||||||
|
|
||||||
## 存储格式
|
## 存储格式(两种,可并存)
|
||||||
|
|
||||||
|
### 1. HTML 注释(文本 / 结构化输出)
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
*`n` = > len value=`xs` *
|
*`n` = > len value=`xs` *
|
||||||
@@ -30,11 +32,26 @@ pending
|
|||||||
-->
|
-->
|
||||||
```
|
```
|
||||||
|
|
||||||
- 注释内为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
|
### 2. Markdown 图片(生成图 / 审计友好)
|
||||||
|
|
||||||
|
当 `value` **看起来像图片引用**(扩展名 `.png` / `.jpg` / `.jpeg` / `.gif` / `.webp` / `.svg` / …,或 `data:image/…`)时,`record` **自动**写成:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|

|
||||||
|

|
||||||
|
```
|
||||||
|
|
||||||
|
- 普通 Markdown 预览即可看见图;view / 静态站额外加 writeback 标记与 output-card 中的 `<img>`。
|
||||||
|
- 非图片路径仍走注释块;把非图片硬写成 `` 时扫描会忽略(校验失败)。
|
||||||
|
- `list` / `scan_path` 结果带 `kind`: `comment` | `image`。
|
||||||
|
|
||||||
|
### 共用规则
|
||||||
|
|
||||||
|
- 标记字为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
|
||||||
- 默认在**调用行下方**插入或替换紧邻**无键**块
|
- 默认在**调用行下方**插入或替换紧邻**无键**块
|
||||||
- `at_end=true`:替换文件末尾的**无键**块
|
- `at_end=true`:替换文件末尾的**无键**块
|
||||||
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽(智能体单步用父调用行,即 `step` 语句下方);`ensure` 在缺失时写入占位且不覆盖已有正文。命名槽互不覆盖,也不使用文件末尾单块。
|
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽;`ensure` 在缺失时写入占位且不覆盖已有正文
|
||||||
- `line=` / `行=`:显式锚点行号。子任务 / 异步写回必须带上,否则会锚到子任务内部调用行。主机侧有全局互斥锁,写前从磁盘重读入口源,避免并发写互相覆盖。
|
- `line=` / `行=`:显式锚点行号;主机侧有全局互斥锁
|
||||||
|
|
||||||
### 替换跨度与空行
|
### 替换跨度与空行
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|---|---|
|
|---|---|
|
||||||
| 状态 | 已定 |
|
| 状态 | 已定 |
|
||||||
| 日期 | 2026-08-04 |
|
| 日期 | 2026-08-04 |
|
||||||
| 相关 | [view.md](view.md) · 源目录 [`public/`](../../public/) |
|
| 相关 | [view.md](view.md) · [view-static-interactive.md](view-static-interactive.md)(静态交互 / 公式代码视觉 · Proposal) · 源目录 [`public/`](../../public/) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -4,14 +4,14 @@
|
|||||||
|---|---|
|
|---|---|
|
||||||
| 状态 | **v1(独立 debug 页)** |
|
| 状态 | **v1(独立 debug 页)** |
|
||||||
| 日期 | 2026-08-05 |
|
| 日期 | 2026-08-05 |
|
||||||
| 相关 | [next-phase.md](../roadmap/next-phase.md) P3 · [view.md](view.md) · [pipeline-debug.md](pipeline-debug.md) |
|
| 相关 | [next-phase.md](../roadmap/next-phase.md) P3 · [view.md](view.md) · [view-document-annotations.md](view-document-annotations.md) · [pipeline-debug.md](pipeline-debug.md) |
|
||||||
|
|
||||||
## 分工
|
## 分工
|
||||||
|
|
||||||
| 命令 | 角色 |
|
| 命令 | 角色 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `marqdo view` | 文档浏览器:Structure + Execution + Source;函数大纲与搜索;**无断点** |
|
| `marqdo view` | 文档浏览器:**叙述保真文档面** Structure + Execution + Source;函数大纲与搜索;跑后引出标注;**无断点**(见 [view-document-annotations.md](view-document-annotations.md)) |
|
||||||
| `marqdo debug` | 调试宿主(默认端口 **7430**):IDE 式布局;**仅 live** |
|
| `marqdo debug` | 调试宿主(默认端口 **7430**):IDE 式布局;AST Structure + BP;**仅 live** |
|
||||||
|
|
||||||
静态 `gh-pages` / `view output` **不能**真断点。
|
静态 `gh-pages` / `view output` **不能**真断点。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
# View:文档面与结果引出标注
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 状态 | **Active** |
|
||||||
|
| 日期 | 2026-10-15 |
|
||||||
|
| 相关 | [view.md](view.md) · [view-debug.md](view-debug.md) · [view-markup-surface.md](view-markup-surface.md) · [view-execution-trace.md](view-execution-trace.md) · [view-frame-selection.md](view-frame-selection.md) · [view-prose-annot-gaps.md](view-prose-annot-gaps.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 动机
|
||||||
|
|
||||||
|
`.mq.md` 是叙述与程序的同一载体。`marqdo view` 的 Structure 必须**保真叙述**,并在可执行标记旁展示运行结果。
|
||||||
|
|
||||||
|
旧 Browse Structure 用 AST 卡片重建语句,并用 `emit_comments` 只插入**语句行之前**的注释。当叙述与 `**…**` / `*…*` / `` `名` `` 在同一行时,该行被 Stmt 占用,叙述被丢弃——信息密度接近 debug,不适合文档浏览。
|
||||||
|
|
||||||
|
## 2. 模式分工
|
||||||
|
|
||||||
|
| 命令 | Structure | 叙述 | 结果 |
|
||||||
|
|------|-----------|------|------|
|
||||||
|
| `marqdo view`(Browse) | **文档面** | 保留并为主 | 跑后引出标注(callout + CSS L-leader) |
|
||||||
|
| `marqdo debug` | AST 卡片 + BP gutter | 弱化/可折叠 | Variables / 步进;不做文档 callout |
|
||||||
|
|
||||||
|
断点与逐步执行**仅**在 debug。静态 `view output` 与 live view **共用** Browse 文档面渲染。
|
||||||
|
|
||||||
|
## 3. 视觉语法
|
||||||
|
|
||||||
|
```
|
||||||
|
文本段…… `变量` …… **语句** …… *返回*
|
||||||
|
━━━━━
|
||||||
|
│
|
||||||
|
└──→ 结果标注
|
||||||
|
```
|
||||||
|
|
||||||
|
1. 叙述正文正常排版(Markdown)。
|
||||||
|
2. 可执行片段高亮,并带底部分割线(underline)。
|
||||||
|
3. 段落下方 **annotation band** 放结果 callout。
|
||||||
|
4. **CSS L-leader**(绝对定位小盒 + `border-left` + `border-bottom`)连接锚点与 callout。**不使用 SVG。**
|
||||||
|
5. 拥挤 / 极窄屏 / `prefers-reduced-motion`:取消长横折,改为编号 keyed 列表。
|
||||||
|
|
||||||
|
关联强度(递减):同色 underline + callout 色条 + label → CSS L-leader → keyed 编号。
|
||||||
|
|
||||||
|
对齐 [view.md](view.md) HIG:系统字体、无外链、浅色、克制装饰。
|
||||||
|
|
||||||
|
## 4. 文档面渲染
|
||||||
|
|
||||||
|
实现:`src/view/document.rs`;Browse 入口经 `render_module_structure` 调用。
|
||||||
|
|
||||||
|
| 源内容 | 呈现 |
|
||||||
|
|--------|------|
|
||||||
|
| 纯叙述段 | Markdown HTML;无 `comment` badge / 厚卡片 |
|
||||||
|
| 含 `ProseBit` 的行 | 原文保留;Decl / BoldCode / ItalicReturn 包 `mark.mq-anchor`(字节偏移来自 `scan_prose_line`) |
|
||||||
|
| 整行结构(`#` / `>` / `-` / `1.` / 表) | 表面语法保真(见 [view-markup-surface.md](view-markup-surface.md));整句可作锚点 |
|
||||||
|
| 函数标题 | 轻量 heading + `id="fn-{line}"`(大纲跳转不变) |
|
||||||
|
|
||||||
|
Debug 仍走 `render_module_structure_mode(..., Debug)` 的 AST 卡片路径。
|
||||||
|
|
||||||
|
## 5. ViewAnnot
|
||||||
|
|
||||||
|
跑后(或 `--no-exec` 时为空)组装标注集,嵌入文档面 `data-*` 与 band HTML。
|
||||||
|
|
||||||
|
| 字段 | 含义 |
|
||||||
|
|------|------|
|
||||||
|
| `id` | 稳定短 id(页内唯一) |
|
||||||
|
| `kind` | `bind` · `return` · `call` · `expr` · `branch` · `loop` · `writeback` |
|
||||||
|
| `anchor_line` | 1-based 源行 |
|
||||||
|
| `anchor_byte_start` / `anchor_byte_end` | 行内字节范围(可选;整行锚点可省略 end) |
|
||||||
|
| `label` | 短标题(名 / return / arm / loop) |
|
||||||
|
| `value` | 截断显示 |
|
||||||
|
| `detail` | 完整文本(inspect) |
|
||||||
|
|
||||||
|
| kind | 数据来源 | 锚点 |
|
||||||
|
|------|----------|------|
|
||||||
|
| `bind` | **StmtEvent post-stmt**(赋值执行后的值);禁止用入口终态回填初始化行 | 该赋值行 |
|
||||||
|
| `return` | 返回事件或入口返回 | ItalicReturn / Return |
|
||||||
|
| `call` / `expr` / `writeback` | writeback 槽、调用摘要 | 语句行或 BoldCode |
|
||||||
|
| `branch` | `ViewTrace`:命中 arm、次数 | 条件 / arm |
|
||||||
|
| `loop` | `ViewTrace`:迭代次数、末次 item | While / ForEach 头 |
|
||||||
|
|
||||||
|
标记面、结构块、多调用帧与 AI JSON 见 [view-execution-trace.md](view-execution-trace.md)。
|
||||||
|
|
||||||
|
`ViewTrace` 由 tree 解释器在 capture 时静默收集,**不**写入 stderr;与 `trace_eval` 调试轨迹分离。Bytecode 后端可暂无 trace(标注降级为 writeback)。
|
||||||
|
|
||||||
|
## 6. 布局与密度
|
||||||
|
|
||||||
|
- 每段默认最多 **4** 个常显 callout;其余 hover / 「show more」。
|
||||||
|
- Leader:按锚点 x 排序 callout,避免交叉;窄屏改为短竖线 + 堆叠。
|
||||||
|
- 客户端:`ResizeObserver` 重算 leader 盒的 `left/top/width/height`。
|
||||||
|
- 静态导出:页载 JS 跑一次布局。
|
||||||
|
|
||||||
|
右侧 **Variables** 仍为全集绑定;callout 为就地摘要,点击可打开同一 inspect。
|
||||||
|
|
||||||
|
## 7. 非目标
|
||||||
|
|
||||||
|
- 不在 view 内做断点 / 单步(见 [view-debug.md](view-debug.md))。
|
||||||
|
- 不新增作者侧标注 DSL / frontmatter 指令。
|
||||||
|
- 不引入外链字体、npm 组件或 SVG leader。
|
||||||
|
- 不把 DB/auth 等塞进 view 壳层。
|
||||||
|
|
||||||
|
## 8. 验收
|
||||||
|
|
||||||
|
1. `inc-prose.mq.md`:叙述「对于输入变量…」完整可见;`n` / `n=n+1` / 返回高亮。
|
||||||
|
2. 跑完后:值经 underline + CSS L-leader 连到下方标注(无 SVG)。
|
||||||
|
3. 分支/循环样例:可见命中 arm 与迭代次数(有 ViewTrace 时)。
|
||||||
|
4. `marqdo debug` 仍为 AST + 断点;叙述不抢主视觉。
|
||||||
|
5. 无外链字体/新依赖;`view output` 可离线打开。
|
||||||
|
|
||||||
|
## 9. 修订历史
|
||||||
|
|
||||||
|
| 日期 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 2026-10-15 | 初稿:文档面、ViewAnnot、CSS L-leader、与 debug 分工 |
|
||||||
|
| 2026-10-15 | bind = post-stmt;交叉链 view-execution-trace |
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# View:执行轨迹与文档面保真
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 状态 | **Active** |
|
||||||
|
| 日期 | 2026-10-15 |
|
||||||
|
| 相关 | [view-document-annotations.md](view-document-annotations.md) · [view-frame-selection.md](view-frame-selection.md) · [view.md](view.md) · [view-markup-surface.md](view-markup-surface.md) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 目标
|
||||||
|
|
||||||
|
`marqdo view` Browse Structure 必须同时做到:
|
||||||
|
|
||||||
|
1. **标记面**:变量名 / 可执行语句 / 返回值按表面渲染(无源码定界符字面量)。
|
||||||
|
2. **结构块**:GFM 表、循环(`-`)、分支(`1.`)有正确 HTML 与缩进。
|
||||||
|
3. **语句后值**:赋值行标注该语句执行后的值,不用入口终态回填。
|
||||||
|
4. **执行臂**:高亮实际走的分支臂。
|
||||||
|
5. **多调用帧**:同函数多次调用可用下拉切换经历。
|
||||||
|
6. **AI 可读**:与 HTML 同源的 `ViewExecutionReport` JSON。
|
||||||
|
|
||||||
|
Debug 仍用 AST 卡片 + 断点;不做文档 callout。
|
||||||
|
|
||||||
|
## 2. 标记面
|
||||||
|
|
||||||
|
| 源标记 | 显示(无定界符) | class |
|
||||||
|
|--------|------------------|-------|
|
||||||
|
| `` `名` `` / `` `名`=默认 `` | `名`(默认次要后缀) | `mq-anchor mq-decl` |
|
||||||
|
| `**…**`(可执行) | 内层文本 | `mq-anchor mq-code` |
|
||||||
|
| `*…*`(返回) | 内层文本 | `mq-anchor mq-return` |
|
||||||
|
|
||||||
|
`data-byte-start/end` 仍为源码字节偏移(供 CSS L-leader)。软强调不进 anchor。
|
||||||
|
|
||||||
|
## 3. 结构块
|
||||||
|
|
||||||
|
| 块 | 呈现 |
|
||||||
|
|----|------|
|
||||||
|
| GFM 表 | `<table class="doc-table">` |
|
||||||
|
| `-` 循环 | `<ul class="doc-loop">`,体按源缩进 `--doc-indent` |
|
||||||
|
| `1.` 分支 | `<ol class="doc-branch">`;命中 `arm-taken`,未走 `arm-miss` |
|
||||||
|
| 公式 / 外联代码 | 现有 formula-card / code-card |
|
||||||
|
| `>` 调用 | 表面高亮,非整行灰 code |
|
||||||
|
|
||||||
|
## 4. StmtEvent / CallFrame
|
||||||
|
|
||||||
|
解释器 capture 时静默采集(非 `trace_eval` stderr):
|
||||||
|
|
||||||
|
```text
|
||||||
|
StmtEvent {
|
||||||
|
line, kind, // assign | return | call | branch | loop | bind_ref
|
||||||
|
name?, value_after?, // post-stmt 或求值结果
|
||||||
|
arm_index?, iter?,
|
||||||
|
call_id // 当前用户函数调用帧
|
||||||
|
}
|
||||||
|
|
||||||
|
CallFrame {
|
||||||
|
call_id, fn_name, fn_line, ordinal,
|
||||||
|
args_brief, // 短摘要供下拉
|
||||||
|
events[] // 或全局 events 用 call_id 过滤
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Assign → 写入后的值挂在**该行**。
|
||||||
|
- 循环内多次写入:UI 默认末次;可带次数。
|
||||||
|
- Branch → taken `arm_index` + 条件摘要。
|
||||||
|
- 进入用户函数分配 `call_id`;`# main` 单帧无下拉。
|
||||||
|
|
||||||
|
## 5. ViewExecutionReport(AI)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"path": "…",
|
||||||
|
"ok": true,
|
||||||
|
"calls": [{ "call_id": 1, "fn": "等级说明", "ordinal": 1, "args_brief": "等级=及格" }],
|
||||||
|
"events": [{ "line": 24, "kind": "assign", "name": "总分", "value_after": "0", "call_id": 0 }],
|
||||||
|
"bindings_final": { "均分": "73", "等级": "及格" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
产出:页内 `#mq-view-trace` JSON;live `GET /api/view-trace?path=`;SSE `done.trace_json`。
|
||||||
|
|
||||||
|
## 6. UI
|
||||||
|
|
||||||
|
- 函数标题旁 `<select class="call-picker">`(调用数 ≥ 2)。
|
||||||
|
- 循环头旁 `<select class="loop-picker">`(迭代数 ≥ 2);默认最后一轮;摘要 `分 = 分数表[i] · value`。
|
||||||
|
- **源码常显**:切换帧只改 chip / 臂高亮,不 `hidden` 结构节点。详见 [view-frame-selection.md](view-frame-selection.md)。
|
||||||
|
- CSS L-leader(非 SVG);拥挤 keyed 降级。
|
||||||
|
|
||||||
|
## 7. 验收
|
||||||
|
|
||||||
|
1. 无字面 `**` / 返回定界 `*` / 变量外层 `` ` ``(Source 除外)。
|
||||||
|
2. 表为真表格;循环/分支有缩进列表;未选中臂源码仍可见。
|
||||||
|
3. `总分 = 0` 标注 `0`,非终态累加。
|
||||||
|
4. 命中臂可视化;多调用下只显示当前帧的 taken。
|
||||||
|
5. 循环可按迭代切换;JSON 含 `loops`;单测覆盖。
|
||||||
|
|
||||||
|
## 8. 修订历史
|
||||||
|
|
||||||
|
| 日期 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 2026-10-15 | 初稿:标记面、结构块、StmtEvent、CallFrame、AI 报告 |
|
||||||
|
| 2026-10-15 | 帧选择保真:call_id 分支、LoopFrame、源码常显 |
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
# View:调用帧 / 循环帧选择与结构保真
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 状态 | **Active** |
|
||||||
|
| 日期 | 2026-10-15 |
|
||||||
|
| 相关 | [view-execution-trace.md](view-execution-trace.md) · [view-document-annotations.md](view-document-annotations.md) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 问题(对照实测)
|
||||||
|
|
||||||
|
1. **结构缺失**:切换函数调用下拉时,JS 按 `data-call-id` **隐藏** `.doc-exec`。未在本帧执行的分支臂体(赋值/返回)只有其它帧的 call_id,或仅有执行帧的 id → **未选中臂的源码被藏掉**,看起来像「臂消失 / 代码没渲染」。
|
||||||
|
2. **调用记录混叠**:`Branch` 标注未带 `call_id`;`taken_arms` 按行号只保留最后一次命中。多帧下同一分支同时出现 `arm 1 taken` 与 `arm 2 taken`。
|
||||||
|
3. **循环无帧**:循环只有总次数摘要;无法按迭代查看;`` - [分](分数表) `` 不能展示「当前是集合第几个元素」。
|
||||||
|
|
||||||
|
## 2. 定稿原则
|
||||||
|
|
||||||
|
| 原则 | 含义 |
|
||||||
|
|------|------|
|
||||||
|
| **源码常显** | 表 / 列表 / 分支臂 / 语句源码**永不**因帧选择 `hidden` |
|
||||||
|
| **轨迹随帧** | 标注 chip、臂高亮、变量值随「当前调用帧 / 当前迭代」变化 |
|
||||||
|
| **默认末帧** | 函数默认最后一次调用;循环默认最后一次迭代 |
|
||||||
|
| **一帧一真相** | 同时只展示一个 call_id(函数)或一个 (loop_id, iter)(循环)的轨迹 |
|
||||||
|
|
||||||
|
## 3. 函数调用帧
|
||||||
|
|
||||||
|
### 数据
|
||||||
|
|
||||||
|
`BranchHit` / 相关 `StmtEvent` 必须带 `call_id`。`ViewAnnot` 的 branch/bind/return 同样带 `call_id`。
|
||||||
|
|
||||||
|
### UI
|
||||||
|
|
||||||
|
- 函数标题旁 `<select class="call-picker" data-fn="…" data-scope="fn">`
|
||||||
|
- 选项:`1: 等级=及格` / `2: 等级=优秀`
|
||||||
|
- 默认选中最后一次
|
||||||
|
|
||||||
|
### 客户端(`applyCallFrame`)
|
||||||
|
|
||||||
|
1. 读 `#mq-view-trace` JSON。
|
||||||
|
2. 过滤 `events` where `call_id == selected`。
|
||||||
|
3. **不**设置结构节点 `hidden`。
|
||||||
|
4. 更新该函数作用域内:
|
||||||
|
- `.annot-chip[data-call-id]`:仅显示匹配帧;无 call_id 的结构说明类可保留
|
||||||
|
- `.doc-branch[data-line]`:按该帧的 branch 事件设置 `arm-taken` / `arm-miss`(全部臂仍可见)
|
||||||
|
- 绑定 chip 的 `.annot-value`:用该帧 assign/return 事件刷新(同名同行取末次)
|
||||||
|
|
||||||
|
## 4. 循环迭代帧
|
||||||
|
|
||||||
|
### 数据
|
||||||
|
|
||||||
|
```text
|
||||||
|
LoopFrame {
|
||||||
|
loop_id, line,
|
||||||
|
item_name?, // "分"
|
||||||
|
collection?, // "分数表"
|
||||||
|
iterations: [{ index, item_value, call_id }] // index 0-based
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`StmtEvent` 增加可选 `loop_id`;循环体内事件带 `iter`(1-based 或 0-based,JSON 内统一 **0-based index**)。
|
||||||
|
|
||||||
|
### UI
|
||||||
|
|
||||||
|
- 循环头(`- [分](分数表)`)旁:`<select class="loop-picker" data-loop-id="…">`
|
||||||
|
- 选项:`迭代 1: 分=92` … `迭代 4: 分=88`
|
||||||
|
- 默认最后一次
|
||||||
|
- 头旁摘要 chip:`分 = 分数表[3] · 88`(下标 0-based 显示为 `[i]`)
|
||||||
|
|
||||||
|
### 客户端(`applyLoopFrame`)
|
||||||
|
|
||||||
|
1. **只显示当前迭代**:带 `data-iter` 的 chip 仅保留选中项;其余 `hidden` + `is-frame-hidden`(SSR 默认已按末轮预隐藏)。
|
||||||
|
2. 更新头摘要 chip(无 `data-iter`)为当前选项文案。
|
||||||
|
3. 不隐藏循环体源码。
|
||||||
|
|
||||||
|
## 5. 分支臂渲染
|
||||||
|
|
||||||
|
- 所有臂(含 else)**始终**渲染完整头 + 体(含 `*返回*` / 赋值)。
|
||||||
|
- `arm-miss` 仅降低不透明度,**不** `display:none` / `hidden`。
|
||||||
|
- 高亮仅反映**当前帧**的 taken `arm_index`。
|
||||||
|
|
||||||
|
## 6. AI JSON 增量
|
||||||
|
|
||||||
|
`ViewExecutionReport` 增加:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"loops": [{
|
||||||
|
"loop_id": 1,
|
||||||
|
"line": 27,
|
||||||
|
"item": "分",
|
||||||
|
"collection": "分数表",
|
||||||
|
"iters": [{ "index": 0, "value": "92" }, { "index": 3, "value": "88" }]
|
||||||
|
}]
|
||||||
|
```
|
||||||
|
|
||||||
|
`events[].call_id` 必填;循环体内事件带 `loop_id` + `iter`(index)。
|
||||||
|
|
||||||
|
## 7. 验收
|
||||||
|
|
||||||
|
1. 未选中分支臂源码始终可见(含返回句)。
|
||||||
|
2. 切换「等级说明」调用:只显示该帧的 arm taken;变量/返回值对应该帧。
|
||||||
|
3. 循环下拉默认最后一轮;`分 = 分数表[3] · 88`;切换迭代后体内累加值变化。
|
||||||
|
4. `#mq-view-trace` 含 `loops` 与带 `call_id` 的 branch 事件。
|
||||||
|
5. `cargo test --lib view::` 全绿。
|
||||||
|
|
||||||
|
## 8. 开发计划(已执行)
|
||||||
|
|
||||||
|
| 阶段 | 内容 | 状态 |
|
||||||
|
|------|------|------|
|
||||||
|
| D0 | 本文档 + `view-execution-trace.md` 交叉引用 | ✅ |
|
||||||
|
| D1 | `BranchHit.call_id`;`LoopFrame` / `LoopIter`;`StmtEvent.loop_id` | ✅ |
|
||||||
|
| D2 | 解释器:foreach/while 推栈;BindRef `分=分数表[i]`;assign 带 iter | ✅ |
|
||||||
|
| D3 | `build_view_annots`:分支带 call_id;LoopFrame 选项;报告 JSON `loops` | ✅ |
|
||||||
|
| D4 | 文档面:源码不贴 `data-call-ids`;call picker `value=call_id`;loop picker;SSR taken=末帧 | ✅ |
|
||||||
|
| D5 | JS:`applyCallFrame` / `applyLoopFrame` — 只滤 chip + 重算 arm,不 hidden 结构 | ✅ |
|
||||||
|
| D6 | 单测:多调用不同臂、loop 末项、HTML 三臂返回 + picker | ✅ |
|
||||||
|
|
||||||
|
## 9. 修订历史
|
||||||
|
|
||||||
|
| 日期 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 2026-10-15 | 初稿:源码常显、帧过滤、循环迭代 picker |
|
||||||
|
| 2026-10-15 | 按计划落地 D1–D6 |
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
# View:叙述面标注缺口(prose annot gaps)
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 状态 | **Active** |
|
||||||
|
| 日期 | 2026-10-15 |
|
||||||
|
| 相关 | [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [view-frame-selection.md](view-frame-selection.md) · [view-execution-trace.md](view-execution-trace.md) |
|
||||||
|
|
||||||
|
> **定位**:对既有文档面设计的**缺口专章**——写清用户可见的四类问题、根因(文件:行)与验收口径。不改写 ADR;不发明作者侧标注 DSL。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 为何「改了却几乎没变化」
|
||||||
|
|
||||||
|
| 原因 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 错二进制 | PATH 上的 `marqdo` 可能仍是旧版(如 1.3.0);改动在源码 / `./target/debug/marqdo`。验收必须用 `cargo build && ./target/debug/marqdo view …` |
|
||||||
|
| Chip 被溢出藏掉 | 同 band 堆多帧 return/print/who;`MAX_VISIBLE_ANNOTS=4` 把当前帧的 `who` 打成 `annot-chip-overflow`(`display:none`);帧切换不重算溢出 |
|
||||||
|
| L-leader 几何错位 | `initAnnotLeaders` 里 `y0=0` 只在 `.annot-band` 顶画短折,**连不到**上方 underline;窄屏或 chip>4 时整段关掉 leaders |
|
||||||
|
| 旧静态快照 | gh-pages / 旧 `view output` 不会自动刷新 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 目标视觉语法(既有,不新造)
|
||||||
|
|
||||||
|
锚定 [view-document-annotations.md](view-document-annotations.md) §3:
|
||||||
|
|
||||||
|
```
|
||||||
|
文本段…… `变量` …… **语句** …… *返回*
|
||||||
|
━━━━━
|
||||||
|
│
|
||||||
|
└──→ 结果标注 chip
|
||||||
|
```
|
||||||
|
|
||||||
|
- underline:`mark.mq-anchor.mq-{decl|code|return}`
|
||||||
|
- band:段落下方 `.annot-band` → leaders + chips
|
||||||
|
- L-leader:CSS `border-left` + `border-bottom`(禁止 SVG)
|
||||||
|
- 公式/代码:[view-static-interactive.md](view-static-interactive.md) G3 **一层主视觉**;卡下不叠 Bind dump
|
||||||
|
- 帧:[view-frame-selection.md](view-frame-selection.md) **源码常显、只滤 chip**;默认末帧
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 管线
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
CLI["marqdo view / view output"] --> build["build_file_view"]
|
||||||
|
build --> cap["run_file_capture"]
|
||||||
|
cap --> annot["build_view_annots"]
|
||||||
|
annot --> doc["document::render_module_document"]
|
||||||
|
doc --> page["html.rs page_file"]
|
||||||
|
page --> js["initAnnotLeaders + initCallPickers"]
|
||||||
|
```
|
||||||
|
|
||||||
|
| 步骤 | 位置 |
|
||||||
|
|------|------|
|
||||||
|
| CLI / 导出 | `src/main.rs` · `src/view/mod.rs` · `src/view/output.rs` |
|
||||||
|
| Capture + Call 事件 | `src/interp.rs` |
|
||||||
|
| Annot 组装 | `src/view/annot.rs` `build_view_annots` |
|
||||||
|
| 文档面 HTML | `src/view/document.rs` |
|
||||||
|
| 卡片 chrome | `src/view/render.rs` `render_*_assign_card` |
|
||||||
|
| CSS / leader JS | `src/view/html.rs` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 四条用户问题 → 根因 → 验收
|
||||||
|
|
||||||
|
复现源:`public/00-welcome.mq.md` · `public/00-欢迎.mq.md`
|
||||||
|
对照金样:`tests/view/document-annot-demo.mq.md` · `tests/markup-v03/inc-prose.mq.md`
|
||||||
|
|
||||||
|
### P1 — 叙述与代码同段时信息不显示
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 现象 | underline 在,chip / 连线弱或无 |
|
||||||
|
| 根因 | `html.rs` `initAnnotLeaders`:`y0=0` 相对 band;`document.rs` `MAX_VISIBLE_ANNOTS` 把当前帧 chip 溢出;PATH 旧 CLI |
|
||||||
|
| 目标 | 同 `inc-prose`:underline + L-leader(从锚点底到 chip)+ 可见 chip |
|
||||||
|
| 验收 | `./target/debug/marqdo view public/00-welcome.mq.md`:主文 `**greet…**` 与 `## greet` 体内均有可见 chip 与接到 underline 的 leader(宽屏) |
|
||||||
|
|
||||||
|
### P2 — 函数内变量不显示
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 现象 | `` `who` `` 有浅蓝 underline,无值 chip |
|
||||||
|
| 根因 | bind chip 存在但带 `annot-chip-overflow`;`applyCallFrame` 只 `hidden` 非选中帧,不解除当前帧 overflow |
|
||||||
|
| 目标 | 选中调用帧时常显 `who` · `print` · `return` 各一枚 |
|
||||||
|
| 验收 | 切换「调用」下拉,三枚 chip 随帧变且默认可见(无需点 +N) |
|
||||||
|
|
||||||
|
### P3 — ` ```text ` 渲染不一致
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 现象 | 变成内联 `text marqdo ext add…`,无卡片 |
|
||||||
|
| 根因 | Comment 围栏若进 `flush_para` → `join(" ")` → pulldown 当 inline code;应走 `render_narrative_fence` |
|
||||||
|
| 目标 | 与 bound python 同 `.code-card` chrome(badge + `pre.code-body`),**无** Run/foot |
|
||||||
|
| 验收 | welcome install 段:`data-lang="text"` + 两行 `marqdo ext add`;无 `<code>text marqdo` |
|
||||||
|
|
||||||
|
### P4 — 函数引用 / 代码卡未渲染
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 现象 | `**greet who=…**` 无结果;或 `hi` python 只见头/Run、不见源码 |
|
||||||
|
| 根因 | 同行多 Call 未与 BoldCode zip;或 Run 挤在 head;静态假 Run;错看 Debug 路径 |
|
||||||
|
| 目标 | 主文两 greet 各有 call chip(stdout 摘要);`hi` = `render_code_assign_card` head→body→foot;静态藏 Run |
|
||||||
|
| 验收 | 两枚 greet mark 均有非空 `data-annot-id`;`code-body` 含 `hello-from-python`;`MARQDO_VIEW_LIVE=false` 无 Run 按钮 |
|
||||||
|
|
||||||
|
### call_id 语义(写死)
|
||||||
|
|
||||||
|
| 位置 | call_id |
|
||||||
|
|------|---------|
|
||||||
|
| 主文 `**greet…**` 的 call chip | 入口帧(`# main` 的 call);结果为 stdout/返回摘要 |
|
||||||
|
| `## greet` 体内 print / who / return | callee 的 CallFrame id;跟函数标题旁 picker |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 修复约定(实现红线)
|
||||||
|
|
||||||
|
1. **帧感知密度**:band 内按选中 `call_id` 计可见 chip;默认末帧;同帧最多 4 枚常显;溢出只藏非当前帧或多余 kind。切换后客户端重算 overflow + `layoutAll()`。
|
||||||
|
2. **Leader 容器**:提升到 `.doc-block`(prose + band);`y0` = 锚点底相对 block;按锚点 x 排序再画线。
|
||||||
|
3. **卡片**:只复用 Browse `render_*_assign_card` / `render_narrative_fence` + `html.rs` `.code-*` / `.formula-card`;本波不改 Debug AST 路径(除非回归红)。
|
||||||
|
4. **静态 Run**:`MARQDO_VIEW_LIVE=false` 时隐藏 Run,不留禁用假按钮(对齐 view-static-interactive D5)。
|
||||||
|
5. **非目标**:不做 debug 断点;不发明作者标注 DSL;不用 SVG leader;不单独发版/推 gh-pages(除非另嘱)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 验收命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo build -q
|
||||||
|
./target/debug/marqdo version # 须为当前工作树版本
|
||||||
|
./target/debug/marqdo view public/00-welcome.mq.md --no-open
|
||||||
|
./target/debug/marqdo view tests/view/document-annot-demo.mq.md --no-open
|
||||||
|
cargo test -q --lib view::
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 修订历史
|
||||||
|
|
||||||
|
| 日期 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 2026-10-15 | 初稿:四问题、错二进制/溢出/leader 根因、帧感知密度与 leader 几何约定 |
|
||||||
|
| 2026-10-15 | L-leader 拥挤/消失:同跨度多帧 chip **共用 annot id**;可见 chip 按锚点 x 重排;leader 挂 doc-block |
|
||||||
|
| 2026-10-15 | L-leader 黑线碎段:JS `border*: "1.5px solid"` 无色覆盖 class → 改为 kind 色写入 shorthand;chip SSR/DOM 按锚点 L→R |
|
||||||
|
| 2026-10-15 | L-leader 改为 SVG:描述底边中点 → 轨道 → 短竖线 → 值 chip 顶边中点;chip 间距加宽 |
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
# View:静态页交互与公式/代码卡视觉
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| 状态 | **Active** |
|
||||||
|
| 日期 | 2026-10-15 |
|
||||||
|
| 相关 | [view.md](view.md) · [user-site.md](user-site.md) · [view-document-annotations.md](view-document-annotations.md) · [view-frame-selection.md](view-frame-selection.md) · [ADR 0002 browser WASM](../adr/0002-browser-marqdo-wasm.md) |
|
||||||
|
|
||||||
|
**已确认(2026-10-15)**
|
||||||
|
|
||||||
|
| 决策 | 选择 |
|
||||||
|
|------|------|
|
||||||
|
| 引擎 | **B**(快照 + S1 帧切换 + 可选懒加载 WASM S2) |
|
||||||
|
| 体验原则 | 静态页与 live view **尽量同构**;控件形态对齐;无服务端时用 WASM/JS 补齐 |
|
||||||
|
| 视觉原则 | **一层主视觉**;一眼能懂;公式/代码不与 Bind chip / 源残留叠床架屋 |
|
||||||
|
| 演示参数条 | **要**(历史实参 select + 可编辑;S1 切帧 / S2 重跑) |
|
||||||
|
| code-card Run | 有 WASM 时可用;否则隐藏(不对齐「假按钮」) |
|
||||||
|
| 公式 Bind chip | **卡内不显示**;Variables 可留终值 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 动机(对照 `public/00-欢迎.mq.md` / gh-pages)
|
||||||
|
|
||||||
|
静态导出(`marqdo view output` → `gh-pages`)与 live `marqdo view` 已共用**文档面 Structure** 渲染路径,但用户站实测仍有三类落差:
|
||||||
|
|
||||||
|
1. **交互控件缺失 / 偏弱**
|
||||||
|
- 函数「问候」仅有参数 chip「谁」,没有可切换的调用帧下拉(即便源里 `> 问候` 写了两次)。
|
||||||
|
- 参数行 `+ 谁` 在文档面呈声明高亮,读者无法在静态页改「谁」并看到新输出。
|
||||||
|
- 外联 `code-card` 的 Run 在静态模式被禁用(`Run is available in live marqdo view`)。
|
||||||
|
- 静态 stdin 仅在有 preset 时显示只读提示,**不能**再跑。
|
||||||
|
|
||||||
|
2. **无服务端时仍可交互的预期**
|
||||||
|
用户站是纯静态托管:没有 `/api/run`。合理路径是 **页内 JS** 和/或 **嵌入 Marqdo WASM**,在浏览器里重算 Structure 标注、Execution 区,甚至模拟 `input` / 外联(沙箱约束另定)。
|
||||||
|
|
||||||
|
3. **公式 / 代码块视觉凌乱**
|
||||||
|
同一赋值同时出现多层表象,信息重复、线框错位:
|
||||||
|
|
||||||
|
| 层 | 公式 `f = $$…$$` | 外联 `hi = ```python…``` |
|
||||||
|
|----|------------------|---------------------------|
|
||||||
|
| A 卡片 | `formula` badge + KaTeX | `code` badge + 高亮源码 + cmd/Run |
|
||||||
|
| B 标注 chip | `f` → `x^2 - 2` | `hi` → 整段 fence 摘要 |
|
||||||
|
| C 源残留 | 卡片外/旁再露 `$$` 或 ASCII | 卡片下再露 `python print…` 明文 |
|
||||||
|
|
||||||
|
再叠加 CSS L-leader 与卡内边框,首屏显得碎、重复、「坏掉的线」。
|
||||||
|
|
||||||
|
**本文件只定问题与方案;确认前不改代码。**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 现状解剖
|
||||||
|
|
||||||
|
### 2.1 静态 vs live(同一 `page_file`)
|
||||||
|
|
||||||
|
| 能力 | Live | Static(`LinkMode::Static`) |
|
||||||
|
|------|------|------------------------------|
|
||||||
|
| 文档面 Structure + annot | ✅(跑后) | ✅(导出时跑后写入) |
|
||||||
|
| call / loop picker JS | ✅(读 `#mq-view-trace`) | ✅(同源 JS;若轨迹未写入则无控件) |
|
||||||
|
| `/api/run` · Stream | ✅ | ❌ |
|
||||||
|
| stdin 表单 | ✅ 可再跑 | 只读 hint(或无) |
|
||||||
|
| code-card Run | ✅ `POST` 外联 | ❌ 禁用按钮 |
|
||||||
|
| WASM 重算 | ❌(未接) | ❌(未接) |
|
||||||
|
|
||||||
|
结论:**不是「静态另做一套皮肤」**,而是「导出瞬间的快照 + 部分 JS 帧切换」;**没有**浏览器内重执行闭环。
|
||||||
|
|
||||||
|
### 2.2 欢迎页结构(问题复现源)
|
||||||
|
|
||||||
|
```text
|
||||||
|
> 问候 谁=marqdo
|
||||||
|
> 问候 谁=marqdo user
|
||||||
|
## 问候
|
||||||
|
+ `谁`
|
||||||
|
> 打印 内容=欢迎,`谁`!
|
||||||
|
`f` = $$ x^2 - 2 $$
|
||||||
|
`hi` = ```python … ```
|
||||||
|
```
|
||||||
|
|
||||||
|
- 期望:`## 问候` 旁 **调用** 下拉(`1: 谁=marqdo` / `2: 谁=marqdo user`),切换时打印行的绑定/输出随帧变。
|
||||||
|
- 现状风险:若导出时 CallFrame < 2、或 picker 未挂上、或读者期望的是「编辑谁」而非「选历史调用」,都会表现为「没有下拉框」。
|
||||||
|
- 公式/代码:`SpecialAssign` → formula/code **card**,同时又对同名绑定建 **Bind annot**,文档面还可能保留块源视觉 → 三重展示。
|
||||||
|
|
||||||
|
### 2.3 已有红线(方案不得破坏)
|
||||||
|
|
||||||
|
- 代码即文档:`.mq.md` 源可读;不发明第二套嵌套 DSL(见 web-artifact / marqdo-dev)。
|
||||||
|
- Browse ≠ Debug:静态站不做断点。
|
||||||
|
- `public/**/*.html` 不入库;gh-pages 由 CI/`view output` 生成([user-site.md](user-site.md))。
|
||||||
|
- 外链字体禁令仍在 [view.md](view.md);WASM/重型资源须 **可选加载**,默认站可降级为纯快照。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 目标(验收口径)
|
||||||
|
|
||||||
|
### G1 — 帧与参数交互(静态可读、可拨)
|
||||||
|
|
||||||
|
1. 同函数 ≥2 次调用时,静态页 **必有**「调用」下拉;默认末次;切换只改 chip/臂/相关输出,**源码常显**(同 [view-frame-selection.md](view-frame-selection.md))。
|
||||||
|
2. 导出保证写入完整 `#mq-view-trace`(含 `calls` / `events` / 可选 `loops`)。
|
||||||
|
3. (增强)演示向参数可提供 **受控输入**:默认值来自末次调用或 FM;改参后可触发页内重算(见 §5 引擎选项)。
|
||||||
|
|
||||||
|
### G2 — 无服务端可重算(可选引擎)
|
||||||
|
|
||||||
|
| 档位 | 能力 | 依赖 |
|
||||||
|
|------|------|------|
|
||||||
|
| **S0 快照**(现状加强) | 导出时跑完;帧 picker;只读 Execution | 无 WASM |
|
||||||
|
| **S1 页内重放轨迹** | 不重跑程序,只切换已序列化帧/标注 | JSON only |
|
||||||
|
| **S2 WASM 重跑** | `marqdo_wasm` + bridge:改 stdin/实参后重跑,刷新 Structure/Execution | WASM 包(可 CDN/`public/wasm/`) |
|
||||||
|
| **S3 外联沙箱** | code-card Run:浏览器内 pyodide **或** 明确标「仅 live」 | 可选;默认可关 |
|
||||||
|
|
||||||
|
默认用户站:**S0 + S1 必达**;**S2 为推荐主路径**(与「用 wasm 模拟输出」对齐);S3 单独开关。
|
||||||
|
|
||||||
|
### G3 — 公式 / 代码视觉单层真相
|
||||||
|
|
||||||
|
对「特殊赋值」块约定 **一层主视觉 + 至多一层结果**:
|
||||||
|
|
||||||
|
| 块 | 主视觉 | 允许的结果层 | 禁止 |
|
||||||
|
|----|--------|--------------|------|
|
||||||
|
| 公式 | KaTeX(formula-card 精简) | 无 Bind chip,或仅在 Variables | 再渲一份 `$$` 明文;annot 与卡重复同一 TeX |
|
||||||
|
| 外联代码 | 高亮源码(code-card) | 运行输出区 `code-out`;静态可藏 Run 或接 S2/S3 | annot 再贴整段 fence;卡下重复裸源 |
|
||||||
|
| 普通赋值 | 标记面语句 | Bind chip + L-leader | — |
|
||||||
|
|
||||||
|
Leader:仅连接「主视觉锚点 → 唯一结果 chip」;卡内不用第二套 L 线。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 问题清单(成文)
|
||||||
|
|
||||||
|
| ID | 问题 | 严重度 | 根因假设 |
|
||||||
|
|----|------|--------|----------|
|
||||||
|
| P1 | 静态页看不到调用/循环下拉 | 高 | 轨迹未导出完整 / picker 条件(≥2)未满足 / 读者要的是编辑参而非选帧 |
|
||||||
|
| P2 | 不能改参/stdin 再看输出 | 高 | Static 禁用 `/api/run`;无 WASM 闭环 |
|
||||||
|
| P3 | code-card Run 静态无效 | 中 | `initForeignCards` 显式禁用 |
|
||||||
|
| P4 | 公式卡 + chip + `$$` 三重 | 高 | card 与 Bind annot 叠加;块源未完全被 SpecialAssign 吞掉 |
|
||||||
|
| P5 | 代码卡 + chip + 明文三重 | 高 | 同 P4 |
|
||||||
|
| P6 | 卡内/旁碎线、错位 | 中 | leader 锚到错误节点;卡 CSS 与 annot-band 叠层 |
|
||||||
|
| P7 | 静态 stdin 体验差 | 中 | 仅有只读 hint |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 解决方案(详案,待选)
|
||||||
|
|
||||||
|
### 5.1 引擎策略(三选一,推荐 **B**)
|
||||||
|
|
||||||
|
| 方案 | 做法 | 优点 | 代价 |
|
||||||
|
|------|------|------|------|
|
||||||
|
| **A. 纯快照 + S1** | 加强导出轨迹与 picker;不引入 WASM | 体积小、离线稳 | 不能改参真重算 |
|
||||||
|
| **B. 快照默认 + 可选 WASM(S0/S1/S2)** | `view output` 仍嵌入跑后 HTML;页脚/侧栏「在浏览器中重跑」懒加载 WASM;改参后 patch Structure/Execution | 对齐用户预期;无 WASM 时仍可读 | 打包/加载体积;宿主能力子集 |
|
||||||
|
| **C. 静态页全面 WASM 首屏** | 打开即 WASM 跑 | 交互最强 | 冷启动慢;gh-pages 带宽;与「文档先可读」冲突 |
|
||||||
|
|
||||||
|
**推荐 B**:文档先可读(S0),帧切换不依赖 WASM(S1),需要改参/演示时再拉 WASM(S2)。
|
||||||
|
|
||||||
|
### 5.2 交互控件(与文档面一致)
|
||||||
|
|
||||||
|
1. **调用 / 循环 picker**(已有组件)
|
||||||
|
- 导出验收:欢迎页「问候」必须出现调用下拉。
|
||||||
|
- 单测:对 `00-欢迎.mq.md` / `document-annot-demo` 断言 HTML 含 `call-picker` 且 options≥2。
|
||||||
|
|
||||||
|
2. **演示参数条(新,窄范围)**
|
||||||
|
- 仅当函数被标记为「可演示」**或**静态页检测到 ≥1 形参且存在 CallFrame 时,在函数标题旁增加:
|
||||||
|
`谁 [ text input | select(历史实参) ] [应用]`
|
||||||
|
- **不**改 `.mq.md` 语法;数据来自 trace 的 `args_brief` / 末次绑定。
|
||||||
|
- 「应用」:S1 仅切换已有帧;S2 调 WASM `run` 后替换 `#structure` / Execution。
|
||||||
|
|
||||||
|
3. **stdin**
|
||||||
|
- 静态:若源含 `input`,渲染与 live 同形的 textarea +「重跑」(S2)或说明「需 WASM」。
|
||||||
|
- 无 input 则不显示。
|
||||||
|
|
||||||
|
### 5.3 公式 / 代码去重(视觉)
|
||||||
|
|
||||||
|
**规则:SpecialAssign 行只走 card,不再为同名同值挂 Bind chip。**
|
||||||
|
|
||||||
|
```text
|
||||||
|
公式赋值行
|
||||||
|
└─ formula-card(badge + 名 + KaTeX)
|
||||||
|
└─ ✗ 不再 render_annot_band(Bind f)
|
||||||
|
└─ ✗ 不再在卡外输出 $$ 源
|
||||||
|
|
||||||
|
外联赋值行
|
||||||
|
└─ code-card(badge + 名 + 高亮体 + 可选 Run)
|
||||||
|
└─ ✗ 不再 Bind chip 贴 fence 全文
|
||||||
|
└─ 运行结果只进 .code-out
|
||||||
|
```
|
||||||
|
|
||||||
|
静态 Run 策略(与 §5.1 对齐):
|
||||||
|
|
||||||
|
- S0:隐藏 Run,或保留禁用并 tooltip「打开 live view / 启用 WASM」。
|
||||||
|
- S2:Run → WASM 宿主 `foreign`(若 WASM 支持)或提示不支持。
|
||||||
|
- S3:可选 Pyodide(默认关)。
|
||||||
|
|
||||||
|
CSS:formula-card / code-card 与 `.annot-band` 垂直节奏统一;禁止对 KaTeX 节点拉 L-leader。
|
||||||
|
|
||||||
|
### 5.4 导出管线
|
||||||
|
|
||||||
|
```text
|
||||||
|
marqdo view output
|
||||||
|
→ build_file_view(跑 + annot + trace_json) // 已有
|
||||||
|
→ page_file(Static)
|
||||||
|
+ 嵌入 #mq-view-trace
|
||||||
|
+ (可选)data-wasm-url / 懒加载脚本
|
||||||
|
+ 公式/代码去重后的 structure_html
|
||||||
|
→ public/ + gh-pages
|
||||||
|
```
|
||||||
|
|
||||||
|
`--no-exec`:文档面无标注;可提示「本页为结构-only」;S2 仍可尝试 WASM 首跑(可选,默认关以免惊喜执行)。
|
||||||
|
|
||||||
|
### 5.5 明确不做(本提案)
|
||||||
|
|
||||||
|
- 静态页断点调试(仍属 `marqdo debug`)。
|
||||||
|
- 在 `public/*.mq.md` 发明新的「交互表」DSL(除非另开设计并获批)。
|
||||||
|
- 默认全站加载 Pyodide。
|
||||||
|
- 提交生成 HTML 进 `main`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 分阶段开发计划(确认后执行)
|
||||||
|
|
||||||
|
| 阶段 | 内容 | 交付 | 依赖确认 |
|
||||||
|
|------|------|------|----------|
|
||||||
|
| **D0** | 本文定稿;选定引擎 **A/B/C**;是否要「演示参数条」 | 状态 → Active | **本次决策** |
|
||||||
|
| **D1** | P4/P5/P6:SpecialAssign 与 Bind 互斥;卡 CSS;去掉重复源 | 欢迎页公式/代码干净;单测 | D0 |
|
||||||
|
| **D2** | P1:导出轨迹验收 + 欢迎页 call-picker 金样;修任何「≥2 调用无下拉」bug | HTML 断言 | D0 |
|
||||||
|
| **D3** | P2/P7 S1 夯实:静态 stdin UI 形态;无 WASM 时文案清晰 | UX | D0 |
|
||||||
|
| **D4** | (若选 B)S2:静态页懒加载 WASM;「应用参数 / 重跑」刷新 Structure+Execution | `public/wasm` 或 CDN 策略;体积预算 | D0=B |
|
||||||
|
| **D5** | P3:code-card 与 S2/S3 策略落地;默认隐藏无效 Run | — | D1+D4 |
|
||||||
|
| **D6** | `build-public` / pages CI 回归;更新 [user-site.md](user-site.md) · [view.md](view.md) 验收条 | gh-pages 抽检欢迎页 | D1–D5 |
|
||||||
|
|
||||||
|
建议默认路径:**D0 选 B → D1 → D2 → D3 → D4 → D5 → D6**。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 决策记录
|
||||||
|
|
||||||
|
见文首「已确认」。开发按 §6:D1 → D2 → D3 → D4 → D5 → D6。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 修订历史
|
||||||
|
|
||||||
|
| 日期 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 2026-10-15 | 初稿:静态交互缺口、公式/代码凌乱、S0–S3 与阶段 D0–D6 |
|
||||||
|
| 2026-10-15 | Active:引擎 B;对齐 live;干净视觉;演示参数条;Run 接 WASM 否则隐藏 |
|
||||||
+6
-4
@@ -4,7 +4,7 @@
|
|||||||
|---|---|
|
|---|---|
|
||||||
| 状态 | 已定(v0.0.2 方向) |
|
| 状态 | 已定(v0.0.2 方向) |
|
||||||
| 日期 | 2026-08-04 |
|
| 日期 | 2026-08-04 |
|
||||||
| 相关 | [examples-and-tests.md](examples-and-tests.md) · [view-markup-surface.md](view-markup-surface.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) |
|
| 相关 | [examples-and-tests.md](examples-and-tests.md) · [view-markup-surface.md](view-markup-surface.md) · [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ OUT_DIR/
|
|||||||
- 用户文档推荐流程:`marqdo view output public -o public`,将生成物发布到 `gh-pages`(见 [user-site.md](user-site.md))。
|
- 用户文档推荐流程:`marqdo view output public -o public`,将生成物发布到 `gh-pages`(见 [user-site.md](user-site.md))。
|
||||||
- **执行权限**:与 `marqdo run` 一致(导入即用);view/导出仅对 `exit`/`sleep` 做软化,避免拖垮进程。详见 [stdlib-modules.md](stdlib-modules.md) §6。
|
- **执行权限**:与 `marqdo run` 一致(导入即用);view/导出仅对 `exit`/`sleep` 做软化,避免拖垮进程。详见 [stdlib-modules.md](stdlib-modules.md) §6。
|
||||||
- 金样例浏览仍可用:`marqdo view output tests -o /tmp/mq-tests`(含 errors,勿当对外用户站)。
|
- 金样例浏览仍可用:`marqdo view output tests -o /tmp/mq-tests`(含 errors,勿当对外用户站)。
|
||||||
- 渲染逻辑与实时 `view` **共用**同一套 HTML 构件(结构 / 执行 / 源码),禁止两套皮肤分叉。
|
- 渲染逻辑与实时 `view` **共用**同一路径:`build_file_view` → 文档面 Structure(`document.rs` + annots)→ `page_file`(同一 CSS/JS,含 call/loop picker、`#mq-view-trace`)。禁止第二套皮肤。`--no-exec` 时仍出文档面,但无运行标注。
|
||||||
|
|
||||||
示例:
|
示例:
|
||||||
|
|
||||||
@@ -90,14 +90,16 @@ marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc
|
|||||||
|
|
||||||
## 4. 信息架构
|
## 4. 信息架构
|
||||||
|
|
||||||
侧栏文件索引 + 主区:结构(AST+注释)· 执行 · 源码。结构旁**右侧栏**(现有 outline 槽)为:
|
侧栏文件索引 + 主区:**文档面 Structure** · 执行 · 源码。Structure(Browse)为叙述保真文档面:标记面(变量/语句/返回无源码定界符)、表/列表/分支结构保真,跑后结果经 **CSS L-leader** 引出——见 [view-document-annotations.md](view-document-annotations.md) · [view-execution-trace.md](view-execution-trace.md)。**不是** AST 卡片栈(那是 debug)。
|
||||||
|
|
||||||
|
结构旁**右侧栏**(现有 outline 槽)为:
|
||||||
|
|
||||||
| 区块 | 内容 |
|
| 区块 | 内容 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| **Functions** | 原函数大纲 + 搜索;可折叠(默认展开) |
|
| **Functions** | 原函数大纲 + 搜索;可折叠(默认展开) |
|
||||||
| **Variables** | 跑完后的入口(`# main`)顶层绑定只读快照;List/Map/`@` 行向渲成 HTML 表;可折叠(默认展开) |
|
| **Variables** | 跑完后的入口(`# main`)顶层绑定只读快照;List/Map/`@` 行向渲成 HTML 表;可折叠(默认展开) |
|
||||||
|
|
||||||
view Variables ≠ debug Variables:前者是跑后快照,后者是暂停时的 locals。`--no-exec` 时 Variables 显示 skipped。Live `/api/run` 终态帧可带 `bindings_html` 刷新该面板。
|
view Variables ≠ debug Variables:前者是跑后快照,后者是暂停时的 locals。`--no-exec` 时 Variables 显示 skipped。Live `/api/run` 终态帧可带 `bindings_html` 刷新该面板;终态亦可刷新 Structure 内标注。
|
||||||
|
|
||||||
表达式为表面语法。**断点调试**不在 view 内,见 [`marqdo debug`](view-debug.md)。
|
表达式为表面语法。**断点调试**不在 view 内,见 [`marqdo debug`](view-debug.md)。
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
1.3.2
|
1.4.1
|
||||||
+3
-2
@@ -1,9 +1,10 @@
|
|||||||
---
|
---
|
||||||
title: ext/net/url
|
title: ext/net/url
|
||||||
description: URL helpers (stdlib host wrappers). ADR 0007.
|
description: URL helpers (stdlib wrappers). ADR 0007.
|
||||||
|
import net:lib/net.mq.md
|
||||||
---
|
---
|
||||||
|
|
||||||
## encode
|
## encode
|
||||||
+ `text`
|
+ `text`
|
||||||
|
|
||||||
*> host_url_encode text=`text`*
|
*> net.url_encode text=`text`*
|
||||||
+2
-2
@@ -11,7 +11,7 @@ Persist run output in .mq.md (Jupyter-style writeback)
|
|||||||
+ `key`=None
|
+ `key`=None
|
||||||
+ `line`=None
|
+ `line`=None
|
||||||
|
|
||||||
Write `value` to `<!-- marqdo-out … -->` in the entry file. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask).
|
Write `value` into the entry file. Image-like values (`.png` / `.svg` / … or `data:image/…`) become `` (or ``); other values use `<!-- marqdo-out … -->`. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask).
|
||||||
|
|
||||||
*> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`*
|
*> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`*
|
||||||
|
|
||||||
@@ -51,6 +51,6 @@ List all output blocks in the entry file (includes `key` when named).
|
|||||||
## scan_path
|
## scan_path
|
||||||
+ `path`
|
+ `path`
|
||||||
|
|
||||||
List `<!-- marqdo-out … -->` slots in any file (workbook inspection).
|
List writeback slots in any file (HTML comment and `` image forms; workbook inspection).
|
||||||
|
|
||||||
*> host_writeback_scan_path path=`path`*
|
*> host_writeback_scan_path path=`path`*
|
||||||
+2
-2
@@ -11,7 +11,7 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回)
|
|||||||
+ `键`=None
|
+ `键`=None
|
||||||
+ `行`=None
|
+ `行`=None
|
||||||
|
|
||||||
在入口文件中写入 `<!-- marqdo-out … -->`。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。
|
在入口文件中写入自写回块:若 `值` 像图片路径/URL(`.png` / `.svg` / … 或 `data:image/…`)则写成 ``,否则写成 `<!-- marqdo-out … -->`。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。
|
||||||
|
|
||||||
*> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`*
|
*> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`*
|
||||||
|
|
||||||
@@ -51,6 +51,6 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回)
|
|||||||
## 扫描路径
|
## 扫描路径
|
||||||
+ `路径`
|
+ `路径`
|
||||||
|
|
||||||
扫描任意文件中的 `<!-- marqdo-out … -->` 槽(工作簿观察)。
|
扫描任意文件中的自写回槽(注释块与 `` 图片;工作簿观察)。
|
||||||
|
|
||||||
*> host_writeback_scan_path path=`路径`*
|
*> host_writeback_scan_path path=`路径`*
|
||||||
+41
-52
@@ -1,29 +1,59 @@
|
|||||||
---
|
---
|
||||||
title: Welcome to Marqdo
|
title: Welcome to Marqdo
|
||||||
description: User docs home — code is documentation (English)
|
description: User-docs home — code as documentation (English)
|
||||||
import math:lib/math.mq.md
|
import math:lib/math.mq.md
|
||||||
import foreign:lib/foreign.mq.md
|
import foreign:lib/foreign.mq.md
|
||||||
---
|
---
|
||||||
|
|
||||||
# main
|
# main
|
||||||
|
|
||||||
Hi — thanks for reading this far. I am Marqdo’s developer. Marqdo is a language where *code is documentation, and documentation is code*: Markdown markers are the program structure, so what you read is what runs.
|
Hello — and welcome. I built Marqdo so that code is documentation and documentation is code: Markdown markers are the program structure, so what you read is what runs.
|
||||||
|
|
||||||
AI already prefers Markdown-shaped output. The idea was: why keep docs and code as two separate worlds? So Marqdo was born as a “docs are code” language. To keep every source renderable as Markdown, files use the `.mq.md` suffix. From early on we aimed for richer tooling — auto-generated YAML for OKF-style knowledge bases, even auto-generated slides — those are later goals. Happily, it already works well as a blogging tool: yes, this site is generated by Marqdo. And when AI writes Marqdo, you tend to burn fewer tokens — wallets everywhere thank you.
|
AI systems already favor Markdown-shaped output. That raised a simple question: why keep docs and programs as two separate artifacts? Marqdo is the answer. The `.mq.md` suffix exists so a file stays renderable as Markdown while remaining executable. Richer OKF-style YAML catalogs and even slide decks are on the roadmap; for now this site itself is generated by Marqdo — and that often saves tokens when an AI is writing with you.
|
||||||
|
|
||||||
The language is still young: structure markers, bilingual core names (`print` / `打印`, …), importable stdlibs (see [`stdlib/`](stdlib/) on this site), local `view`, and static export. Contribute on [GitHub](https://github.com/cflmy/marqdo).
|
The language is still early: structural markers, English/Chinese builtin aliases (`print` / `打印` …), an importable standard library (see [`stdlib/`](stdlib/) on this site), local `view`, and static export. Join in at [GitHub](https://github.com/cflmy/marqdo).
|
||||||
|
|
||||||
## Install
|
中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。
|
||||||
|
|
||||||
Pick one way to get the CLI:
|
Want a quick hello? Calls only run when they sit in the entry `# main` — `##` children are methods until something calls them. Try **greet who="marqdo"**. Names can include spaces: **greet who="marqdo user"**.
|
||||||
|
|
||||||
| Method | Notes |
|
Beyond the basics, Marqdo ships table, time, text, files, system, math, foreign, and more. Math and foreign deserve a special mention.
|
||||||
|--------|-------|
|
|
||||||
|
Write a math block and bind it with a TeX comment:
|
||||||
|
|
||||||
|
$$
|
||||||
|
% marqdo: var=f
|
||||||
|
x^2 - 2
|
||||||
|
$$
|
||||||
|
|
||||||
|
Then plot it: **_svg = math.plot formula=`f` var="x" min=-3 max=3**
|
||||||
|
|
||||||
|
Foreign lets you embed another language. Bind `hi` to a small Python block:
|
||||||
|
|
||||||
|
`hi` =
|
||||||
|
```python
|
||||||
|
print("hello-from-python")
|
||||||
|
```
|
||||||
|
|
||||||
|
Under Markdown this stays easy to read — which is the point: code as documentation, documentation as code.
|
||||||
|
|
||||||
|
Welcome again — enjoy exploring Marqdo.
|
||||||
|
|
||||||
|
## greet
|
||||||
|
|
||||||
|
When we meet a visitor `who`, we **print text="Welcome, `who`!"** and close with*None*.
|
||||||
|
|
||||||
|
## install
|
||||||
|
|
||||||
|
Install the interpreter (CLI) in any of these ways:
|
||||||
|
|
||||||
|
| Way | Notes |
|
||||||
|
|------|------|
|
||||||
| Ubuntu PPA | `sudo add-apt-repository ppa:cflmy/marqdo` then `sudo apt install marqdo` |
|
| Ubuntu PPA | `sudo add-apt-repository ppa:cflmy/marqdo` then `sudo apt install marqdo` |
|
||||||
| GitHub Releases | Prebuilt Windows / Linux zips at [releases](https://github.com/cflmy/marqdo/releases) |
|
| GitHub Releases | Prebuilt Windows / Linux packages from [releases](https://github.com/cflmy/marqdo/releases) |
|
||||||
| From source | `cargo build --release` (needs Rust) |
|
| From source | `cargo build --release` (needs a local Rust toolchain) |
|
||||||
|
|
||||||
Official extensions version independently of the CLI:
|
Official extensions update independently of the CLI:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
marqdo ext add web
|
marqdo ext add web
|
||||||
@@ -31,44 +61,3 @@ marqdo ext add quantum
|
|||||||
```
|
```
|
||||||
|
|
||||||
`ext add` tries CDN https://ext.marqdo.com first, then GitHub, then the proxy mirror. See [`features/05-extensions.mq.md`](features/05-extensions.mq.md).
|
`ext add` tries CDN https://ext.marqdo.com first, then GitHub, then the proxy mirror. See [`features/05-extensions.mq.md`](features/05-extensions.mq.md).
|
||||||
|
|
||||||
中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。
|
|
||||||
|
|
||||||
A small function to say hello:
|
|
||||||
|
|
||||||
> greet who=marqdo
|
|
||||||
|
|
||||||
Named args can include spaces:
|
|
||||||
|
|
||||||
> greet who=marqdo user
|
|
||||||
|
|
||||||
## greet
|
|
||||||
+ `who`
|
|
||||||
|
|
||||||
> print text=Welcome, `who`!
|
|
||||||
|
|
||||||
*None*
|
|
||||||
|
|
||||||
Beyond the basics above, Marqdo also ships standard libraries: table, time, text, files, system, math, foreign, and more.
|
|
||||||
|
|
||||||
Math and foreign deserve a special mention. With the math library you can bind a formula like this:
|
|
||||||
|
|
||||||
`f` =
|
|
||||||
$$
|
|
||||||
x^2 - 2
|
|
||||||
$$
|
|
||||||
|
|
||||||
Then plot it:
|
|
||||||
|
|
||||||
**`_svg` = > math.plot formula=`f` var="x" min=-3 max=3**
|
|
||||||
|
|
||||||
The foreign library lets you call external code, for example:
|
|
||||||
|
|
||||||
`hi` =
|
|
||||||
```python
|
|
||||||
print("hello-from-python")
|
|
||||||
```
|
|
||||||
|
|
||||||
Under Markdown this stays easy to read — which is the point: Marqdo’s design is code as documentation, documentation as code.
|
|
||||||
|
|
||||||
Welcome again — enjoy exploring Marqdo.
|
|
||||||
+32
-44
@@ -7,12 +7,42 @@ description: 用户文档首页 — 代码即文档(中文版)
|
|||||||
|
|
||||||
# main
|
# main
|
||||||
|
|
||||||
阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门*代码即文档,文档即代码*的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。
|
阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门「代码即文档,文档即代码」的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。
|
||||||
|
|
||||||
AI 偏爱 Markdown结构的输出。作者的念头是:何必再把文档和代码拆成两套?我们来实现一个文档即代码的语言,所以marqdo应运而生,为了确保代码一定可以被渲染,marqdo的文件后缀定义为了`.mq.md`。在开发之处我们就尝试希望更丰富的支持,自动生成一个yaml文件使得 OKF 式知识库便捷的自动配置,乃至自动生成ppt,自然这都是以后的目标了。不过相当不错的是,至少这会成为一个不错的博客工具——对,这个站点就是 Marqdo 生成的,而且AI输出的时候会节约不少token,你知道的,token烧的太多,钱包会可怜的饿瘦的。
|
AI 偏爱 Markdown 结构的输出。我当时的念头很简单——何必再把文档和代码拆成两套?于是有了 marqdo。为了让文件既能当文档渲染又能执行,后缀定为 `.mq.md`。更远的目标还有 OKF 式知识库的 YAML、甚至自动生成 PPT;眼下它至少已经是个不错的博客工具——对,这个站点就是 Marqdo 生成的。AI 写 `.mq.md` 时往往更省 token,钱包也会轻松一点。
|
||||||
|
|
||||||
语言仍在起步:结构标记、中英内核双名(`打印` / `print` …)、可导入的标准库(见本站 [`stdlib/`](stdlib/))、本地 `view` 与静态导出。欢迎到 [GitHub](https://github.com/cflmy/marqdo) 一起做。
|
语言仍在起步:结构标记、中英内核双名(`打印` / `print` …)、可导入的标准库(见本站 [`stdlib/`](stdlib/))、本地 `view` 与静态导出。欢迎到 [GitHub](https://github.com/cflmy/marqdo) 一起做。
|
||||||
|
|
||||||
|
English docs: [`00-welcome.mq.md`](00-welcome.mq.md)(English prose and English builtins).
|
||||||
|
|
||||||
|
想先打个招呼?调用写在入口 `# main` 里才会真的跑——子标题里的方法要等你叫到它。比如:**问候 谁="marqdo"**。名字里可以带空格:**问候 谁="marqdo user"**。
|
||||||
|
|
||||||
|
除了这些基本面,标准库里还有表、时间、文本、文件、系统、数学、外联等。我特别想提数学和外联。
|
||||||
|
|
||||||
|
比方说,直接写一块公式,并用 TeX 注释标上变量名:
|
||||||
|
|
||||||
|
$$
|
||||||
|
% marqdo: var=f
|
||||||
|
x^2 - 2
|
||||||
|
$$
|
||||||
|
|
||||||
|
接着画出来:**_svg = 数学.绘图 formula=`f` var="x" min=-3 max=3**
|
||||||
|
|
||||||
|
外联则允许嵌一段别的语言。把`hi`绑成下面这样即可:
|
||||||
|
|
||||||
|
`hi` =
|
||||||
|
```python
|
||||||
|
print("hello-from-python")
|
||||||
|
```
|
||||||
|
|
||||||
|
这些在 Markdown 里读起来仍然像文章——这就是 marqdo 想坚持的:代码即文档,文档即代码。
|
||||||
|
|
||||||
|
最后,再次欢迎你,尽情体验 marqdo 吧!
|
||||||
|
|
||||||
|
## 问候
|
||||||
|
|
||||||
|
见到访客`谁`时,我们 **打印 内容="欢迎,`谁`!"**,然后收束为*None*。
|
||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
|
|
||||||
解释器(CLI)任选其一:
|
解释器(CLI)任选其一:
|
||||||
@@ -31,45 +61,3 @@ marqdo ext add quantum
|
|||||||
```
|
```
|
||||||
|
|
||||||
`ext add` 下载顺序:CDN https://ext.marqdo.com → GitHub → proxy 镜像。详见本站 [`features/05-扩展.mq.md`](features/05-扩展.mq.md)。
|
`ext add` 下载顺序:CDN https://ext.marqdo.com → GitHub → proxy 镜像。详见本站 [`features/05-扩展.mq.md`](features/05-扩展.mq.md)。
|
||||||
|
|
||||||
English docs: [`00-welcome.mq.md`](00-welcome.mq.md) (English prose and English builtins).
|
|
||||||
|
|
||||||
用一个小函数打个招呼:
|
|
||||||
|
|
||||||
> 问候 谁=marqdo
|
|
||||||
|
|
||||||
具名实参可以带空格:
|
|
||||||
|
|
||||||
> 问候 谁=marqdo user
|
|
||||||
|
|
||||||
## 问候
|
|
||||||
+ `谁`
|
|
||||||
|
|
||||||
> 打印 内容=欢迎,`谁`!
|
|
||||||
|
|
||||||
*None*
|
|
||||||
|
|
||||||
除了上面的一些基本内容之外,我还开发了这个语言的一些标准库,包括表、时间、文本、文件、系统、数学和外联等标准库。
|
|
||||||
|
|
||||||
其中数学库和外联库是我要着重提到的,例如数学库,你可以通过下面的方式调用:
|
|
||||||
|
|
||||||
`f` =
|
|
||||||
$$
|
|
||||||
x^2 - 2
|
|
||||||
$$
|
|
||||||
|
|
||||||
之后让我们画个图像吧!
|
|
||||||
|
|
||||||
**`_svg` = > 数学.绘图 formula=`f` var="x" min=-3 max=3**
|
|
||||||
|
|
||||||
外联库则允许你调用外部代码,例如:
|
|
||||||
|
|
||||||
`hi` =
|
|
||||||
```python
|
|
||||||
print("hello-from-python")
|
|
||||||
```
|
|
||||||
|
|
||||||
这些代码在markdown下面都非常的易读,就像我说的,marqdo的设计思想就是代码即文档,
|
|
||||||
文档即代码。
|
|
||||||
|
|
||||||
最后,再次欢迎你,尽情体验marqdo吧!
|
|
||||||
@@ -5,12 +5,14 @@ description: Local browse and static export from the interpreter
|
|||||||
|
|
||||||
# main
|
# main
|
||||||
|
|
||||||
Milestone: `marqdo view` and `view output`.
|
Milestone: `marqdo view` and `view output` (v1.4.1 mid→mid annot leaders + document surface).
|
||||||
|
|
||||||
Local: `marqdo view public`
|
Local: `marqdo view public`
|
||||||
|
|
||||||
Static export: `marqdo view output public -o public`
|
Static export: `marqdo view output public -o public`
|
||||||
|
|
||||||
Executable user docs live under `public/`. Generated HTML (`index.html` / `pages/`) is for hosting; CI publishes to `gh-pages`.
|
Browse Structure keeps narration, highlights executable markers, and attaches
|
||||||
|
run results (values, taken branch arms, call/loop frames). The same render path
|
||||||
|
builds this user docs site; CI publishes to `gh-pages`.
|
||||||
|
|
||||||
> print text=Docs site: generated by the Marqdo interpreter, not hand-written HTML.
|
> print text=Docs site: generated by the Marqdo interpreter, not hand-written HTML.
|
||||||
@@ -5,12 +5,13 @@ description: 本地浏览与静态导出由解释器生成
|
|||||||
|
|
||||||
# main
|
# main
|
||||||
|
|
||||||
里程碑:`marqdo view` 与 `view output`。
|
里程碑:`marqdo view` 与 `view output`(v1.4.1 mid→mid 标注连线 + 文档面)。
|
||||||
|
|
||||||
本地浏览:`marqdo view public`
|
本地浏览:`marqdo view public`
|
||||||
|
|
||||||
静态导出:`marqdo view output public -o public`
|
静态导出:`marqdo view output public -o public`
|
||||||
|
|
||||||
用户可执行文档在 `public/`;生成的 HTML(`index.html` / `pages/`)供静态托管,CI 发布到 `gh-pages`。
|
Browse Structure 保真叙述、高亮可执行标记,并挂载运行结果(变量值、分支命中臂、调用/循环帧)。
|
||||||
|
用户站与 live view 同源渲染;CI 发布到 `gh-pages`。
|
||||||
|
|
||||||
> 打印 内容=文档站:由 Marqdo 解释器生成,不是手写 HTML。
|
> 打印 内容=文档站:由 Marqdo 解释器生成,不是手写 HTML。
|
||||||
@@ -124,7 +124,10 @@ if [ "$REUSE_ORIG" -eq 1 ]; then
|
|||||||
echo "==> reusing published ${ORIG_NAME} (debian-only bump; do not rewrite orig)"
|
echo "==> reusing published ${ORIG_NAME} (debian-only bump; do not rewrite orig)"
|
||||||
echo " source: ${ORIG_SRC}"
|
echo " source: ${ORIG_SRC}"
|
||||||
sha256sum "$ORIG_SRC"
|
sha256sum "$ORIG_SRC"
|
||||||
cp -f "$ORIG_SRC" "$BUILD_AREA/$ORIG_NAME"
|
# Local fallback may already be build-area/ORIG_NAME — do not cp onto itself.
|
||||||
|
if [ "$(realpath "$ORIG_SRC")" != "$(realpath "$BUILD_AREA/$ORIG_NAME" 2>/dev/null || echo "")" ]; then
|
||||||
|
cp -f "$ORIG_SRC" "$BUILD_AREA/$ORIG_NAME"
|
||||||
|
fi
|
||||||
# Unpack orig (top dir is usually ${VER} or marqdo-${VER})
|
# Unpack orig (top dir is usually ${VER} or marqdo-${VER})
|
||||||
tar -xJf "$BUILD_AREA/$ORIG_NAME" -C "$(dirname "$PKG_ROOT")"
|
tar -xJf "$BUILD_AREA/$ORIG_NAME" -C "$(dirname "$PKG_ROOT")"
|
||||||
if [ ! -d "$PKG_ROOT" ]; then
|
if [ ! -d "$PKG_ROOT" ]; then
|
||||||
|
|||||||
+94
-1
@@ -1,7 +1,98 @@
|
|||||||
//! Captured program run (for tests and `view`).
|
//! Captured program run (for tests and `view`).
|
||||||
|
|
||||||
use crate::value::Value;
|
|
||||||
use crate::host::PlotArtifact;
|
use crate::host::PlotArtifact;
|
||||||
|
use crate::value::Value;
|
||||||
|
|
||||||
|
/// Silent execution trace for view annotations (not stderr `trace_eval`).
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct ViewTrace {
|
||||||
|
pub branches: Vec<BranchHit>,
|
||||||
|
pub loops: Vec<LoopHit>,
|
||||||
|
/// Per-statement post-state / control events (tree capture).
|
||||||
|
pub events: Vec<StmtEvent>,
|
||||||
|
/// User-function invocations (tree capture).
|
||||||
|
pub calls: Vec<CallFrame>,
|
||||||
|
/// Foreach / while loop frames with per-iteration item values.
|
||||||
|
pub loop_frames: Vec<LoopFrame>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct BranchHit {
|
||||||
|
pub line: u32,
|
||||||
|
pub arm_index: usize,
|
||||||
|
pub count: u32,
|
||||||
|
/// Call frame that took this arm (`0` = entry / `# main`).
|
||||||
|
pub call_id: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct LoopHit {
|
||||||
|
pub line: u32,
|
||||||
|
pub iterations: u32,
|
||||||
|
pub last_item: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct LoopFrame {
|
||||||
|
pub loop_id: u32,
|
||||||
|
pub line: u32,
|
||||||
|
pub item_name: Option<String>,
|
||||||
|
pub collection: Option<String>,
|
||||||
|
pub iterations: Vec<LoopIter>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct LoopIter {
|
||||||
|
/// 0-based iteration index.
|
||||||
|
pub index: u32,
|
||||||
|
pub item_value: String,
|
||||||
|
pub call_id: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct StmtEvent {
|
||||||
|
pub line: u32,
|
||||||
|
pub kind: StmtEventKind,
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub value_after: Option<String>,
|
||||||
|
pub arm_index: Option<usize>,
|
||||||
|
/// 0-based iteration index when inside a loop.
|
||||||
|
pub iter: Option<u32>,
|
||||||
|
pub call_id: u32,
|
||||||
|
pub loop_id: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum StmtEventKind {
|
||||||
|
Assign,
|
||||||
|
Return,
|
||||||
|
Call,
|
||||||
|
Branch,
|
||||||
|
Loop,
|
||||||
|
BindRef,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StmtEventKind {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
StmtEventKind::Assign => "assign",
|
||||||
|
StmtEventKind::Return => "return",
|
||||||
|
StmtEventKind::Call => "call",
|
||||||
|
StmtEventKind::Branch => "branch",
|
||||||
|
StmtEventKind::Loop => "loop",
|
||||||
|
StmtEventKind::BindRef => "bind_ref",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct CallFrame {
|
||||||
|
pub call_id: u32,
|
||||||
|
pub fn_name: String,
|
||||||
|
pub fn_line: u32,
|
||||||
|
pub ordinal: u32,
|
||||||
|
pub args_brief: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct RunCapture {
|
pub struct RunCapture {
|
||||||
@@ -10,4 +101,6 @@ pub struct RunCapture {
|
|||||||
pub plots: Vec<PlotArtifact>,
|
pub plots: Vec<PlotArtifact>,
|
||||||
/// Entry-function bindings after a successful tree-backend run (empty for bytecode).
|
/// Entry-function bindings after a successful tree-backend run (empty for bytecode).
|
||||||
pub bindings: std::collections::HashMap<String, Value>,
|
pub bindings: std::collections::HashMap<String, Value>,
|
||||||
|
/// Branch/loop/stmt hits collected during tree capture (empty for bytecode).
|
||||||
|
pub view_trace: ViewTrace,
|
||||||
}
|
}
|
||||||
+244
-26
@@ -1,7 +1,11 @@
|
|||||||
//! Jupyter-style output persistence in `.mq.md` (`<!-- marqdo-out … -->`).
|
//! Jupyter-style output persistence in `.mq.md`.
|
||||||
//!
|
//!
|
||||||
//! Optional **named slots**: `<!-- marqdo-out ok -->` / `<!-- marqdo-out error -->`
|
//! Two surface forms (both scanned / replaced):
|
||||||
//! so success and failure results do not overwrite each other.
|
//! - HTML comment: `<!-- marqdo-out … -->` (text / structured output)
|
||||||
|
//! - Markdown image: `` (image refs; validated)
|
||||||
|
//!
|
||||||
|
//! Optional **named slots**: `marqdo-out ok` / `marqdo-out error` so success and
|
||||||
|
//! failure results do not overwrite each other.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
@@ -14,14 +18,30 @@ const MAGIC: &str = "marqdo-out";
|
|||||||
/// Serialize all writeback file mutations (sync + subtask writers).
|
/// Serialize all writeback file mutations (sync + subtask writers).
|
||||||
static WRITEBACK_LOCK: Mutex<()> = Mutex::new(());
|
static WRITEBACK_LOCK: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum BlockKind {
|
||||||
|
Comment,
|
||||||
|
Image,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
struct BlockSpan {
|
struct BlockSpan {
|
||||||
start: usize,
|
start: usize,
|
||||||
end: usize,
|
end: usize,
|
||||||
|
/// Comment body text, or image URL/path for [`BlockKind::Image`].
|
||||||
body: String,
|
body: String,
|
||||||
start_line: u32,
|
start_line: u32,
|
||||||
/// Named slot from header (`marqdo-out ok` → `ok`); `None` = legacy unkeyed.
|
/// Named slot from header (`marqdo-out ok` → `ok`); `None` = legacy unkeyed.
|
||||||
key: Option<String>,
|
key: Option<String>,
|
||||||
|
kind: BlockKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// View-facing writeback piece under a statement line.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct WritebackEntry {
|
||||||
|
pub key: Option<String>,
|
||||||
|
pub body: String,
|
||||||
|
pub is_image: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn display_value(v: &Value) -> String {
|
fn display_value(v: &Value) -> String {
|
||||||
@@ -119,13 +139,71 @@ fn line_number_at(source: &str, byte: usize) -> u32 {
|
|||||||
+ 1
|
+ 1
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_block(body: &str, key: Option<&str>) -> String {
|
fn format_comment_block(body: &str, key: Option<&str>) -> String {
|
||||||
match key {
|
match key {
|
||||||
Some(k) => format!("<!-- {MAGIC} {k}\n{body}\n-->"),
|
Some(k) => format!("<!-- {MAGIC} {k}\n{body}\n-->"),
|
||||||
None => format!("<!-- {MAGIC}\n{body}\n-->"),
|
None => format!("<!-- {MAGIC}\n{body}\n-->"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn format_image_block(url: &str, key: Option<&str>) -> String {
|
||||||
|
match key {
|
||||||
|
Some(k) => format!(""),
|
||||||
|
None => format!(""),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_block_for_value(body: &str, key: Option<&str>) -> Result<String, String> {
|
||||||
|
if looks_like_image_ref(body) {
|
||||||
|
validate_image_ref(body)?;
|
||||||
|
Ok(format_image_block(body.trim(), key))
|
||||||
|
} else {
|
||||||
|
Ok(format_comment_block(body, key))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when `s` looks like a path/URL that should persist as ``.
|
||||||
|
pub fn looks_like_image_ref(s: &str) -> bool {
|
||||||
|
validate_image_ref(s).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accept local/relative paths and http(s) URLs with a known image extension,
|
||||||
|
/// or `data:image/…` URIs.
|
||||||
|
pub fn validate_image_ref(s: &str) -> Result<(), String> {
|
||||||
|
let t = s.trim().trim_matches('"').trim_matches('\'');
|
||||||
|
if t.is_empty() {
|
||||||
|
return Err("writeback image: empty path".into());
|
||||||
|
}
|
||||||
|
if t.starts_with("data:image/") {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// Strip query/fragment for extension check.
|
||||||
|
let no_query = t.split_once('?').map(|(p, _)| p).unwrap_or(t);
|
||||||
|
let path_part = no_query.split_once('#').map(|(p, _)| p).unwrap_or(no_query);
|
||||||
|
let file = path_part.rsplit('/').next().unwrap_or(path_part);
|
||||||
|
// Require a real extension (reject bare names like `svg` / `png`).
|
||||||
|
let Some((stem, ext)) = file.rsplit_once('.') else {
|
||||||
|
return Err(format!(
|
||||||
|
"writeback image: path needs an image extension (got `{t}`)"
|
||||||
|
));
|
||||||
|
};
|
||||||
|
if stem.is_empty() {
|
||||||
|
return Err(format!("writeback image: invalid file name `{t}`"));
|
||||||
|
}
|
||||||
|
let ext = ext.to_ascii_lowercase();
|
||||||
|
const OK: &[&str] = &[
|
||||||
|
"png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "tif", "tiff",
|
||||||
|
];
|
||||||
|
if OK.contains(&ext.as_str()) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(format!(
|
||||||
|
"writeback image: not an image path/URL (got `{t}`; need .{})",
|
||||||
|
OK.join("/.")
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_header_key(header: &str) -> Option<String> {
|
fn parse_header_key(header: &str) -> Option<String> {
|
||||||
let mut parts = header.split_whitespace();
|
let mut parts = header.split_whitespace();
|
||||||
let first = parts.next()?;
|
let first = parts.next()?;
|
||||||
@@ -160,11 +238,43 @@ fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option<Block
|
|||||||
body,
|
body,
|
||||||
start_line: line_number_at(source, start_byte),
|
start_line: line_number_at(source, start_byte),
|
||||||
key,
|
key,
|
||||||
|
kind: BlockKind::Comment,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `` on a single source line.
|
||||||
|
fn parse_image_line(line: &str, line_start: usize, source: &str) -> Option<BlockSpan> {
|
||||||
|
let trimmed = line.trim();
|
||||||
|
let rest = trimmed.strip_prefix("?;
|
||||||
|
let alt = rest[..alt_end].trim();
|
||||||
|
if !alt.split_whitespace().any(|t| t == MAGIC) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let key = parse_header_key(alt);
|
||||||
|
let after_alt = &rest[alt_end + 2..];
|
||||||
|
let url_end = after_alt.rfind(')')?;
|
||||||
|
let url = after_alt[..url_end].trim();
|
||||||
|
if url.is_empty() || validate_image_ref(url).is_err() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// Span covers the trimmed image on its line (indent kept outside).
|
||||||
|
let trim_start = line.find(trimmed).unwrap_or(0);
|
||||||
|
let start = line_start + trim_start;
|
||||||
|
let end = start + trimmed.len();
|
||||||
|
Some(BlockSpan {
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
body: url.to_string(),
|
||||||
|
start_line: line_number_at(source, start),
|
||||||
|
key,
|
||||||
|
kind: BlockKind::Image,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scan_blocks(source: &str) -> Vec<BlockSpan> {
|
fn scan_blocks(source: &str) -> Vec<BlockSpan> {
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
|
// HTML comment blocks
|
||||||
let mut i = 0usize;
|
let mut i = 0usize;
|
||||||
while i < source.len() {
|
while i < source.len() {
|
||||||
let rest = &source[i..];
|
let rest = &source[i..];
|
||||||
@@ -186,6 +296,16 @@ fn scan_blocks(source: &str) -> Vec<BlockSpan> {
|
|||||||
}
|
}
|
||||||
i = abs + end_rel + 3;
|
i = abs + end_rel + 3;
|
||||||
}
|
}
|
||||||
|
// Image writebacks (line-oriented)
|
||||||
|
let mut line_start = 0usize;
|
||||||
|
for line in source.split_inclusive('\n') {
|
||||||
|
let content = line.trim_end_matches(['\r', '\n']);
|
||||||
|
if let Some(b) = parse_image_line(content, line_start, source) {
|
||||||
|
out.push(b);
|
||||||
|
}
|
||||||
|
line_start += line.len();
|
||||||
|
}
|
||||||
|
out.sort_by_key(|b| b.start);
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,7 +443,7 @@ fn find_keyed_in_cluster(source: &str, after_line: u32, key: &str) -> Option<Blo
|
|||||||
/// Replace keyed block under `anchor` line, or insert into that cluster (not EOF).
|
/// Replace keyed block under `anchor` line, or insert into that cluster (not EOF).
|
||||||
fn replace_or_insert_keyed_at(source: &str, anchor: u32, key: &str, body: &str) -> Result<String, String> {
|
fn replace_or_insert_keyed_at(source: &str, anchor: u32, key: &str, body: &str) -> Result<String, String> {
|
||||||
let key = normalize_slot_key(key);
|
let key = normalize_slot_key(key);
|
||||||
let block = format_block(body, Some(&key));
|
let block = format_block_for_value(body, Some(&key))?;
|
||||||
if let Some(existing) = find_keyed_in_cluster(source, anchor, &key) {
|
if let Some(existing) = find_keyed_in_cluster(source, anchor, &key) {
|
||||||
return Ok(splice_block(source, existing.start, existing.end, &block));
|
return Ok(splice_block(source, existing.start, existing.end, &block));
|
||||||
}
|
}
|
||||||
@@ -438,13 +558,13 @@ pub fn record(
|
|||||||
let stripped = find_eof_block(&source)
|
let stripped = find_eof_block(&source)
|
||||||
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
||||||
.unwrap_or_else(|| source.clone());
|
.unwrap_or_else(|| source.clone());
|
||||||
append_eof(&stripped, &format_block(&body, None))
|
append_eof(&stripped, &format_block_for_value(&body, None)?)
|
||||||
} else {
|
} else {
|
||||||
let line = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?;
|
let line = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?;
|
||||||
let stripped = find_adjacent_block(&source, line)
|
let stripped = find_adjacent_block(&source, line)
|
||||||
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
||||||
.unwrap_or_else(|| source.clone());
|
.unwrap_or_else(|| source.clone());
|
||||||
insert_after_line(&stripped, line, &format_block(&body, None))?
|
insert_after_line(&stripped, line, &format_block_for_value(&body, None)?)?
|
||||||
};
|
};
|
||||||
persist(ctx, &next)?;
|
persist(ctx, &next)?;
|
||||||
Ok(Value::Text(body.clone()))
|
Ok(Value::Text(body.clone()))
|
||||||
@@ -549,10 +669,15 @@ fn slots_from_source(source: &str) -> Value {
|
|||||||
.map(|b| {
|
.map(|b| {
|
||||||
let anchor = anchor_line_above(source, b.start_line);
|
let anchor = anchor_line_above(source, b.start_line);
|
||||||
let at_eof = b.key.is_none() && is_eof_block(source, &b);
|
let at_eof = b.key.is_none() && is_eof_block(source, &b);
|
||||||
|
let kind = match b.kind {
|
||||||
|
BlockKind::Comment => "comment",
|
||||||
|
BlockKind::Image => "image",
|
||||||
|
};
|
||||||
let mut entries = vec![
|
let mut entries = vec![
|
||||||
("line".into(), Value::Int(anchor as i64)),
|
("line".into(), Value::Int(anchor as i64)),
|
||||||
("body".into(), Value::Text(b.body)),
|
("body".into(), Value::Text(b.body)),
|
||||||
("at_end".into(), Value::Bool(at_eof)),
|
("at_end".into(), Value::Bool(at_eof)),
|
||||||
|
("kind".into(), Value::Text(kind.into())),
|
||||||
];
|
];
|
||||||
if let Some(k) = b.key {
|
if let Some(k) = b.key {
|
||||||
entries.push(("key".into(), Value::Text(k)));
|
entries.push(("key".into(), Value::Text(k)));
|
||||||
@@ -584,29 +709,49 @@ pub fn ensure_slot(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map statement line → body for adjacent blocks (keyed slots included under their anchor).
|
/// Structured writebacks keyed by the statement line above the block cluster.
|
||||||
pub fn writeback_map(source: &str) -> HashMap<u32, String> {
|
pub fn writeback_entries(source: &str) -> HashMap<u32, Vec<WritebackEntry>> {
|
||||||
let mut map = HashMap::new();
|
let mut map: HashMap<u32, Vec<WritebackEntry>> = HashMap::new();
|
||||||
for b in scan_blocks(source) {
|
for b in scan_blocks(source) {
|
||||||
let anchor = anchor_line_above(source, b.start_line);
|
let anchor = if b.key.is_none() && is_eof_block(source, &b) {
|
||||||
let piece = match &b.key {
|
0
|
||||||
Some(k) => format!("[{k}]\n{}", b.body),
|
|
||||||
None => b.body.clone(),
|
|
||||||
};
|
|
||||||
if b.key.is_none() && is_eof_block(source, &b) {
|
|
||||||
map.insert(0, piece);
|
|
||||||
} else {
|
} else {
|
||||||
map.entry(anchor)
|
anchor_line_above(source, b.start_line)
|
||||||
.and_modify(|e| {
|
};
|
||||||
e.push_str("\n\n");
|
let entry = WritebackEntry {
|
||||||
e.push_str(&piece);
|
key: b.key.clone(),
|
||||||
})
|
body: b.body.clone(),
|
||||||
.or_insert(piece);
|
is_image: b.kind == BlockKind::Image,
|
||||||
}
|
};
|
||||||
|
map.entry(anchor).or_default().push(entry);
|
||||||
}
|
}
|
||||||
map
|
map
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Map statement line → combined body for adjacent blocks (keyed slots included).
|
||||||
|
/// Image slots are encoded as a markdown image line so view/static can render `<img>`.
|
||||||
|
pub fn writeback_map(source: &str) -> HashMap<u32, String> {
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
for (anchor, entries) in writeback_entries(source) {
|
||||||
|
let mut pieces = Vec::new();
|
||||||
|
for e in entries {
|
||||||
|
let content = if e.is_image {
|
||||||
|
format!("", e.body)
|
||||||
|
} else {
|
||||||
|
e.body
|
||||||
|
};
|
||||||
|
let piece = match &e.key {
|
||||||
|
Some(k) => format!("[{k}]\n{content}"),
|
||||||
|
None => content,
|
||||||
|
};
|
||||||
|
pieces.push(piece);
|
||||||
|
}
|
||||||
|
map.insert(anchor, pieces.join("\n\n"));
|
||||||
|
}
|
||||||
|
map
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -614,7 +759,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn parse_and_insert_adjacent() {
|
fn parse_and_insert_adjacent() {
|
||||||
let src = "# main\n\n**x = 1**\n";
|
let src = "# main\n\n**x = 1**\n";
|
||||||
let block = format_block("1", None);
|
let block = format_comment_block("1", None);
|
||||||
let next = insert_after_line(src, 3, &block).unwrap();
|
let next = insert_after_line(src, 3, &block).unwrap();
|
||||||
assert!(next.contains("marqdo-out"));
|
assert!(next.contains("marqdo-out"));
|
||||||
assert!(!next.contains("@line"));
|
assert!(!next.contains("@line"));
|
||||||
@@ -625,6 +770,79 @@ mod tests {
|
|||||||
assert!(!replaced.contains("marqdo-out"));
|
assert!(!replaced.contains("marqdo-out"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn image_writeback_scan_and_format() {
|
||||||
|
assert!(looks_like_image_ref("plot.svg"));
|
||||||
|
assert!(looks_like_image_ref("https://ex.com/a.PNG"));
|
||||||
|
assert!(looks_like_image_ref("data:image/png;base64,xx"));
|
||||||
|
assert!(looks_like_image_ref("plots/a.svg?v=1"));
|
||||||
|
assert!(!looks_like_image_ref("readme.txt"));
|
||||||
|
assert!(!looks_like_image_ref("42"));
|
||||||
|
assert!(!looks_like_image_ref("svg")); // bare name, not an extension
|
||||||
|
assert!(!looks_like_image_ref(".svg"));
|
||||||
|
let block = format_image_block("out/plot.svg", Some("ok"));
|
||||||
|
assert_eq!(block, "");
|
||||||
|
let src = "# main\n\n**x = 1**\n\n\n> print text=tail\n";
|
||||||
|
let blocks = scan_blocks(src);
|
||||||
|
assert_eq!(blocks.len(), 1);
|
||||||
|
assert_eq!(blocks[0].kind, BlockKind::Image);
|
||||||
|
assert_eq!(blocks[0].body, "out/plot.svg");
|
||||||
|
assert_eq!(blocks[0].key.as_deref(), Some("ok"));
|
||||||
|
let map = writeback_map(src);
|
||||||
|
assert_eq!(
|
||||||
|
map.get(&3).map(|s| s.as_str()),
|
||||||
|
Some("[ok]\n")
|
||||||
|
);
|
||||||
|
// Invalid image URL in marqdo-out alt → not a writeback slot
|
||||||
|
let bad = "# main\n\n\n";
|
||||||
|
assert!(scan_blocks(bad).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unkeyed_comment_and_image_replace_each_other() {
|
||||||
|
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\nold\n-->\n\n> print text=tail\n";
|
||||||
|
let line = 3u32;
|
||||||
|
let to_image = {
|
||||||
|
let stripped = find_adjacent_block(src, line)
|
||||||
|
.map(|b| strip_span(src, b.start, span_end_including_nl(src, b.end)))
|
||||||
|
.unwrap_or_else(|| src.to_string());
|
||||||
|
insert_after_line(
|
||||||
|
&stripped,
|
||||||
|
line,
|
||||||
|
&format_block_for_value("fig.svg", None).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
assert!(to_image.contains(""));
|
||||||
|
assert!(!to_image.contains("<!-- marqdo-out"));
|
||||||
|
let blocks = scan_blocks(&to_image);
|
||||||
|
assert_eq!(blocks.len(), 1);
|
||||||
|
assert_eq!(blocks[0].kind, BlockKind::Image);
|
||||||
|
|
||||||
|
let to_text = {
|
||||||
|
let stripped = find_adjacent_block(&to_image, line)
|
||||||
|
.map(|b| strip_span(&to_image, b.start, span_end_including_nl(&to_image, b.end)))
|
||||||
|
.unwrap_or_else(|| to_image.clone());
|
||||||
|
insert_after_line(
|
||||||
|
&stripped,
|
||||||
|
line,
|
||||||
|
&format_block_for_value("hello", None).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
assert!(to_text.contains("<!-- marqdo-out\nhello\n-->"));
|
||||||
|
assert!(!to_text.contains("![marqdo-out]"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn record_format_picks_image_for_svg_path() {
|
||||||
|
let s = format_block_for_value("figs/a.svg", None).unwrap();
|
||||||
|
assert_eq!(s, "");
|
||||||
|
let t = format_block_for_value("hello", None).unwrap();
|
||||||
|
assert!(t.contains("<!-- marqdo-out"));
|
||||||
|
assert!(format_block_for_value("notes.txt", None).unwrap().contains("<!--"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn writeback_map_uses_line_above() {
|
fn writeback_map_uses_line_above() {
|
||||||
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\n42\n-->\n\n> print text=tail\n";
|
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\n42\n-->\n\n> print text=tail\n";
|
||||||
@@ -671,7 +889,7 @@ mod tests {
|
|||||||
let stripped = find_adjacent_block(s, line)
|
let stripped = find_adjacent_block(s, line)
|
||||||
.map(|b| strip_span(s, b.start, span_end_including_nl(s, b.end)))
|
.map(|b| strip_span(s, b.start, span_end_including_nl(s, b.end)))
|
||||||
.unwrap_or_else(|| s.to_string());
|
.unwrap_or_else(|| s.to_string());
|
||||||
insert_after_line(&stripped, line, &format_block(body, None)).unwrap()
|
insert_after_line(&stripped, line, &format_comment_block(body, None)).unwrap()
|
||||||
};
|
};
|
||||||
let once = strip_insert(src, "a");
|
let once = strip_insert(src, "a");
|
||||||
let twice = strip_insert(&once, "b");
|
let twice = strip_insert(&once, "b");
|
||||||
|
|||||||
+357
-3
@@ -17,6 +17,9 @@ use crate::debug::{emit_trace, DebugController};
|
|||||||
use crate::diagnostics::{bail_at, Span};
|
use crate::diagnostics::{bail_at, Span};
|
||||||
use crate::host::{call_host, HostContext, HostFn};
|
use crate::host::{call_host, HostContext, HostFn};
|
||||||
use crate::input_feed::InputFeed;
|
use crate::input_feed::InputFeed;
|
||||||
|
use crate::capture::{
|
||||||
|
BranchHit, CallFrame, LoopFrame, LoopHit, LoopIter, StmtEvent, StmtEventKind, ViewTrace,
|
||||||
|
};
|
||||||
use crate::value::Value;
|
use crate::value::Value;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -27,6 +30,14 @@ pub struct Interpreter {
|
|||||||
pub captured_stdout: String,
|
pub captured_stdout: String,
|
||||||
/// Bindings in the entry (`# main` / sole object) env after it finishes.
|
/// Bindings in the entry (`# main` / sole object) env after it finishes.
|
||||||
pub entry_bindings: HashMap<String, Value>,
|
pub entry_bindings: HashMap<String, Value>,
|
||||||
|
/// Silent branch/loop hits for `marqdo view` annotations.
|
||||||
|
pub view_trace: ViewTrace,
|
||||||
|
next_call_id: u32,
|
||||||
|
call_stack: Vec<u32>,
|
||||||
|
fn_ordinals: HashMap<String, u32>,
|
||||||
|
next_loop_id: u32,
|
||||||
|
/// Active loops: `(loop_id, iter_index_0based)`.
|
||||||
|
loop_stack: Vec<(u32, u32)>,
|
||||||
current_span: Span,
|
current_span: Span,
|
||||||
input: InputFeed,
|
input: InputFeed,
|
||||||
host: HostContext,
|
host: HostContext,
|
||||||
@@ -82,6 +93,12 @@ impl Interpreter {
|
|||||||
capture: false,
|
capture: false,
|
||||||
captured_stdout: String::new(),
|
captured_stdout: String::new(),
|
||||||
entry_bindings: HashMap::new(),
|
entry_bindings: HashMap::new(),
|
||||||
|
view_trace: ViewTrace::default(),
|
||||||
|
next_call_id: 1,
|
||||||
|
call_stack: Vec::new(),
|
||||||
|
fn_ordinals: HashMap::new(),
|
||||||
|
next_loop_id: 1,
|
||||||
|
loop_stack: Vec::new(),
|
||||||
current_span: Span::new(1, 1),
|
current_span: Span::new(1, 1),
|
||||||
input: InputFeed::new(false, Vec::new()),
|
input: InputFeed::new(false, Vec::new()),
|
||||||
host: HostContext::for_run(path, Default::default(), Vec::new()),
|
host: HostContext::for_run(path, Default::default(), Vec::new()),
|
||||||
@@ -97,6 +114,12 @@ impl Interpreter {
|
|||||||
capture: true,
|
capture: true,
|
||||||
captured_stdout: String::new(),
|
captured_stdout: String::new(),
|
||||||
entry_bindings: HashMap::new(),
|
entry_bindings: HashMap::new(),
|
||||||
|
view_trace: ViewTrace::default(),
|
||||||
|
next_call_id: 1,
|
||||||
|
call_stack: Vec::new(),
|
||||||
|
fn_ordinals: HashMap::new(),
|
||||||
|
next_loop_id: 1,
|
||||||
|
loop_stack: Vec::new(),
|
||||||
current_span: Span::new(1, 1),
|
current_span: Span::new(1, 1),
|
||||||
input: InputFeed::new(true, Vec::new()),
|
input: InputFeed::new(true, Vec::new()),
|
||||||
host: HostContext::for_capture(path, Default::default()),
|
host: HostContext::for_capture(path, Default::default()),
|
||||||
@@ -150,6 +173,172 @@ impl Interpreter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn current_call_id(&self) -> u32 {
|
||||||
|
self.call_stack.last().copied().unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn loop_ctx(&self) -> (Option<u32>, Option<u32>) {
|
||||||
|
self.loop_stack
|
||||||
|
.last()
|
||||||
|
.map(|(id, iter)| (Some(*id), Some(*iter)))
|
||||||
|
.unwrap_or((None, None))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_view_call(&mut self, fun: &Function, env: &Env) {
|
||||||
|
if !self.capture {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let call_id = self.next_call_id;
|
||||||
|
self.next_call_id += 1;
|
||||||
|
let ordinal = {
|
||||||
|
let e = self.fn_ordinals.entry(fun.name.clone()).or_insert(0);
|
||||||
|
*e += 1;
|
||||||
|
*e
|
||||||
|
};
|
||||||
|
let args_brief = fun
|
||||||
|
.params
|
||||||
|
.iter()
|
||||||
|
.filter_map(|p| {
|
||||||
|
env.get(&p.name)
|
||||||
|
.map(|v| format!("{}={}", p.name, brief_trace_val(v)))
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
self.view_trace.calls.push(CallFrame {
|
||||||
|
call_id,
|
||||||
|
fn_name: fun.name.clone(),
|
||||||
|
fn_line: fun.span.line,
|
||||||
|
ordinal,
|
||||||
|
args_brief,
|
||||||
|
});
|
||||||
|
self.call_stack.push(call_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pop_view_call(&mut self) {
|
||||||
|
if self.capture {
|
||||||
|
self.call_stack.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn begin_view_loop(
|
||||||
|
&mut self,
|
||||||
|
line: u32,
|
||||||
|
item: Option<&str>,
|
||||||
|
collection: Option<&str>,
|
||||||
|
) -> u32 {
|
||||||
|
let loop_id = self.next_loop_id;
|
||||||
|
self.next_loop_id += 1;
|
||||||
|
self.view_trace.loop_frames.push(LoopFrame {
|
||||||
|
loop_id,
|
||||||
|
line,
|
||||||
|
item_name: item.map(|s| s.to_string()),
|
||||||
|
collection: collection.map(|s| s.to_string()),
|
||||||
|
iterations: Vec::new(),
|
||||||
|
});
|
||||||
|
self.loop_stack.push((loop_id, 0));
|
||||||
|
loop_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enter_loop_iter(&mut self, loop_id: u32, index: u32, item_value: &str) {
|
||||||
|
if let Some((_, cur)) = self.loop_stack.iter_mut().rev().find(|(id, _)| *id == loop_id)
|
||||||
|
{
|
||||||
|
*cur = index;
|
||||||
|
}
|
||||||
|
let call_id = self.current_call_id();
|
||||||
|
if let Some(fr) = self
|
||||||
|
.view_trace
|
||||||
|
.loop_frames
|
||||||
|
.iter_mut()
|
||||||
|
.find(|f| f.loop_id == loop_id)
|
||||||
|
{
|
||||||
|
fr.iterations.push(LoopIter {
|
||||||
|
index,
|
||||||
|
item_value: item_value.to_string(),
|
||||||
|
call_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end_view_loop(&mut self, loop_id: u32) {
|
||||||
|
if self
|
||||||
|
.loop_stack
|
||||||
|
.last()
|
||||||
|
.map(|(id, _)| *id == loop_id)
|
||||||
|
.unwrap_or(false)
|
||||||
|
{
|
||||||
|
self.loop_stack.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_stmt_event(&mut self, mut ev: StmtEvent) {
|
||||||
|
if self.capture {
|
||||||
|
if ev.loop_id.is_none() || ev.iter.is_none() {
|
||||||
|
let (lid, iter) = self.loop_ctx();
|
||||||
|
if ev.loop_id.is_none() {
|
||||||
|
ev.loop_id = lid;
|
||||||
|
}
|
||||||
|
if ev.iter.is_none() {
|
||||||
|
ev.iter = iter;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.view_trace.events.push(ev);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_branch_hit(&mut self, line: u32, arm_index: usize) {
|
||||||
|
let call_id = self.current_call_id();
|
||||||
|
if let Some(existing) = self.view_trace.branches.iter_mut().find(|h| {
|
||||||
|
h.line == line && h.arm_index == arm_index && h.call_id == call_id
|
||||||
|
}) {
|
||||||
|
existing.count += 1;
|
||||||
|
} else {
|
||||||
|
self.view_trace.branches.push(BranchHit {
|
||||||
|
line,
|
||||||
|
arm_index,
|
||||||
|
count: 1,
|
||||||
|
call_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let (loop_id, iter) = self.loop_ctx();
|
||||||
|
self.record_stmt_event(StmtEvent {
|
||||||
|
line,
|
||||||
|
kind: StmtEventKind::Branch,
|
||||||
|
name: None,
|
||||||
|
value_after: Some(format!("arm {}", arm_index + 1)),
|
||||||
|
arm_index: Some(arm_index),
|
||||||
|
iter,
|
||||||
|
call_id,
|
||||||
|
loop_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_loop_hit(&mut self, line: u32, iterations: u32, last_item: Option<String>) {
|
||||||
|
if let Some(existing) = self.view_trace.loops.iter_mut().find(|h| h.line == line) {
|
||||||
|
existing.iterations = iterations;
|
||||||
|
if last_item.is_some() {
|
||||||
|
existing.last_item = last_item.clone();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.view_trace.loops.push(LoopHit {
|
||||||
|
line,
|
||||||
|
iterations,
|
||||||
|
last_item: last_item.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let (loop_id, _) = self.loop_ctx();
|
||||||
|
self.record_stmt_event(StmtEvent {
|
||||||
|
line,
|
||||||
|
kind: StmtEventKind::Loop,
|
||||||
|
name: None,
|
||||||
|
value_after: Some(format!("{iterations} iters")),
|
||||||
|
arm_index: None,
|
||||||
|
// Summary event: total count (not 0-based index).
|
||||||
|
iter: Some(iterations),
|
||||||
|
call_id: self.current_call_id(),
|
||||||
|
loop_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// Run a function by name anywhere in the module (for `lib/subtask` workers).
|
/// Run a function by name anywhere in the module (for `lib/subtask` workers).
|
||||||
pub fn invoke_function(
|
pub fn invoke_function(
|
||||||
&mut self,
|
&mut self,
|
||||||
@@ -337,6 +526,7 @@ impl Interpreter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let ret = Value::None;
|
let ret = Value::None;
|
||||||
|
self.push_view_call(fun, &env);
|
||||||
self.host.push_call_frame(&fun.name);
|
self.host.push_call_frame(&fun.name);
|
||||||
let body_result = (|| -> Result<Value> {
|
let body_result = (|| -> Result<Value> {
|
||||||
for stmt in &fun.body {
|
for stmt in &fun.body {
|
||||||
@@ -347,6 +537,7 @@ impl Interpreter {
|
|||||||
Ok(ret)
|
Ok(ret)
|
||||||
})();
|
})();
|
||||||
self.host.pop_call_frame();
|
self.host.pop_call_frame();
|
||||||
|
self.pop_view_call();
|
||||||
let ret = body_result?;
|
let ret = body_result?;
|
||||||
if capture_entry_env {
|
if capture_entry_env {
|
||||||
self.entry_bindings = env.vars_clone();
|
self.entry_bindings = env.vars_clone();
|
||||||
@@ -402,6 +593,18 @@ impl Interpreter {
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if self.capture {
|
||||||
|
self.record_stmt_event(StmtEvent {
|
||||||
|
line: span.line,
|
||||||
|
kind: StmtEventKind::Assign,
|
||||||
|
name: Some(name.clone()),
|
||||||
|
value_after: Some(v.as_display()),
|
||||||
|
arm_index: None,
|
||||||
|
iter: None,
|
||||||
|
call_id: self.current_call_id(),
|
||||||
|
loop_id: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
env.set(name.clone(), v);
|
env.set(name.clone(), v);
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
@@ -425,6 +628,18 @@ impl Interpreter {
|
|||||||
&[("kind", "return"), ("value", display.as_str())],
|
&[("kind", "return"), ("value", display.as_str())],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if self.capture {
|
||||||
|
self.record_stmt_event(StmtEvent {
|
||||||
|
line: span.line,
|
||||||
|
kind: StmtEventKind::Return,
|
||||||
|
name: None,
|
||||||
|
value_after: Some(v.as_display()),
|
||||||
|
arm_index: None,
|
||||||
|
iter: None,
|
||||||
|
call_id: self.current_call_id(),
|
||||||
|
loop_id: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
Ok(Some(v))
|
Ok(Some(v))
|
||||||
}
|
}
|
||||||
Stmt::Call { call, span } => {
|
Stmt::Call { call, span } => {
|
||||||
@@ -437,7 +652,26 @@ impl Interpreter {
|
|||||||
&[("kind", "call"), ("callee", call.callee.as_str())],
|
&[("kind", "call"), ("callee", call.callee.as_str())],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
let _ = self.eval_call(module, fun, env, call)?;
|
let stdout_before = self.captured_stdout.len();
|
||||||
|
let v = self.eval_call(module, fun, env, call)?;
|
||||||
|
if self.capture {
|
||||||
|
let (loop_id, iter) = self.loop_ctx();
|
||||||
|
self.record_stmt_event(StmtEvent {
|
||||||
|
line: span.line,
|
||||||
|
kind: StmtEventKind::Call,
|
||||||
|
name: Some(call.callee.clone()),
|
||||||
|
value_after: Some(call_event_brief(
|
||||||
|
&v,
|
||||||
|
&self.captured_stdout,
|
||||||
|
stdout_before,
|
||||||
|
&call.callee,
|
||||||
|
)),
|
||||||
|
arm_index: None,
|
||||||
|
iter,
|
||||||
|
call_id: self.current_call_id(),
|
||||||
|
loop_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
Stmt::Expr { value, span } => {
|
Stmt::Expr { value, span } => {
|
||||||
@@ -450,7 +684,30 @@ impl Interpreter {
|
|||||||
&[("kind", "expr")],
|
&[("kind", "expr")],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
let _ = self.eval_expr(module, fun, env, value)?;
|
let stdout_before = self.captured_stdout.len();
|
||||||
|
let v = self.eval_expr(module, fun, env, value)?;
|
||||||
|
if self.capture {
|
||||||
|
let (loop_id, iter) = self.loop_ctx();
|
||||||
|
let name = match value {
|
||||||
|
Expr::Call(c) => Some(c.callee.clone()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
self.record_stmt_event(StmtEvent {
|
||||||
|
line: span.line,
|
||||||
|
kind: StmtEventKind::Call,
|
||||||
|
name: name.clone(),
|
||||||
|
value_after: Some(call_event_brief(
|
||||||
|
&v,
|
||||||
|
&self.captured_stdout,
|
||||||
|
stdout_before,
|
||||||
|
name.as_deref().unwrap_or("expr"),
|
||||||
|
)),
|
||||||
|
arm_index: None,
|
||||||
|
iter,
|
||||||
|
call_id: self.current_call_id(),
|
||||||
|
loop_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
Stmt::Branch { arms, span } => {
|
Stmt::Branch { arms, span } => {
|
||||||
@@ -463,12 +720,15 @@ impl Interpreter {
|
|||||||
&[("kind", "branch")],
|
&[("kind", "branch")],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
for arm in arms {
|
for (arm_index, arm) in arms.iter().enumerate() {
|
||||||
let take = match &arm.condition {
|
let take = match &arm.condition {
|
||||||
None => true,
|
None => true,
|
||||||
Some(cond) => self.eval_expr(module, fun, env, cond)?.truthy(),
|
Some(cond) => self.eval_expr(module, fun, env, cond)?.truthy(),
|
||||||
};
|
};
|
||||||
if take {
|
if take {
|
||||||
|
if self.capture {
|
||||||
|
self.record_branch_hit(span.line, arm_index);
|
||||||
|
}
|
||||||
for s in &arm.body {
|
for s in &arm.body {
|
||||||
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
|
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
|
||||||
return Ok(Some(v));
|
return Ok(Some(v));
|
||||||
@@ -493,18 +753,38 @@ impl Interpreter {
|
|||||||
&[("kind", "while")],
|
&[("kind", "while")],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
let loop_id = if self.capture {
|
||||||
|
Some(self.begin_view_loop(span.line, None, None))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
let mut guard = 0u32;
|
let mut guard = 0u32;
|
||||||
while self.eval_expr(module, fun, env, condition)?.truthy() {
|
while self.eval_expr(module, fun, env, condition)?.truthy() {
|
||||||
guard += 1;
|
guard += 1;
|
||||||
if guard > 1_000_000 {
|
if guard > 1_000_000 {
|
||||||
return Err(self.err("while loop exceeded iteration limit"));
|
return Err(self.err("while loop exceeded iteration limit"));
|
||||||
}
|
}
|
||||||
|
if let Some(lid) = loop_id {
|
||||||
|
self.enter_loop_iter(lid, guard - 1, &format!("iter {guard}"));
|
||||||
|
}
|
||||||
for s in body {
|
for s in body {
|
||||||
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
|
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
|
||||||
|
if self.capture {
|
||||||
|
if let Some(lid) = loop_id {
|
||||||
|
self.end_view_loop(lid);
|
||||||
|
}
|
||||||
|
self.record_loop_hit(span.line, guard, None);
|
||||||
|
}
|
||||||
return Ok(Some(v));
|
return Ok(Some(v));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if self.capture {
|
||||||
|
if let Some(lid) = loop_id {
|
||||||
|
self.end_view_loop(lid);
|
||||||
|
}
|
||||||
|
self.record_loop_hit(span.line, guard, None);
|
||||||
|
}
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
Stmt::ForEach {
|
Stmt::ForEach {
|
||||||
@@ -534,14 +814,56 @@ impl Interpreter {
|
|||||||
Ok(_) => unreachable!(),
|
Ok(_) => unreachable!(),
|
||||||
Err(m) => return Err(self.err(m)),
|
Err(m) => return Err(self.err(m)),
|
||||||
};
|
};
|
||||||
|
let loop_id = if self.capture {
|
||||||
|
Some(self.begin_view_loop(
|
||||||
|
span.line,
|
||||||
|
Some(item.as_str()),
|
||||||
|
Some(collection.as_str()),
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let mut iterations = 0u32;
|
||||||
|
let mut last_item: Option<String> = None;
|
||||||
for val in items {
|
for val in items {
|
||||||
|
let index = iterations;
|
||||||
|
iterations += 1;
|
||||||
|
let display = val.as_display();
|
||||||
|
last_item = Some(display.clone());
|
||||||
|
if let Some(lid) = loop_id {
|
||||||
|
self.enter_loop_iter(lid, index, &display);
|
||||||
|
self.record_stmt_event(StmtEvent {
|
||||||
|
line: span.line,
|
||||||
|
kind: StmtEventKind::BindRef,
|
||||||
|
name: Some(item.clone()),
|
||||||
|
value_after: Some(format!(
|
||||||
|
"{collection}[{index}]={display}"
|
||||||
|
)),
|
||||||
|
arm_index: None,
|
||||||
|
iter: Some(index),
|
||||||
|
call_id: self.current_call_id(),
|
||||||
|
loop_id: Some(lid),
|
||||||
|
});
|
||||||
|
}
|
||||||
env.set(item.clone(), val);
|
env.set(item.clone(), val);
|
||||||
for s in body {
|
for s in body {
|
||||||
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
|
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
|
||||||
|
if self.capture {
|
||||||
|
if let Some(lid) = loop_id {
|
||||||
|
self.end_view_loop(lid);
|
||||||
|
}
|
||||||
|
self.record_loop_hit(span.line, iterations, last_item.clone());
|
||||||
|
}
|
||||||
return Ok(Some(v));
|
return Ok(Some(v));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if self.capture {
|
||||||
|
if let Some(lid) = loop_id {
|
||||||
|
self.end_view_loop(lid);
|
||||||
|
}
|
||||||
|
self.record_loop_hit(span.line, iterations, last_item);
|
||||||
|
}
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1399,6 +1721,38 @@ fn cmp_ord(l: &Value, r: &Value, f: impl Fn(std::cmp::Ordering) -> bool) -> Resu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn brief_trace_val(v: &Value) -> String {
|
||||||
|
let s = v.as_display();
|
||||||
|
if s.chars().count() > 24 {
|
||||||
|
format!("{}…", s.chars().take(24).collect::<String>())
|
||||||
|
} else {
|
||||||
|
s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prefer real result; else last stdout line emitted by the call; else callee name.
|
||||||
|
fn call_event_brief(v: &Value, stdout: &str, stdout_before: usize, callee: &str) -> String {
|
||||||
|
if !matches!(v, Value::None) {
|
||||||
|
return brief_trace_val(v);
|
||||||
|
}
|
||||||
|
if stdout.len() > stdout_before {
|
||||||
|
let delta = &stdout[stdout_before..];
|
||||||
|
let line = delta
|
||||||
|
.trim_end()
|
||||||
|
.lines()
|
||||||
|
.last()
|
||||||
|
.unwrap_or(delta.trim_end());
|
||||||
|
if !line.is_empty() {
|
||||||
|
return if line.chars().count() > 48 {
|
||||||
|
format!("{}…", line.chars().take(48).collect::<String>())
|
||||||
|
} else {
|
||||||
|
line.to_string()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
callee.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
fn stmt_span(stmt: &Stmt) -> Span {
|
fn stmt_span(stmt: &Stmt) -> Span {
|
||||||
match stmt {
|
match stmt {
|
||||||
Stmt::Assign { span, .. }
|
Stmt::Assign { span, .. }
|
||||||
|
|||||||
+80
-1
@@ -279,7 +279,52 @@ fn breaks_comment_paragraph(trimmed: &str) -> bool {
|
|||||||
if trimmed.starts_with('#') || trimmed.starts_with('>') {
|
if trimmed.starts_with('#') || trimmed.starts_with('>') {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
is_marqdo_star_line(trimmed)
|
if is_marqdo_star_line(trimmed) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Branch arms / loops / params must not be swallowed after prose in an arm body.
|
||||||
|
if looks_like_ordered_list_item(trimmed) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if trimmed.starts_with("- ") || trimmed.starts_with("-\t") || trimmed == "-" {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if trimmed.starts_with('+') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if is_image_writeback_line(trimmed) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `` — image writeback surface (see stdlib-writeback).
|
||||||
|
pub fn is_image_writeback_line(trimmed: &str) -> bool {
|
||||||
|
let t = trimmed.trim();
|
||||||
|
let Some(rest) = t.strip_prefix(" else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let alt = rest[..alt_end].trim();
|
||||||
|
alt.split_whitespace().any(|tok| tok == "marqdo-out")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn looks_like_ordered_list_item(trimmed: &str) -> bool {
|
||||||
|
let mut chars = trimmed.chars();
|
||||||
|
let mut saw_digit = false;
|
||||||
|
while let Some(c) = chars.next() {
|
||||||
|
if c.is_ascii_digit() {
|
||||||
|
saw_digit = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if c == '.' && saw_digit {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Classify a single logical line (no trailing newline required).
|
/// Classify a single logical line (no trailing newline required).
|
||||||
@@ -353,6 +398,9 @@ pub fn classify_source(source: &str) -> Vec<ClassifiedLine> {
|
|||||||
in_writeback = false;
|
in_writeback = false;
|
||||||
}
|
}
|
||||||
LineKind::Writeback
|
LineKind::Writeback
|
||||||
|
} else if is_image_writeback_line(trimmed) {
|
||||||
|
in_comment_paragraph = false;
|
||||||
|
LineKind::Writeback
|
||||||
} else {
|
} else {
|
||||||
match base {
|
match base {
|
||||||
LineKind::Blank => {
|
LineKind::Blank => {
|
||||||
@@ -439,6 +487,26 @@ pub fn format_lines_dump(path: &str, lines: &[ClassifiedLine]) -> String {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ordered_arm_breaks_prose_paragraph() {
|
||||||
|
let src = "\
|
||||||
|
# main\n\
|
||||||
|
\n\
|
||||||
|
1. `n` > 0\n\
|
||||||
|
此时我们 **打印 内容=\"正\"**\n\
|
||||||
|
2. *\n\
|
||||||
|
否则 **打印 内容=\"非正\"**\n\
|
||||||
|
";
|
||||||
|
let lines = classify_source(src);
|
||||||
|
let l12 = lines.iter().find(|l| l.text.trim() == "2. *").expect("2. *");
|
||||||
|
assert_eq!(
|
||||||
|
l12.kind,
|
||||||
|
LineKind::Code,
|
||||||
|
"else arm must stay Code after prose, got dump:\n{}",
|
||||||
|
format_lines_dump("t", &lines)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn blank_and_comment_and_code() {
|
fn blank_and_comment_and_code() {
|
||||||
assert_eq!(classify_line(""), LineKind::Blank);
|
assert_eq!(classify_line(""), LineKind::Blank);
|
||||||
@@ -498,6 +566,17 @@ mod tests {
|
|||||||
assert_eq!(lines[3].kind, LineKind::Writeback);
|
assert_eq!(lines[3].kind, LineKind::Writeback);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn image_writeback_line_classified() {
|
||||||
|
assert!(is_image_writeback_line(""));
|
||||||
|
assert!(is_image_writeback_line(""));
|
||||||
|
assert!(!is_image_writeback_line(""));
|
||||||
|
let src = "# main\n\n**x = 1**\n\n\n> print text=x\n";
|
||||||
|
let lines = classify_source(src);
|
||||||
|
let img = lines.iter().find(|l| l.text.contains("marqdo-out]")).unwrap();
|
||||||
|
assert_eq!(img.kind, LineKind::Writeback, "{:?}", lines);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn paragraph_comment_keeps_backtick_continuation() {
|
fn paragraph_comment_keeps_backtick_continuation() {
|
||||||
let src = "采用了\n`.mq.md`的双层后缀\n\n> print text=ok\n";
|
let src = "采用了\n`.mq.md`的双层后缀\n\n> print text=ok\n";
|
||||||
|
|||||||
@@ -306,6 +306,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
|||||||
value,
|
value,
|
||||||
plots,
|
plots,
|
||||||
bindings: interp.entry_bindings,
|
bindings: interp.entry_bindings,
|
||||||
|
view_trace: interp.view_trace,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Backend::Bytecode => {
|
Backend::Bytecode => {
|
||||||
@@ -331,6 +332,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
|||||||
value,
|
value,
|
||||||
plots,
|
plots,
|
||||||
bindings: Default::default(),
|
bindings: Default::default(),
|
||||||
|
view_trace: Default::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -366,6 +368,7 @@ pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
|
|||||||
value,
|
value,
|
||||||
plots,
|
plots,
|
||||||
bindings: interp.entry_bindings,
|
bindings: interp.entry_bindings,
|
||||||
|
view_trace: interp.view_trace,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Backend::Bytecode => {
|
Backend::Bytecode => {
|
||||||
@@ -391,6 +394,7 @@ pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
|
|||||||
value,
|
value,
|
||||||
plots,
|
plots,
|
||||||
bindings: Default::default(),
|
bindings: Default::default(),
|
||||||
|
view_trace: Default::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+411
-30
@@ -358,6 +358,13 @@ impl<'a> Cursor<'a> {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self.peek_is_formula_fence() {
|
||||||
|
if let Some(stmt) = self.try_parse_meta_formula_assign()? {
|
||||||
|
fun.body.push(stmt);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if is_ordered_branch(trimmed) {
|
if is_ordered_branch(trimmed) {
|
||||||
fun.body.push(self.parse_branch()?);
|
fun.body.push(self.parse_branch()?);
|
||||||
continue;
|
continue;
|
||||||
@@ -405,9 +412,10 @@ impl<'a> Cursor<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if trimmed.starts_with("$$") {
|
if trimmed.starts_with("$$") {
|
||||||
|
// Standalone meta formulas are handled before parse_simple_stmt.
|
||||||
bail!(
|
bail!(
|
||||||
"{span}: formula fence must follow an empty assignment (`name` =); \
|
"{span}: formula fence must follow an empty assignment (`name` =) \
|
||||||
`$$:name` binding was removed"
|
or include `% marqdo: var=name` inside the block"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -503,7 +511,7 @@ impl<'a> Cursor<'a> {
|
|||||||
if crate::aliases::is_reserved_keyword(&name) {
|
if crate::aliases::is_reserved_keyword(&name) {
|
||||||
bail!("{span}: `{name}` is a reserved keyword");
|
bail!("{span}: `{name}` is a reserved keyword");
|
||||||
}
|
}
|
||||||
let (value, end_line) = self.resolve_assign_rhs(&rhs, span, true)?;
|
let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, true)?;
|
||||||
return Ok(Stmt::Assign {
|
return Ok(Stmt::Assign {
|
||||||
name,
|
name,
|
||||||
value,
|
value,
|
||||||
@@ -544,7 +552,7 @@ impl<'a> Cursor<'a> {
|
|||||||
if crate::aliases::is_reserved_keyword(&name) {
|
if crate::aliases::is_reserved_keyword(&name) {
|
||||||
bail!("{span}: `{name}` is a reserved keyword");
|
bail!("{span}: `{name}` is a reserved keyword");
|
||||||
}
|
}
|
||||||
let (value, end_line) = self.resolve_assign_rhs(&rhs, span, true)?;
|
let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, true)?;
|
||||||
Ok(Stmt::Assign {
|
Ok(Stmt::Assign {
|
||||||
name,
|
name,
|
||||||
value,
|
value,
|
||||||
@@ -570,7 +578,7 @@ impl<'a> Cursor<'a> {
|
|||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
let rhs = after[1..].trim().to_string();
|
let rhs = after[1..].trim().to_string();
|
||||||
let (value, end_line) = self.resolve_assign_rhs(&rhs, span, false)?;
|
let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, false)?;
|
||||||
Ok(Some(Stmt::Assign {
|
Ok(Some(Stmt::Assign {
|
||||||
name,
|
name,
|
||||||
value,
|
value,
|
||||||
@@ -584,6 +592,7 @@ impl<'a> Cursor<'a> {
|
|||||||
/// `prefer_var`: italic RHS uses variable-preferring expression syntax.
|
/// `prefer_var`: italic RHS uses variable-preferring expression syntax.
|
||||||
fn resolve_assign_rhs(
|
fn resolve_assign_rhs(
|
||||||
&mut self,
|
&mut self,
|
||||||
|
assign_name: &str,
|
||||||
rhs: &str,
|
rhs: &str,
|
||||||
span: Span,
|
span: Span,
|
||||||
prefer_var: bool,
|
prefer_var: bool,
|
||||||
@@ -592,7 +601,9 @@ impl<'a> Cursor<'a> {
|
|||||||
if rhs.is_empty() {
|
if rhs.is_empty() {
|
||||||
self.skip_blanks();
|
self.skip_blanks();
|
||||||
if self.peek_is_formula_fence() {
|
if self.peek_is_formula_fence() {
|
||||||
return self.consume_formula_fence(span);
|
let (expr, end_line, meta_var) = self.consume_formula_fence(span)?;
|
||||||
|
check_formula_meta_var(assign_name, meta_var.as_deref(), span)?;
|
||||||
|
return Ok((expr, end_line));
|
||||||
}
|
}
|
||||||
if self.peek_is_code_fence() {
|
if self.peek_is_code_fence() {
|
||||||
return self.consume_code_fence(span);
|
return self.consume_code_fence(span);
|
||||||
@@ -698,7 +709,8 @@ impl<'a> Cursor<'a> {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn consume_formula_fence(&mut self, span: Span) -> Result<(Expr, u32)> {
|
/// Consume `$$…$$`. Returns `(expr, end_line, optional var from % marqdo: var=)`.
|
||||||
|
fn consume_formula_fence(&mut self, span: Span) -> Result<(Expr, u32, Option<String>)> {
|
||||||
let open = self
|
let open = self
|
||||||
.bump()
|
.bump()
|
||||||
.ok_or_else(|| anyhow::anyhow!("{span}: expected `$$` formula fence"))?;
|
.ok_or_else(|| anyhow::anyhow!("{span}: expected `$$` formula fence"))?;
|
||||||
@@ -707,7 +719,7 @@ impl<'a> Cursor<'a> {
|
|||||||
if trimmed.starts_with("$$:") || trimmed.starts_with("$$ name=") {
|
if trimmed.starts_with("$$:") || trimmed.starts_with("$$ name=") {
|
||||||
bail!(
|
bail!(
|
||||||
"{open_line}:1: `$$:name` / `$$ name=` binding was removed; \
|
"{open_line}:1: `$$:name` / `$$ name=` binding was removed; \
|
||||||
use `name` = then a `$$…$$` fence"
|
use `% marqdo: var=name` inside `$$…$$` or `name` = then a fence"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// Single-line: $$body$$
|
// Single-line: $$body$$
|
||||||
@@ -716,15 +728,21 @@ impl<'a> Cursor<'a> {
|
|||||||
if body.is_empty() {
|
if body.is_empty() {
|
||||||
bail!("{open_line}:1: empty formula");
|
bail!("{open_line}:1: empty formula");
|
||||||
}
|
}
|
||||||
|
let (meta_var, tex) = strip_formula_marqdo_meta(body)
|
||||||
|
.map_err(|e| anyhow::anyhow!("{open_line}:1: {e}"))?;
|
||||||
|
if tex.is_empty() {
|
||||||
|
bail!("{open_line}:1: empty formula");
|
||||||
|
}
|
||||||
return Ok((
|
return Ok((
|
||||||
formula_fence_to_expr(body)
|
formula_fence_to_expr(&tex)
|
||||||
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?,
|
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?,
|
||||||
open_line,
|
open_line,
|
||||||
|
meta_var,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if trimmed != "$$" {
|
if trimmed != "$$" {
|
||||||
bail!(
|
bail!(
|
||||||
"{open_line}:1: expected `$$` fence opener after empty assignment, got: {trimmed}"
|
"{open_line}:1: expected `$$` fence opener, got: {trimmed}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
let mut body_lines: Vec<String> = Vec::new();
|
let mut body_lines: Vec<String> = Vec::new();
|
||||||
@@ -743,13 +761,45 @@ impl<'a> Cursor<'a> {
|
|||||||
if !closed {
|
if !closed {
|
||||||
bail!("{open_line}:1: unclosed formula fence `$$`");
|
bail!("{open_line}:1: unclosed formula fence `$$`");
|
||||||
}
|
}
|
||||||
let text = body_lines.join("\n").trim().to_string();
|
let raw = body_lines.join("\n");
|
||||||
if text.is_empty() {
|
let (meta_var, tex) = strip_formula_marqdo_meta(&raw)
|
||||||
|
.map_err(|e| anyhow::anyhow!("{open_line}:1: {e}"))?;
|
||||||
|
if tex.is_empty() {
|
||||||
bail!("{open_line}:1: empty formula");
|
bail!("{open_line}:1: empty formula");
|
||||||
}
|
}
|
||||||
let expr = formula_fence_to_expr(&text)
|
let expr = formula_fence_to_expr(&tex)
|
||||||
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?;
|
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?;
|
||||||
Ok((expr, end_line))
|
Ok((expr, end_line, meta_var))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Standalone `$$` with `% marqdo: var=` → Assign (no empty RHS required).
|
||||||
|
fn try_parse_meta_formula_assign(&mut self) -> Result<Option<Stmt>> {
|
||||||
|
if !self.peek_is_formula_fence() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let Some(l) = self.peek() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let span = Span {
|
||||||
|
line: l.line_no,
|
||||||
|
col: 1,
|
||||||
|
};
|
||||||
|
let (value, end_line, meta_var) = self.consume_formula_fence(span)?;
|
||||||
|
let Some(name) = meta_var else {
|
||||||
|
bail!(
|
||||||
|
"{span}: formula fence must follow an empty assignment (`name` =) \
|
||||||
|
or include `% marqdo: var=name` inside the block"
|
||||||
|
);
|
||||||
|
};
|
||||||
|
if crate::aliases::is_reserved_keyword(&name) {
|
||||||
|
bail!("{span}: `{name}` is a reserved keyword");
|
||||||
|
}
|
||||||
|
Ok(Some(Stmt::Assign {
|
||||||
|
name,
|
||||||
|
value,
|
||||||
|
span,
|
||||||
|
end_line,
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GFM table after empty RHS:
|
/// GFM table after empty RHS:
|
||||||
@@ -878,11 +928,7 @@ impl<'a> Cursor<'a> {
|
|||||||
let cond_src = strip_ordered(trimmed).unwrap();
|
let cond_src = strip_ordered(trimmed).unwrap();
|
||||||
self.bump();
|
self.bump();
|
||||||
|
|
||||||
let condition = if cond_src == "*" || cond_src.is_empty() {
|
let condition = parse_branch_condition(cond_src)?;
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(parse_expr_str(cond_src)?)
|
|
||||||
};
|
|
||||||
|
|
||||||
let body = self.parse_indented_body(base_indent)?;
|
let body = self.parse_indented_body(base_indent)?;
|
||||||
arms.push(BranchArm { condition, body });
|
arms.push(BranchArm { condition, body });
|
||||||
@@ -904,8 +950,10 @@ impl<'a> Cursor<'a> {
|
|||||||
let trimmed = line.text.trim();
|
let trimmed = line.text.trim();
|
||||||
let rest = trimmed.strip_prefix('-').unwrap().trim();
|
let rest = trimmed.strip_prefix('-').unwrap().trim();
|
||||||
|
|
||||||
// foreach: [item](collection)
|
// foreach: [item](collection) or narrative sugar
|
||||||
if let Some((item, coll)) = parse_foreach_header(rest) {
|
if let Some((item, coll)) = parse_foreach_header(rest)
|
||||||
|
.or_else(|| parse_foreach_narrative(rest))
|
||||||
|
{
|
||||||
let body = self.parse_indented_body(base_indent)?;
|
let body = self.parse_indented_body(base_indent)?;
|
||||||
return Ok(Stmt::ForEach {
|
return Ok(Stmt::ForEach {
|
||||||
item,
|
item,
|
||||||
@@ -931,7 +979,7 @@ impl<'a> Cursor<'a> {
|
|||||||
let Some(l) = self.peek() else { break };
|
let Some(l) = self.peek() else { break };
|
||||||
let ind = indent_of(&l.text);
|
let ind = indent_of(&l.text);
|
||||||
if ind <= parent_indent {
|
if ind <= parent_indent {
|
||||||
// Same-indent `+`/`-` ends body (next arm / sibling).
|
// Same-indent `2.` / `-` ends body (next arm / sibling).
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
let trimmed = l.text.trim();
|
let trimmed = l.text.trim();
|
||||||
@@ -951,6 +999,39 @@ impl<'a> Cursor<'a> {
|
|||||||
body.push(self.parse_loop_or_err()?);
|
body.push(self.parse_loop_or_err()?);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
// Same prose rights as function body (fixes arm/loop narrative escape).
|
||||||
|
if self.peek_is_prose() {
|
||||||
|
let line = self.bump().unwrap();
|
||||||
|
let span = Span {
|
||||||
|
line: line.line_no,
|
||||||
|
col: 1,
|
||||||
|
};
|
||||||
|
let bits = scan_prose_line(line.text.trim_end_matches(['\r', '\n']));
|
||||||
|
let mut end_arm = false;
|
||||||
|
for bit in bits {
|
||||||
|
match bit {
|
||||||
|
ProseBit::Decl { .. } => {}
|
||||||
|
ProseBit::BoldCode { inner, .. } => {
|
||||||
|
body.push(self.stmt_from_bold_inner(&inner, span.clone())?);
|
||||||
|
}
|
||||||
|
ProseBit::ItalicReturn { inner, .. } => {
|
||||||
|
body.push(stmt_from_italic_return(&inner, span.clone())?);
|
||||||
|
end_arm = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if end_arm {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if self.peek_is_formula_fence() {
|
||||||
|
if let Some(stmt) = self.try_parse_meta_formula_assign()? {
|
||||||
|
body.push(stmt);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
let stmt = self.parse_simple_stmt()?;
|
let stmt = self.parse_simple_stmt()?;
|
||||||
let end_arm = matches!(stmt, Stmt::Return { .. });
|
let end_arm = matches!(stmt, Stmt::Return { .. });
|
||||||
body.push(stmt);
|
body.push(stmt);
|
||||||
@@ -998,26 +1079,101 @@ fn is_bare_assign_ident(s: &str) -> bool {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Same-line `$$body$$` → Formula or numeric matrix List; otherwise None.
|
/// Same-line `$$body$$` or `$body$` → Formula; otherwise None.
|
||||||
fn try_parse_inline_formula(rhs: &str) -> Result<Option<Expr>> {
|
fn try_parse_inline_formula(rhs: &str) -> Result<Option<Expr>> {
|
||||||
let rhs = rhs.trim();
|
let rhs = rhs.trim();
|
||||||
if !rhs.starts_with("$$") {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
if rhs.starts_with("$$:") || rhs.starts_with("$$ name=") {
|
if rhs.starts_with("$$:") || rhs.starts_with("$$ name=") {
|
||||||
bail!(
|
bail!(
|
||||||
"`$$:name` / `$$ name=` binding was removed; use `name` = then a `$$…$$` fence"
|
"`$$:name` / `$$ name=` binding was removed; use `% marqdo: var=name` \
|
||||||
|
inside `$$…$$` or `name` = then a fence"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if rhs.ends_with("$$") && rhs.len() > 4 {
|
if rhs.starts_with("$$") {
|
||||||
let body = rhs[2..rhs.len() - 2].trim();
|
if rhs.ends_with("$$") && rhs.len() > 4 {
|
||||||
|
let body = rhs[2..rhs.len() - 2].trim();
|
||||||
|
if body.is_empty() {
|
||||||
|
bail!("empty formula");
|
||||||
|
}
|
||||||
|
let (_meta, tex) = strip_formula_marqdo_meta(body)
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
if tex.is_empty() {
|
||||||
|
bail!("empty formula");
|
||||||
|
}
|
||||||
|
let expr = formula_fence_to_expr(&tex).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
|
||||||
|
return Ok(Some(expr));
|
||||||
|
}
|
||||||
|
bail!("incomplete inline formula (expected `$$…$$` on one line)");
|
||||||
|
}
|
||||||
|
// Traditional inline: $…$ (not $$)
|
||||||
|
if rhs.starts_with('$') && rhs.ends_with('$') && rhs.len() > 2 && !rhs.starts_with("$$") {
|
||||||
|
let body = rhs[1..rhs.len() - 1].trim();
|
||||||
if body.is_empty() {
|
if body.is_empty() {
|
||||||
bail!("empty formula");
|
bail!("empty formula");
|
||||||
}
|
}
|
||||||
|
if body.contains('%') && body.to_lowercase().contains("marqdo:") {
|
||||||
|
bail!(
|
||||||
|
"inline `$…$` must not use `% marqdo:` (breaks Markdown/TeX); \
|
||||||
|
bind with `name` = $…$ or use a `$$` block with `% marqdo: var=`"
|
||||||
|
);
|
||||||
|
}
|
||||||
let expr = formula_fence_to_expr(body).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
|
let expr = formula_fence_to_expr(body).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
|
||||||
return Ok(Some(expr));
|
return Ok(Some(expr));
|
||||||
}
|
}
|
||||||
bail!("incomplete inline formula (expected `$$…$$` on one line)");
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strip `% marqdo: var=name` directive lines from formula fence body.
|
||||||
|
/// Returns `(optional var name, remaining TeX)`.
|
||||||
|
fn strip_formula_marqdo_meta(body: &str) -> Result<(Option<String>, String), String> {
|
||||||
|
let mut meta_var: Option<String> = None;
|
||||||
|
let mut out: Vec<&str> = Vec::new();
|
||||||
|
for line in body.lines() {
|
||||||
|
let t = line.trim();
|
||||||
|
if let Some(rest) = t.strip_prefix('%') {
|
||||||
|
let rest = rest.trim_start();
|
||||||
|
if rest.to_ascii_lowercase().starts_with("marqdo:") {
|
||||||
|
let after = rest["marqdo:".len()..].trim_start();
|
||||||
|
let mut got_var = false;
|
||||||
|
for part in after.split_whitespace() {
|
||||||
|
if let Some(v) = part.strip_prefix("var=") {
|
||||||
|
if v.is_empty() {
|
||||||
|
return Err("% marqdo: var= requires a name".into());
|
||||||
|
}
|
||||||
|
if !is_bare_assign_ident(v) {
|
||||||
|
return Err(format!("invalid marqdo var name `{v}`"));
|
||||||
|
}
|
||||||
|
if meta_var.as_deref() == Some(v) || meta_var.is_none() {
|
||||||
|
meta_var = Some(v.to_string());
|
||||||
|
} else {
|
||||||
|
return Err(format!(
|
||||||
|
"conflicting % marqdo: var= ({} vs {v})",
|
||||||
|
meta_var.as_deref().unwrap_or("")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
got_var = true;
|
||||||
|
} else {
|
||||||
|
return Err(format!("unknown marqdo key `{part}` (only var= is supported)"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !got_var {
|
||||||
|
return Err("% marqdo: requires var=<name>".into());
|
||||||
|
}
|
||||||
|
continue; // strip directive line
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(line);
|
||||||
|
}
|
||||||
|
Ok((meta_var, out.join("\n").trim().to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_formula_meta_var(assign_name: &str, meta: Option<&str>, span: Span) -> Result<()> {
|
||||||
|
match meta {
|
||||||
|
None => Ok(()),
|
||||||
|
Some(v) if v == assign_name => Ok(()),
|
||||||
|
Some(v) => bail!(
|
||||||
|
"{span}: formula `% marqdo: var={v}` conflicts with assignment `{assign_name}`"
|
||||||
|
),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn formula_fence_to_expr(body: &str) -> Result<Expr, String> {
|
fn formula_fence_to_expr(body: &str) -> Result<Expr, String> {
|
||||||
@@ -1112,6 +1268,148 @@ fn parse_foreach_header(rest: &str) -> Option<(String, String)> {
|
|||||||
Some((item, coll))
|
Some((item, coll))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Narrative foreach sugar (recommended remains `- [item](coll)`).
|
||||||
|
/// - ZH: `对`xs`的每一项`项`` optional `遍历`
|
||||||
|
/// - EN: `for each `item` in `xs``
|
||||||
|
fn parse_foreach_narrative(rest: &str) -> Option<(String, String)> {
|
||||||
|
let rest = rest.trim();
|
||||||
|
if let Some(after) = rest.strip_prefix('对') {
|
||||||
|
let (coll, after) = take_backtick_token(after.trim_start())?;
|
||||||
|
let after = after.trim_start().strip_prefix("的每一项")?;
|
||||||
|
let (item, after) = take_backtick_token(after.trim_start())?;
|
||||||
|
let after = after
|
||||||
|
.trim()
|
||||||
|
.trim_end_matches('。')
|
||||||
|
.trim();
|
||||||
|
let after = after.strip_prefix("遍历").unwrap_or(after).trim();
|
||||||
|
if after.is_empty() {
|
||||||
|
return Some((item, coll));
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let lower = rest.to_ascii_lowercase();
|
||||||
|
let Some(idx) = lower.find("for each ") else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
if idx != 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let after = rest["for each ".len()..].trim_start();
|
||||||
|
let (item, after) = take_backtick_token(after)?;
|
||||||
|
let after = after.trim_start();
|
||||||
|
let after_l = after.to_ascii_lowercase();
|
||||||
|
if !after_l.starts_with("in ") && !after_l.starts_with("in\t") {
|
||||||
|
// require ` in `
|
||||||
|
let Some(in_at) = after_l.find("in ") else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
if in_at != 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let after = after["in ".len()..].trim_start();
|
||||||
|
let (coll, after) = take_backtick_token(after)?;
|
||||||
|
if after.trim().is_empty() {
|
||||||
|
return Some((item, coll));
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take_backtick_token(s: &str) -> Option<(String, &str)> {
|
||||||
|
let s = s.trim_start();
|
||||||
|
if !s.starts_with('`') {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let end = s[1..].find('`')?;
|
||||||
|
let name = s[1..1 + end].to_string();
|
||||||
|
if name.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((name, &s[1 + end + 1..]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Branch arm condition: expr, bold code, narrative (当`n`大于 0 时), or else `*`.
|
||||||
|
fn parse_branch_condition(cond_src: &str) -> Result<Option<Expr>> {
|
||||||
|
let t = cond_src.trim();
|
||||||
|
if t.is_empty() || t == "*" {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
// "否则 *" / "else *"
|
||||||
|
if let Some(before) = t.strip_suffix('*') {
|
||||||
|
let before = before.trim();
|
||||||
|
if before.is_empty()
|
||||||
|
|| before == "否则"
|
||||||
|
|| before == "其它"
|
||||||
|
|| before == "其他"
|
||||||
|
|| before.eq_ignore_ascii_case("else")
|
||||||
|
|| before.eq_ignore_ascii_case("otherwise")
|
||||||
|
{
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(e) = parse_expr_str(t) {
|
||||||
|
return Ok(Some(e));
|
||||||
|
}
|
||||||
|
if let Some(inner) = extract_first_bold_inner(t) {
|
||||||
|
if let Ok(e) = parse_expr_str(inner.trim()) {
|
||||||
|
return Ok(Some(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(e) = try_narrative_condition(t) {
|
||||||
|
return Ok(Some(e));
|
||||||
|
}
|
||||||
|
bail!(
|
||||||
|
"branch condition: cannot parse `{t}` \
|
||||||
|
(use an expression, **`n` > 0**, or 当`n`大于 0 时)"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_first_bold_inner(s: &str) -> Option<&str> {
|
||||||
|
let start = s.find("**")?;
|
||||||
|
let rest = &s[start + 2..];
|
||||||
|
let end = rest.find("**")?;
|
||||||
|
Some(&rest[..end])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_narrative_condition(s: &str) -> Option<Expr> {
|
||||||
|
let mut s = s.trim();
|
||||||
|
for p in ["当且仅当", "当", "若", "如果"] {
|
||||||
|
if let Some(r) = s.strip_prefix(p) {
|
||||||
|
s = r.trim_start();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let lower = s.to_ascii_lowercase();
|
||||||
|
if let Some(r) = lower.strip_prefix("when ") {
|
||||||
|
let _ = r;
|
||||||
|
s = s[5..].trim_start();
|
||||||
|
} else if let Some(r) = lower.strip_prefix("if ") {
|
||||||
|
let _ = r;
|
||||||
|
s = s[3..].trim_start();
|
||||||
|
}
|
||||||
|
for suf in ["的话", "时", "则"] {
|
||||||
|
if let Some(r) = s.strip_suffix(suf) {
|
||||||
|
s = r.trim_end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut mapped = s.to_string();
|
||||||
|
let replacements = [
|
||||||
|
("大于等于", ">="),
|
||||||
|
("小于等于", "<="),
|
||||||
|
("不等于", "!="),
|
||||||
|
("等于", "=="),
|
||||||
|
("大于", ">"),
|
||||||
|
("小于", "<"),
|
||||||
|
];
|
||||||
|
for (zh, op) in replacements {
|
||||||
|
if mapped.contains(zh) {
|
||||||
|
mapped = mapped.replace(zh, op);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parse_expr_str(mapped.trim()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_heading(trimmed: &str) -> Option<(u8, &str)> {
|
fn parse_heading(trimmed: &str) -> Option<(u8, &str)> {
|
||||||
if !trimmed.starts_with('#') {
|
if !trimmed.starts_with('#') {
|
||||||
return None;
|
return None;
|
||||||
@@ -1882,6 +2180,89 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::ast::Stmt;
|
use crate::ast::Stmt;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_formula_meta_var_standalone() {
|
||||||
|
let src = "# main\n\n$$\n% marqdo: var=f\nx^2 - 2\n$$\n";
|
||||||
|
let m = parse_source(src).unwrap();
|
||||||
|
match &m.functions[0].body[0] {
|
||||||
|
Stmt::Assign { name, value, .. } => {
|
||||||
|
assert_eq!(name, "f");
|
||||||
|
assert!(matches!(value, Expr::Formula(_)));
|
||||||
|
}
|
||||||
|
other => panic!("expected formula assign, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_formula_meta_conflicts_with_assign() {
|
||||||
|
let src = "# main\n\n`f` =\n$$\n% marqdo: var=g\nx\n$$\n";
|
||||||
|
let err = parse_source(src).unwrap_err().to_string();
|
||||||
|
assert!(
|
||||||
|
err.contains("conflicts") || err.contains("var=g"),
|
||||||
|
"{err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_foreach_narrative_zh_en() {
|
||||||
|
let src = "# main\n\n- 对`xs`的每一项`项`\n > print text=`项`\n\n- for each `item` in `ys`\n > print text=`item`\n";
|
||||||
|
let m = parse_source(src).unwrap();
|
||||||
|
match &m.functions[0].body[0] {
|
||||||
|
Stmt::ForEach { item, collection, .. } => {
|
||||||
|
assert_eq!(item, "项");
|
||||||
|
assert_eq!(collection, "xs");
|
||||||
|
}
|
||||||
|
other => panic!("zh foreach: {other:?}"),
|
||||||
|
}
|
||||||
|
match &m.functions[0].body[1] {
|
||||||
|
Stmt::ForEach { item, collection, .. } => {
|
||||||
|
assert_eq!(item, "item");
|
||||||
|
assert_eq!(collection, "ys");
|
||||||
|
}
|
||||||
|
other => panic!("en foreach: {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn branch_arm_prose_stays_inside_arm() {
|
||||||
|
let src = include_str!("../../tests/markup-v03/branch-arm-prose.mq.md");
|
||||||
|
let m = parse_source(src).unwrap();
|
||||||
|
let main = &m.functions[0];
|
||||||
|
let branches: Vec<_> = main
|
||||||
|
.body
|
||||||
|
.iter()
|
||||||
|
.filter(|s| matches!(s, Stmt::Branch { .. }))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
branches.len(),
|
||||||
|
1,
|
||||||
|
"expected one Branch, body={:?}",
|
||||||
|
main.body
|
||||||
|
);
|
||||||
|
match &main.body[1] {
|
||||||
|
Stmt::Branch { arms, .. } => {
|
||||||
|
assert_eq!(arms.len(), 2, "arms={arms:?}");
|
||||||
|
assert!(
|
||||||
|
!arms[0].body.is_empty(),
|
||||||
|
"then arm must contain prose stmts: {:?}",
|
||||||
|
arms[0].body
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!arms[1].body.is_empty(),
|
||||||
|
"else arm must contain prose stmts: {:?}",
|
||||||
|
arms[1].body
|
||||||
|
);
|
||||||
|
}
|
||||||
|
other => panic!("expected Branch as body[1] after assign, got {other:?}"),
|
||||||
|
}
|
||||||
|
// No Call/Assign print siblings after the branch
|
||||||
|
assert!(
|
||||||
|
!main.body.iter().skip(2).any(|s| matches!(s, Stmt::Call { .. } | Stmt::Assign { .. })),
|
||||||
|
"prose escaped branch: {:?}",
|
||||||
|
main.body
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parse_hello() {
|
fn parse_hello() {
|
||||||
let src = include_str!("../../tests/structure/hello.mq.md");
|
let src = include_str!("../../tests/structure/hello.mq.md");
|
||||||
|
|||||||
+1155
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+671
-4
@@ -330,6 +330,236 @@ section.block > h2 {
|
|||||||
background: transparent;
|
background: transparent;
|
||||||
padding-left: calc(1.1rem - 2px);
|
padding-left: calc(1.1rem - 2px);
|
||||||
}
|
}
|
||||||
|
/* Document surface (Browse Structure) */
|
||||||
|
.document-surface {
|
||||||
|
padding: 0.5rem 1rem 1.25rem;
|
||||||
|
color: var(--ink);
|
||||||
|
line-height: 1.55;
|
||||||
|
}
|
||||||
|
.doc-imports { margin: 0 0 0.85rem; }
|
||||||
|
.doc-fun {
|
||||||
|
margin: 1.1rem 0 0.65rem;
|
||||||
|
padding-bottom: 0.35rem;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.doc-fun-title {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.15rem;
|
||||||
|
font-weight: 650;
|
||||||
|
letter-spacing: -0.01em;
|
||||||
|
}
|
||||||
|
.doc-fun-bar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem 1rem;
|
||||||
|
}
|
||||||
|
.call-picker-label {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
color: var(--muted);
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
}
|
||||||
|
.call-picker, .loop-picker {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
padding: 0.2rem 0.4rem;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
.loop-picker-label {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
color: var(--muted);
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
}
|
||||||
|
li.doc-list-meta {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0.25rem 0 0.5rem;
|
||||||
|
margin-left: -1.25rem;
|
||||||
|
}
|
||||||
|
.doc-block { position: relative; margin: 0.55rem 0 0.85rem; }
|
||||||
|
.doc-block > .annot-leaders {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
overflow: visible;
|
||||||
|
z-index: 1; /* below .annot-chips */
|
||||||
|
}
|
||||||
|
.doc-block > .annot-leaders svg {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: 0;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
.doc-block.is-keyed > .annot-leaders { display: none; }
|
||||||
|
.doc-block.doc-exec[style*="--doc-indent"] {
|
||||||
|
margin-left: calc(var(--doc-indent, 1) * 1.5rem);
|
||||||
|
}
|
||||||
|
.doc-prose { color: var(--ink); }
|
||||||
|
.doc-prose > :first-child { margin-top: 0; }
|
||||||
|
.doc-prose > :last-child { margin-bottom: 0; }
|
||||||
|
.doc-line { margin: 0.15rem 0; }
|
||||||
|
.doc-prose-line { white-space: pre-wrap; }
|
||||||
|
.doc-stmt, .doc-call, .doc-cond {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.92em;
|
||||||
|
}
|
||||||
|
.mq-call-gt { color: var(--muted); margin-right: 0.25rem; }
|
||||||
|
.mq-else { font-family: var(--mono); color: var(--muted); font-style: italic; }
|
||||||
|
.doc-table-wrap { overflow-x: auto; }
|
||||||
|
.doc-table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: auto;
|
||||||
|
min-width: 12rem;
|
||||||
|
font-size: 0.92rem;
|
||||||
|
margin: 0.35rem 0;
|
||||||
|
}
|
||||||
|
.doc-table th, .doc-table td {
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
padding: 0.35rem 0.7rem;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.doc-table th {
|
||||||
|
background: var(--fill);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
ul.doc-loop, ol.doc-branch {
|
||||||
|
margin: 0.5rem 0 0.75rem;
|
||||||
|
padding-left: calc(var(--doc-indent, 1) * 1.5rem + 1.25rem);
|
||||||
|
}
|
||||||
|
.doc-list-item { margin: 0.45rem 0; }
|
||||||
|
.doc-list-head { font-family: var(--mono); font-size: 0.92em; }
|
||||||
|
.doc-list-body {
|
||||||
|
margin: 0.35rem 0 0.2rem;
|
||||||
|
padding-left: 1.5rem;
|
||||||
|
border-left: 2px solid var(--line);
|
||||||
|
}
|
||||||
|
.doc-list-item.arm-taken {
|
||||||
|
border-left: 3px solid #bf5af2;
|
||||||
|
padding-left: 0.55rem;
|
||||||
|
margin-left: -0.15rem;
|
||||||
|
}
|
||||||
|
.doc-list-item.arm-taken > .doc-list-head { font-weight: 600; }
|
||||||
|
.doc-list-item.arm-miss { opacity: 0.45; }
|
||||||
|
.doc-code {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.9em;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
.mq-anchor {
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
padding: 0 0.05em;
|
||||||
|
border-radius: 0;
|
||||||
|
border-bottom: 2px solid var(--line-strong);
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: inherit;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
.mq-anchor.mq-decl {
|
||||||
|
border-bottom-color: #5ac8fa;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.95em;
|
||||||
|
}
|
||||||
|
.mq-anchor.mq-code {
|
||||||
|
border-bottom-color: #ff9f0a;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.95em;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.mq-anchor.mq-return {
|
||||||
|
border-bottom-color: #30d158;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.95em;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
.mq-anchor.is-focus { background: rgba(0,0,0,0.04); }
|
||||||
|
.annot-band {
|
||||||
|
position: relative;
|
||||||
|
margin: 0.55rem 0 0.15rem;
|
||||||
|
min-height: 1.6rem;
|
||||||
|
padding-top: 1.15rem; /* room for mid→mid leaders (rail + stub) */
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
/* Band-local leaders kept for keyed fallback; geometry uses .doc-block > .annot-leaders */
|
||||||
|
.annot-band > .annot-leaders { display: none; }
|
||||||
|
.annot-leader {
|
||||||
|
fill: none;
|
||||||
|
stroke-width: 1.5;
|
||||||
|
stroke-linecap: round;
|
||||||
|
stroke-linejoin: round;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.annot-chips {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.45rem 0.7rem;
|
||||||
|
position: relative;
|
||||||
|
z-index: 3; /* chips above leaders */
|
||||||
|
}
|
||||||
|
.annot-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 0.35rem;
|
||||||
|
max-width: 100%;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.22rem 0.5rem;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-left-width: 3px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--fill);
|
||||||
|
color: var(--ink);
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.72rem;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
/* Author `display:inline-flex` must not defeat frame filtering. */
|
||||||
|
.annot-chip[hidden],
|
||||||
|
.annot-chip.is-frame-hidden {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
.annot-chip:hover,
|
||||||
|
.annot-chip.is-focus { background: #fff; }
|
||||||
|
.annot-chip.annot-bind { border-left-color: #5ac8fa; }
|
||||||
|
.annot-chip.annot-return { border-left-color: #30d158; }
|
||||||
|
.annot-chip.annot-call,
|
||||||
|
.annot-chip.annot-expr,
|
||||||
|
.annot-chip.annot-code { border-left-color: #ff9f0a; }
|
||||||
|
.annot-chip.annot-branch { border-left-color: #bf5af2; }
|
||||||
|
.annot-chip.annot-loop { border-left-color: #64d2ff; }
|
||||||
|
.annot-chip.annot-writeback { border-left-color: #8e8e93; }
|
||||||
|
.annot-chip.annot-chip-overflow { display: none !important; }
|
||||||
|
.annot-band.is-expanded .annot-chip.annot-chip-overflow:not([hidden]):not(.is-frame-hidden) {
|
||||||
|
display: inline-flex !important;
|
||||||
|
}
|
||||||
|
.annot-label { color: var(--muted); font-weight: 600; }
|
||||||
|
.annot-value { color: var(--ink); word-break: break-word; }
|
||||||
|
.annot-more {
|
||||||
|
border: 1px dashed var(--line);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.72rem;
|
||||||
|
padding: 0.22rem 0.45rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.annot-band.is-keyed .annot-chip::before,
|
||||||
|
.doc-block.is-keyed .annot-chip::before {
|
||||||
|
content: attr(data-annot-key) " ";
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.annot-band { padding-top: 0.25rem; }
|
||||||
|
.doc-block > .annot-leaders { display: none; }
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.doc-block > .annot-leaders { display: none; }
|
||||||
|
}
|
||||||
.badge {
|
.badge {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
font-family: var(--mono);
|
font-family: var(--mono);
|
||||||
@@ -365,6 +595,15 @@ section.block > h2 {
|
|||||||
font-size: 0.65em;
|
font-size: 0.65em;
|
||||||
opacity: 0.7;
|
opacity: 0.7;
|
||||||
}
|
}
|
||||||
|
.chip .chip-val {
|
||||||
|
font-weight: 500;
|
||||||
|
opacity: 0.78;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.92em;
|
||||||
|
}
|
||||||
|
.chip .chip-val:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
.nested {
|
.nested {
|
||||||
margin: 0.45rem 0 0.15rem 0.15rem;
|
margin: 0.45rem 0 0.15rem 0.15rem;
|
||||||
padding-left: 0.85rem;
|
padding-left: 0.85rem;
|
||||||
@@ -735,6 +974,9 @@ section.block > h2 {
|
|||||||
border-left: 3px solid #2563eb;
|
border-left: 3px solid #2563eb;
|
||||||
background: #f8fafc;
|
background: #f8fafc;
|
||||||
}
|
}
|
||||||
|
.output-card.output-card-image {
|
||||||
|
border-left-color: #0d9488;
|
||||||
|
}
|
||||||
.output-card .wb-badges {
|
.output-card .wb-badges {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
@@ -750,6 +992,58 @@ section.block > h2 {
|
|||||||
white-space: pre-wrap;
|
white-space: pre-wrap;
|
||||||
color: #0f172a;
|
color: #0f172a;
|
||||||
}
|
}
|
||||||
|
.wb-figure {
|
||||||
|
margin: 0.5rem 0 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.wb-image {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
.wb-image-url {
|
||||||
|
margin: 0.35rem 0 0;
|
||||||
|
font: 0.75rem/1.35 var(--mono);
|
||||||
|
color: var(--muted);
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
.doc-writeback {
|
||||||
|
margin: 0.35rem 0;
|
||||||
|
padding: 0.4rem 0.55rem;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px dashed #94a3b8;
|
||||||
|
background: #f1f5f9;
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.4rem 0.65rem;
|
||||||
|
align-items: baseline;
|
||||||
|
}
|
||||||
|
.doc-writeback[data-wb-kind="image"] {
|
||||||
|
border-color: #0d9488;
|
||||||
|
background: #f0fdfa;
|
||||||
|
}
|
||||||
|
.wb-source-badge {
|
||||||
|
font: 0.68rem/1.2 var(--sans);
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: #334155;
|
||||||
|
background: #e2e8f0;
|
||||||
|
padding: 0.12rem 0.4rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
.doc-writeback[data-wb-kind="image"] .wb-source-badge {
|
||||||
|
background: #ccfbf1;
|
||||||
|
color: #115e59;
|
||||||
|
}
|
||||||
|
.wb-source-text {
|
||||||
|
font: 0.82rem/1.4 var(--mono);
|
||||||
|
color: #0f172a;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
.wb-outline {
|
.wb-outline {
|
||||||
margin-top: 0.75rem;
|
margin-top: 0.75rem;
|
||||||
padding-top: 0.75rem;
|
padding-top: 0.75rem;
|
||||||
@@ -1048,6 +1342,16 @@ section.block > h2 {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.4rem;
|
gap: 0.4rem;
|
||||||
}
|
}
|
||||||
|
.code-foot {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.45rem 0.65rem;
|
||||||
|
padding: 0.5rem 0.85rem;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
background: #fafafa;
|
||||||
|
}
|
||||||
|
.code-foot .code-actions { margin-left: auto; }
|
||||||
.code-cmd {
|
.code-cmd {
|
||||||
min-width: 9rem;
|
min-width: 9rem;
|
||||||
max-width: 16rem;
|
max-width: 16rem;
|
||||||
@@ -1084,6 +1388,7 @@ section.block > h2 {
|
|||||||
background: #1e1e1e;
|
background: #1e1e1e;
|
||||||
color: #d4d4d4;
|
color: #d4d4d4;
|
||||||
font: 0.82rem/1.45 var(--mono);
|
font: 0.82rem/1.45 var(--mono);
|
||||||
|
min-height: 2.4rem;
|
||||||
}
|
}
|
||||||
.code-body code {
|
.code-body code {
|
||||||
font: inherit;
|
font: inherit;
|
||||||
@@ -1287,17 +1592,23 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
|
|||||||
function initForeignCards() {{
|
function initForeignCards() {{
|
||||||
var live = !!window.MARQDO_VIEW_LIVE;
|
var live = !!window.MARQDO_VIEW_LIVE;
|
||||||
document.querySelectorAll(".code-card").forEach(function (card) {{
|
document.querySelectorAll(".code-card").forEach(function (card) {{
|
||||||
|
var foot = card.querySelector(".code-foot");
|
||||||
var btn = card.querySelector(".code-run");
|
var btn = card.querySelector(".code-run");
|
||||||
var cmd = card.querySelector(".code-cmd");
|
var cmd = card.querySelector(".code-cmd");
|
||||||
var out = card.querySelector(".code-out");
|
var out = card.querySelector(".code-out");
|
||||||
var body = card.querySelector(".code-body code");
|
var body = card.querySelector(".code-body code");
|
||||||
if (!btn || !out || !body) return;
|
// Narrative ```text``` cards have no Run chrome — leave as-is.
|
||||||
|
if (!btn) return;
|
||||||
if (!live) {{
|
if (!live) {{
|
||||||
btn.disabled = true;
|
// Static: hide fake Run (view-static-interactive D5 / view-prose-annot-gaps P4).
|
||||||
btn.title = "Run is available in live marqdo view";
|
if (foot) foot.hidden = true;
|
||||||
if (cmd) cmd.disabled = true;
|
else {{
|
||||||
|
btn.hidden = true;
|
||||||
|
if (cmd) cmd.hidden = true;
|
||||||
|
}}
|
||||||
return;
|
return;
|
||||||
}}
|
}}
|
||||||
|
if (!out || !body) return;
|
||||||
btn.addEventListener("click", function () {{
|
btn.addEventListener("click", function () {{
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
out.hidden = false;
|
out.hidden = false;
|
||||||
@@ -1740,6 +2051,19 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
|
|||||||
initVarsPanel();
|
initVarsPanel();
|
||||||
}}
|
}}
|
||||||
}}
|
}}
|
||||||
|
if (typeof ev.structure_html === "string" && ev.structure_html) {{
|
||||||
|
var structEl = document.getElementById("structure");
|
||||||
|
if (structEl) {{
|
||||||
|
structEl.innerHTML = ev.structure_html;
|
||||||
|
initAnnotLeaders();
|
||||||
|
initCallPickers();
|
||||||
|
initLoopPickers();
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
if (typeof ev.trace_json === "string" && ev.trace_json) {{
|
||||||
|
var tr = document.getElementById("mq-view-trace");
|
||||||
|
if (tr) tr.textContent = ev.trace_json;
|
||||||
|
}}
|
||||||
}}
|
}}
|
||||||
}}
|
}}
|
||||||
}}
|
}}
|
||||||
@@ -1938,18 +2262,352 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
|
|||||||
renderMath(panel);
|
renderMath(panel);
|
||||||
}}
|
}}
|
||||||
|
|
||||||
|
function readViewTrace() {{
|
||||||
|
var el = document.getElementById("mq-view-trace");
|
||||||
|
if (!el) return null;
|
||||||
|
try {{ return JSON.parse(el.textContent || "{{}}"); }} catch (e) {{ return null; }}
|
||||||
|
}}
|
||||||
|
|
||||||
|
function parseArgsBrief(brief) {{
|
||||||
|
var out = {{}};
|
||||||
|
if (!brief) return out;
|
||||||
|
String(brief).split(", ").forEach(function (part) {{
|
||||||
|
var i = part.indexOf("=");
|
||||||
|
if (i <= 0) return;
|
||||||
|
out[part.slice(0, i)] = part.slice(i + 1);
|
||||||
|
}});
|
||||||
|
return out;
|
||||||
|
}}
|
||||||
|
|
||||||
|
function applyParamChipValues(fnName, callId, trace) {{
|
||||||
|
if (!trace || !Array.isArray(trace.calls)) return;
|
||||||
|
var brief = "";
|
||||||
|
for (var i = 0; i < trace.calls.length; i++) {{
|
||||||
|
var c = trace.calls[i];
|
||||||
|
if (String(c.call_id) === String(callId) && String(c.fn || "") === String(fnName)) {{
|
||||||
|
brief = c.args_brief || "";
|
||||||
|
break;
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
var args = parseArgsBrief(brief);
|
||||||
|
document.querySelectorAll('.chip[data-fn="' + fnName + '"][data-param-name]').forEach(function (chip) {{
|
||||||
|
var name = chip.getAttribute("data-param-name") || "";
|
||||||
|
var slot = chip.querySelector(".chip-val");
|
||||||
|
if (!slot) return;
|
||||||
|
var v = args[name];
|
||||||
|
slot.textContent = v ? ("=" + v) : "";
|
||||||
|
}});
|
||||||
|
}}
|
||||||
|
|
||||||
|
var MAX_VISIBLE_ANNOTS = 4;
|
||||||
|
|
||||||
|
function setFrameHidden(el, hide) {{
|
||||||
|
el.hidden = !!hide;
|
||||||
|
if (hide) el.classList.add("is-frame-hidden");
|
||||||
|
else el.classList.remove("is-frame-hidden");
|
||||||
|
}}
|
||||||
|
|
||||||
|
/** After frame filter: overflow only among chips visible in the selected frame. */
|
||||||
|
function recomputeAnnotOverflow(scope) {{
|
||||||
|
var root = scope || document.getElementById("structure") || document;
|
||||||
|
root.querySelectorAll("[data-annot-band]").forEach(function (band) {{
|
||||||
|
band.classList.remove("is-expanded");
|
||||||
|
var chips = band.querySelectorAll(".annot-chip");
|
||||||
|
var visible = [];
|
||||||
|
chips.forEach(function (chip) {{
|
||||||
|
chip.classList.remove("annot-chip-overflow");
|
||||||
|
if (chip.hidden || chip.classList.contains("is-frame-hidden")) return;
|
||||||
|
visible.push(chip);
|
||||||
|
}});
|
||||||
|
var overflow = 0;
|
||||||
|
visible.forEach(function (chip, i) {{
|
||||||
|
if (i >= MAX_VISIBLE_ANNOTS) {{
|
||||||
|
chip.classList.add("annot-chip-overflow");
|
||||||
|
overflow++;
|
||||||
|
}}
|
||||||
|
}});
|
||||||
|
var more = band.querySelector("[data-annot-more]");
|
||||||
|
if (more) {{
|
||||||
|
if (overflow > 0) {{
|
||||||
|
more.hidden = false;
|
||||||
|
more.textContent = "+" + overflow;
|
||||||
|
}} else {{
|
||||||
|
more.hidden = true;
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
}});
|
||||||
|
}}
|
||||||
|
|
||||||
|
/** Source structure always stays visible; only chips + arm classes follow the frame. */
|
||||||
|
function initCallPickers() {{
|
||||||
|
document.querySelectorAll(".call-picker").forEach(function (sel) {{
|
||||||
|
function apply() {{
|
||||||
|
var callId = String(sel.value || "");
|
||||||
|
var fnName = String(sel.getAttribute("data-fn") || "");
|
||||||
|
var allowed = {{}};
|
||||||
|
Array.prototype.forEach.call(sel.options, function (o) {{
|
||||||
|
allowed[String(o.value)] = true;
|
||||||
|
}});
|
||||||
|
var root = document.getElementById("structure") || document;
|
||||||
|
// Only touch chips whose call_id belongs to this function's calls.
|
||||||
|
root.querySelectorAll(".annot-chip[data-call-id]").forEach(function (chip) {{
|
||||||
|
var cid = String(chip.getAttribute("data-call-id") || "");
|
||||||
|
if (!allowed[cid]) return;
|
||||||
|
setFrameHidden(chip, cid !== callId);
|
||||||
|
}});
|
||||||
|
var trace = readViewTrace();
|
||||||
|
applyParamChipValues(fnName, callId, trace);
|
||||||
|
if (trace && Array.isArray(trace.events)) {{
|
||||||
|
var takenByLine = {{}};
|
||||||
|
trace.events.forEach(function (ev) {{
|
||||||
|
if (ev.kind === "branch" && String(ev.call_id) === callId && ev.arm_index != null) {{
|
||||||
|
takenByLine[ev.line] = ev.arm_index;
|
||||||
|
}}
|
||||||
|
}});
|
||||||
|
root.querySelectorAll("ol.doc-branch").forEach(function (ol) {{
|
||||||
|
var line = parseInt(ol.getAttribute("data-line") || "0", 10);
|
||||||
|
var taken = takenByLine[line];
|
||||||
|
if (taken === undefined) return;
|
||||||
|
ol.querySelectorAll(":scope > li.doc-list-item[data-arm-index]").forEach(function (li) {{
|
||||||
|
var idx = parseInt(li.getAttribute("data-arm-index") || "-1", 10);
|
||||||
|
li.classList.remove("arm-taken", "arm-miss");
|
||||||
|
if (idx === taken) li.classList.add("arm-taken");
|
||||||
|
else li.classList.add("arm-miss");
|
||||||
|
}});
|
||||||
|
}});
|
||||||
|
}}
|
||||||
|
recomputeAnnotOverflow(root);
|
||||||
|
initAnnotLeaders();
|
||||||
|
}}
|
||||||
|
if (sel.dataset.bound !== "1") {{
|
||||||
|
sel.dataset.bound = "1";
|
||||||
|
sel.addEventListener("change", apply);
|
||||||
|
}}
|
||||||
|
apply();
|
||||||
|
}});
|
||||||
|
}}
|
||||||
|
|
||||||
|
function initLoopPickers() {{
|
||||||
|
document.querySelectorAll(".loop-picker").forEach(function (sel) {{
|
||||||
|
function apply() {{
|
||||||
|
var iter = String(sel.value || "");
|
||||||
|
var loopId = String(sel.getAttribute("data-loop-id") || "");
|
||||||
|
var ul = sel.closest("ul.doc-loop");
|
||||||
|
var scope = ul || document.getElementById("structure");
|
||||||
|
if (!scope) return;
|
||||||
|
// Only the selected iteration's chips; structure source stays visible.
|
||||||
|
scope.querySelectorAll(".annot-chip").forEach(function (chip) {{
|
||||||
|
var lid = chip.getAttribute("data-loop-id");
|
||||||
|
var chipIter = chip.getAttribute("data-iter");
|
||||||
|
if (loopId && lid && String(lid) !== loopId) return;
|
||||||
|
if (chipIter == null) {{
|
||||||
|
// No data-iter: leave alone (foreach uses BindRef chips; while may have one summary).
|
||||||
|
return;
|
||||||
|
}}
|
||||||
|
// Chips with data-iter but no loop-id still filter by iter inside this ul.
|
||||||
|
if (lid && loopId && String(lid) !== loopId) return;
|
||||||
|
setFrameHidden(chip, String(chipIter) !== iter);
|
||||||
|
}});
|
||||||
|
recomputeAnnotOverflow(scope);
|
||||||
|
initAnnotLeaders();
|
||||||
|
}}
|
||||||
|
if (sel.dataset.bound !== "1") {{
|
||||||
|
sel.dataset.bound = "1";
|
||||||
|
sel.addEventListener("change", apply);
|
||||||
|
}}
|
||||||
|
apply();
|
||||||
|
}});
|
||||||
|
}}
|
||||||
|
|
||||||
|
function ensureBlockLeaders(block) {{
|
||||||
|
var leaders = block.querySelector(":scope > .annot-leaders");
|
||||||
|
if (!leaders) {{
|
||||||
|
leaders = document.createElement("div");
|
||||||
|
leaders.className = "annot-leaders";
|
||||||
|
leaders.setAttribute("aria-hidden", "true");
|
||||||
|
block.insertBefore(leaders, block.firstChild);
|
||||||
|
}}
|
||||||
|
return leaders;
|
||||||
|
}}
|
||||||
|
|
||||||
|
function leaderColor(kind) {{
|
||||||
|
if (kind === "bind") return "#5ac8fa";
|
||||||
|
if (kind === "return") return "#30d158";
|
||||||
|
if (kind === "call" || kind === "expr" || kind === "code") return "#ff9f0a";
|
||||||
|
if (kind === "branch") return "#bf5af2";
|
||||||
|
if (kind === "loop") return "#64d2ff";
|
||||||
|
return "#8e8e93";
|
||||||
|
}}
|
||||||
|
|
||||||
|
function initAnnotLeaders() {{
|
||||||
|
var bands = document.querySelectorAll("[data-annot-band]");
|
||||||
|
if (!bands.length) return;
|
||||||
|
var reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||||
|
var narrow = window.matchMedia && window.matchMedia("(max-width: 640px)").matches;
|
||||||
|
|
||||||
|
function layoutBand(band) {{
|
||||||
|
var block = band.closest(".doc-block");
|
||||||
|
if (!block) return;
|
||||||
|
var leaders = ensureBlockLeaders(block);
|
||||||
|
leaders.innerHTML = "";
|
||||||
|
var chipsEl = band.querySelector(".annot-chips");
|
||||||
|
var chips = Array.prototype.slice.call(
|
||||||
|
band.querySelectorAll(".annot-chip:not(.annot-chip-overflow):not([hidden]):not(.is-frame-hidden)")
|
||||||
|
);
|
||||||
|
// Pair chips with anchors; reorder DOM left→right under underlines so
|
||||||
|
// L-leaders do not cross (crowded reverse order looked like missing lines).
|
||||||
|
var items = [];
|
||||||
|
chips.forEach(function (chip) {{
|
||||||
|
var id = chip.getAttribute("data-annot-id") || "";
|
||||||
|
var kind = chip.getAttribute("data-annot-kind") || "";
|
||||||
|
var anchor = id
|
||||||
|
? (block.querySelector('.mq-anchor[data-annot-id="' + id + '"]')
|
||||||
|
|| document.querySelector('.mq-anchor[data-annot-id="' + id + '"]'))
|
||||||
|
: null;
|
||||||
|
// Fallback: match mark kind on this block (frame chips may share a span).
|
||||||
|
if (!anchor) {{
|
||||||
|
var cls = kind === "bind" ? "mq-decl"
|
||||||
|
: kind === "return" ? "mq-return"
|
||||||
|
: (kind === "call" || kind === "expr" || kind === "code") ? "mq-code"
|
||||||
|
: "";
|
||||||
|
if (cls) anchor = block.querySelector(".mq-anchor." + cls);
|
||||||
|
}}
|
||||||
|
if (!anchor) return;
|
||||||
|
if (id) anchor.setAttribute("data-annot-id", id);
|
||||||
|
items.push({{
|
||||||
|
chip: chip,
|
||||||
|
anchor: anchor,
|
||||||
|
kind: kind,
|
||||||
|
x: anchor.getBoundingClientRect().left
|
||||||
|
}});
|
||||||
|
}});
|
||||||
|
items.sort(function (a, b) {{ return a.x - b.x; }});
|
||||||
|
if (chipsEl && items.length) {{
|
||||||
|
items.forEach(function (it) {{ chipsEl.appendChild(it.chip); }});
|
||||||
|
var more = band.querySelector("[data-annot-more]");
|
||||||
|
if (more) chipsEl.appendChild(more);
|
||||||
|
}}
|
||||||
|
if (reduce || narrow || items.length > MAX_VISIBLE_ANNOTS) {{
|
||||||
|
block.classList.add("is-keyed");
|
||||||
|
band.classList.add("is-keyed");
|
||||||
|
items.forEach(function (it, i) {{
|
||||||
|
it.chip.setAttribute("data-annot-key", String(i + 1));
|
||||||
|
}});
|
||||||
|
return;
|
||||||
|
}}
|
||||||
|
block.classList.remove("is-keyed");
|
||||||
|
band.classList.remove("is-keyed");
|
||||||
|
// Mid-bottom of mark → mid-top of chip: vertical, horizontal rail, short stub.
|
||||||
|
var blockRect = block.getBoundingClientRect();
|
||||||
|
var bw = Math.max(1, block.offsetWidth);
|
||||||
|
var bh = Math.max(1, block.offsetHeight);
|
||||||
|
var svgNS = "http://www.w3.org/2000/svg";
|
||||||
|
var svg = document.createElementNS(svgNS, "svg");
|
||||||
|
svg.setAttribute("width", String(bw));
|
||||||
|
svg.setAttribute("height", String(bh));
|
||||||
|
svg.setAttribute("viewBox", "0 0 " + bw + " " + bh);
|
||||||
|
svg.setAttribute("aria-hidden", "true");
|
||||||
|
items.forEach(function (it) {{
|
||||||
|
var a = it.anchor.getBoundingClientRect();
|
||||||
|
var c = it.chip.getBoundingClientRect();
|
||||||
|
var x0 = a.left + a.width / 2 - blockRect.left;
|
||||||
|
var y0 = a.bottom - blockRect.top + 1;
|
||||||
|
var x1 = c.left + c.width / 2 - blockRect.left;
|
||||||
|
var y1 = c.top - blockRect.top;
|
||||||
|
if (y1 < y0 + 8) {{
|
||||||
|
y1 = y0 + 12;
|
||||||
|
}}
|
||||||
|
// Short stub into chip top-center; rail sits above that.
|
||||||
|
var stub = Math.min(10, Math.max(6, (y1 - y0) * 0.28));
|
||||||
|
var yRail = y1 - stub;
|
||||||
|
if (yRail < y0 + 4) {{
|
||||||
|
yRail = (y0 + y1) / 2;
|
||||||
|
}}
|
||||||
|
var path = document.createElementNS(svgNS, "path");
|
||||||
|
path.setAttribute("class", "annot-leader annot-" + it.kind);
|
||||||
|
path.setAttribute("stroke", leaderColor(it.kind));
|
||||||
|
// Orthogonal: down from mark mid → across → short down to chip mid.
|
||||||
|
path.setAttribute(
|
||||||
|
"d",
|
||||||
|
"M " + x0.toFixed(1) + " " + y0.toFixed(1) +
|
||||||
|
" L " + x0.toFixed(1) + " " + yRail.toFixed(1) +
|
||||||
|
" L " + x1.toFixed(1) + " " + yRail.toFixed(1) +
|
||||||
|
" L " + x1.toFixed(1) + " " + y1.toFixed(1)
|
||||||
|
);
|
||||||
|
svg.appendChild(path);
|
||||||
|
}});
|
||||||
|
leaders.appendChild(svg);
|
||||||
|
}}
|
||||||
|
|
||||||
|
function layoutAll() {{
|
||||||
|
bands.forEach(layoutBand);
|
||||||
|
}}
|
||||||
|
layoutAll();
|
||||||
|
// Second pass after fonts/layout settle (first paint often has zero chip width).
|
||||||
|
requestAnimationFrame(function () {{ layoutAll(); }});
|
||||||
|
if (document.documentElement.dataset.annotLeadersRo === "1") return;
|
||||||
|
document.documentElement.dataset.annotLeadersRo = "1";
|
||||||
|
if (typeof ResizeObserver !== "undefined") {{
|
||||||
|
var ro = new ResizeObserver(function () {{ layoutAll(); }});
|
||||||
|
bands.forEach(function (b) {{
|
||||||
|
ro.observe(b);
|
||||||
|
var blk = b.closest(".doc-block");
|
||||||
|
if (blk) ro.observe(blk);
|
||||||
|
}});
|
||||||
|
var surface = document.querySelector(".document-surface");
|
||||||
|
if (surface) ro.observe(surface);
|
||||||
|
}}
|
||||||
|
window.addEventListener("resize", layoutAll);
|
||||||
|
|
||||||
|
document.querySelectorAll("[data-annot-more]").forEach(function (btn) {{
|
||||||
|
if (btn.dataset.bound === "1") return;
|
||||||
|
btn.dataset.bound = "1";
|
||||||
|
btn.addEventListener("click", function () {{
|
||||||
|
var band = btn.closest("[data-annot-band]");
|
||||||
|
if (!band) return;
|
||||||
|
band.classList.add("is-expanded");
|
||||||
|
btn.hidden = true;
|
||||||
|
layoutAll();
|
||||||
|
}});
|
||||||
|
}});
|
||||||
|
document.querySelectorAll(".annot-chip").forEach(function (chip) {{
|
||||||
|
if (chip.dataset.focusBound === "1") return;
|
||||||
|
chip.dataset.focusBound = "1";
|
||||||
|
chip.addEventListener("mouseenter", function () {{
|
||||||
|
var id = chip.getAttribute("data-annot-id");
|
||||||
|
if (!id) return;
|
||||||
|
var a = document.querySelector('.mq-anchor[data-annot-id="' + id + '"]');
|
||||||
|
if (a) a.classList.add("is-focus");
|
||||||
|
chip.classList.add("is-focus");
|
||||||
|
}});
|
||||||
|
chip.addEventListener("mouseleave", function () {{
|
||||||
|
var id = chip.getAttribute("data-annot-id");
|
||||||
|
if (!id) return;
|
||||||
|
var a = document.querySelector('.mq-anchor[data-annot-id="' + id + '"]');
|
||||||
|
if (a) a.classList.remove("is-focus");
|
||||||
|
chip.classList.remove("is-focus");
|
||||||
|
}});
|
||||||
|
}});
|
||||||
|
}}
|
||||||
|
|
||||||
if (document.readyState === "loading") {{
|
if (document.readyState === "loading") {{
|
||||||
document.addEventListener("DOMContentLoaded", function () {{
|
document.addEventListener("DOMContentLoaded", function () {{
|
||||||
initForeignCards();
|
initForeignCards();
|
||||||
initOutlineSearch();
|
initOutlineSearch();
|
||||||
initStreamPanel();
|
initStreamPanel();
|
||||||
initVarsPanel();
|
initVarsPanel();
|
||||||
|
initAnnotLeaders();
|
||||||
|
initCallPickers();
|
||||||
|
initLoopPickers();
|
||||||
}});
|
}});
|
||||||
}} else {{
|
}} else {{
|
||||||
initForeignCards();
|
initForeignCards();
|
||||||
initOutlineSearch();
|
initOutlineSearch();
|
||||||
initStreamPanel();
|
initStreamPanel();
|
||||||
initVarsPanel();
|
initVarsPanel();
|
||||||
|
initAnnotLeaders();
|
||||||
|
initCallPickers();
|
||||||
|
initLoopPickers();
|
||||||
}}
|
}}
|
||||||
|
|
||||||
function initOutlineSearch() {{
|
function initOutlineSearch() {{
|
||||||
@@ -2293,6 +2951,9 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
|
|||||||
.to_string(),
|
.to_string(),
|
||||||
_ => String::new(),
|
_ => String::new(),
|
||||||
};
|
};
|
||||||
|
let trace_safe = vm
|
||||||
|
.trace_json
|
||||||
|
.replace("</", "<\\/");
|
||||||
let main = format!(
|
let main = format!(
|
||||||
r#"
|
r#"
|
||||||
<script>
|
<script>
|
||||||
@@ -2300,6 +2961,7 @@ window.MARQDO_VIEW_LIVE = {live};
|
|||||||
window.MARQDO_FILE_PATH = {path_js};
|
window.MARQDO_FILE_PATH = {path_js};
|
||||||
window.MARQDO_AUTO_STREAM = {auto_stream};
|
window.MARQDO_AUTO_STREAM = {auto_stream};
|
||||||
</script>
|
</script>
|
||||||
|
<script type="application/json" id="mq-view-trace">{trace}</script>
|
||||||
<h1 class="page">{title}<span class="status-pill {status}">{status_label}</span></h1>
|
<h1 class="page">{title}<span class="status-pill {status}">{status_label}</span></h1>
|
||||||
<p class="meta">{rel}</p>
|
<p class="meta">{rel}</p>
|
||||||
<section class="block">
|
<section class="block">
|
||||||
@@ -2322,6 +2984,11 @@ window.MARQDO_AUTO_STREAM = {auto_stream};
|
|||||||
live = live_flag,
|
live = live_flag,
|
||||||
path_js = escape_js_string(rel),
|
path_js = escape_js_string(rel),
|
||||||
auto_stream = if vm.auto_stream { "true" } else { "false" },
|
auto_stream = if vm.auto_stream { "true" } else { "false" },
|
||||||
|
trace = if trace_safe.is_empty() {
|
||||||
|
"{}"
|
||||||
|
} else {
|
||||||
|
trace_safe.as_str()
|
||||||
|
},
|
||||||
title = escape(title),
|
title = escape(title),
|
||||||
status = status,
|
status = status,
|
||||||
status_label = status_label,
|
status_label = status_label,
|
||||||
|
|||||||
+57
-13
@@ -1,8 +1,10 @@
|
|||||||
//! `marqdo view` — local HTML browser for `.mq.md` structure + output.
|
//! `marqdo view` — local HTML browser for `.mq.md` structure + output.
|
||||||
//! `marqdo debug` — separate debugger host (tree-walk breakpoints).
|
//! `marqdo debug` — separate debugger host (tree-walk breakpoints).
|
||||||
|
|
||||||
|
mod annot;
|
||||||
mod debug_api;
|
mod debug_api;
|
||||||
mod debug_page;
|
mod debug_page;
|
||||||
|
mod document;
|
||||||
mod html;
|
mod html;
|
||||||
mod output;
|
mod output;
|
||||||
mod render;
|
mod render;
|
||||||
@@ -23,9 +25,10 @@ use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
|
|||||||
use crate::input_feed::{effective_stdin, extract_frontmatter_stdin, split_stdin_text};
|
use crate::input_feed::{effective_stdin, extract_frontmatter_stdin, split_stdin_text};
|
||||||
use crate::view::debug_page::{build_debug_model, page_debug};
|
use crate::view::debug_page::{build_debug_model, page_debug};
|
||||||
use crate::view::html::{escape, page_file, page_index, LinkMode};
|
use crate::view::html::{escape, page_file, page_index, LinkMode};
|
||||||
|
use crate::view::annot::{build_view_annots, view_execution_report_json};
|
||||||
use crate::view::render::{
|
use crate::view::render::{
|
||||||
collect_input_prompts, render_bindings_html, render_module_structure, render_right_rail,
|
collect_input_prompts, render_bindings_html, render_module_structure,
|
||||||
uses_stream_panel, FileViewModel,
|
render_module_structure_with_annots, render_right_rail, uses_stream_panel, FileViewModel,
|
||||||
};
|
};
|
||||||
use crate::{run_file_capture, RunOptions};
|
use crate::{run_file_capture, RunOptions};
|
||||||
|
|
||||||
@@ -212,6 +215,24 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
|
|||||||
let json = files_json(&root.files);
|
let json = files_json(&root.files);
|
||||||
respond_json(request, json)
|
respond_json(request, json)
|
||||||
}
|
}
|
||||||
|
"/api/view-trace" => {
|
||||||
|
let rel = query_param(query, "path").unwrap_or_default();
|
||||||
|
if rel.is_empty() {
|
||||||
|
return respond_json_status(
|
||||||
|
request,
|
||||||
|
StatusCode(400),
|
||||||
|
serde_json::json!({ "ok": false, "error": "missing path" }).to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let resolved = resolve_rel(root, &rel)?;
|
||||||
|
let vm = build_file_view(root, &resolved, &rel, &[], true)?;
|
||||||
|
let body = if vm.trace_json.is_empty() {
|
||||||
|
serde_json::json!({ "version": 1, "path": rel, "ok": vm.ok, "calls": [], "events": [], "bindings_final": {} }).to_string()
|
||||||
|
} else {
|
||||||
|
vm.trace_json
|
||||||
|
};
|
||||||
|
respond_json(request, body)
|
||||||
|
}
|
||||||
"/api/events" => api_events(request),
|
"/api/events" => api_events(request),
|
||||||
_ => {
|
_ => {
|
||||||
let resp = Response::from_string("not found").with_status_code(StatusCode(404));
|
let resp = Response::from_string("not found").with_status_code(StatusCode(404));
|
||||||
@@ -345,6 +366,7 @@ pub(crate) fn build_file_view(
|
|||||||
opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) };
|
opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) };
|
||||||
// Optional: sandbox to the whole view tree so sibling folders are reachable.
|
// Optional: sandbox to the whole view tree so sibling folders are reachable.
|
||||||
opts.fs_root = Some(root.root.clone());
|
opts.fs_root = Some(root.root.clone());
|
||||||
|
let mut captured: Option<crate::capture::RunCapture> = None;
|
||||||
let (stdout, stderr, ok, plots, mut bindings_html) = if awaiting_input || auto_stream {
|
let (stdout, stderr, ok, plots, mut bindings_html) = if awaiting_input || auto_stream {
|
||||||
(
|
(
|
||||||
String::new(),
|
String::new(),
|
||||||
@@ -355,13 +377,13 @@ pub(crate) fn build_file_view(
|
|||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
match run_file_capture(abs, &opts) {
|
match run_file_capture(abs, &opts) {
|
||||||
Ok(cap) => (
|
Ok(cap) => {
|
||||||
cap.stdout,
|
let stdout = cap.stdout.clone();
|
||||||
String::new(),
|
let plots = cap.plots.iter().map(|p| p.svg.clone()).collect();
|
||||||
true,
|
let bindings_html = render_bindings_html(&cap.bindings);
|
||||||
cap.plots.into_iter().map(|p| p.svg).collect(),
|
captured = Some(cap);
|
||||||
render_bindings_html(&cap.bindings),
|
(stdout, String::new(), true, plots, bindings_html)
|
||||||
),
|
}
|
||||||
Err(e) => (
|
Err(e) => (
|
||||||
String::new(),
|
String::new(),
|
||||||
tidy_user_error(&format!("{e:#}"), abs, rel),
|
tidy_user_error(&format!("{e:#}"), abs, rel),
|
||||||
@@ -375,10 +397,14 @@ pub(crate) fn build_file_view(
|
|||||||
if !awaiting_input && !auto_stream {
|
if !awaiting_input && !auto_stream {
|
||||||
if let Ok(next) = fs::read_to_string(abs) {
|
if let Ok(next) = fs::read_to_string(abs) {
|
||||||
source = next;
|
source = next;
|
||||||
if let Ok(module) = crate::parse::parse_source(&source) {
|
}
|
||||||
structure = render_module_structure(&module, &source);
|
if let Ok(module) = crate::parse::parse_source(&source) {
|
||||||
module_opt = Some(module);
|
let annots = match &captured {
|
||||||
}
|
Some(cap) => build_view_annots(&module, &source, cap),
|
||||||
|
None => Vec::new(),
|
||||||
|
};
|
||||||
|
structure = render_module_structure_with_annots(&module, &source, &annots);
|
||||||
|
module_opt = Some(module);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let wb = crate::view::render::render_writeback_outline(&source);
|
let wb = crate::view::render::render_writeback_outline(&source);
|
||||||
@@ -392,6 +418,10 @@ pub(crate) fn build_file_view(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
let trace_json = match &captured {
|
||||||
|
Some(cap) => view_execution_report_json(rel, ok, cap),
|
||||||
|
None => String::new(),
|
||||||
|
};
|
||||||
Ok(FileViewModel {
|
Ok(FileViewModel {
|
||||||
rel_path: rel.to_string(),
|
rel_path: rel.to_string(),
|
||||||
source,
|
source,
|
||||||
@@ -407,6 +437,7 @@ pub(crate) fn build_file_view(
|
|||||||
show_stream,
|
show_stream,
|
||||||
plots,
|
plots,
|
||||||
bindings_html: std::mem::take(&mut bindings_html),
|
bindings_html: std::mem::take(&mut bindings_html),
|
||||||
|
trace_json,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -641,6 +672,17 @@ fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> {
|
|||||||
// Keep the terminal frame small — tokens already streamed via bus.
|
// Keep the terminal frame small — tokens already streamed via bus.
|
||||||
let preview: String = cap.stdout.chars().take(500).collect();
|
let preview: String = cap.stdout.chars().take(500).collect();
|
||||||
let bindings_html = render_bindings_html(&cap.bindings);
|
let bindings_html = render_bindings_html(&cap.bindings);
|
||||||
|
let source_now = fs::read_to_string(&abs).unwrap_or(source);
|
||||||
|
let (structure_html, trace_json) = match crate::parse::parse_source(&source_now) {
|
||||||
|
Ok(module) => {
|
||||||
|
let annots = build_view_annots(&module, &source_now, &cap);
|
||||||
|
(
|
||||||
|
render_module_structure_with_annots(&module, &source_now, &annots),
|
||||||
|
view_execution_report_json(&rel_clone, true, &cap),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Err(_) => (String::new(), String::new()),
|
||||||
|
};
|
||||||
let done = serde_json::json!({
|
let done = serde_json::json!({
|
||||||
"type": "done",
|
"type": "done",
|
||||||
"run_id": run_id,
|
"run_id": run_id,
|
||||||
@@ -648,6 +690,8 @@ fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> {
|
|||||||
"ok": true,
|
"ok": true,
|
||||||
"result": preview,
|
"result": preview,
|
||||||
"bindings_html": bindings_html,
|
"bindings_html": bindings_html,
|
||||||
|
"structure_html": structure_html,
|
||||||
|
"trace_json": trace_json,
|
||||||
});
|
});
|
||||||
crate::host::event_bus::EventBus::global().publish_json(&done.to_string());
|
crate::host::event_bus::EventBus::global().publish_json(&done.to_string());
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-1
@@ -32,11 +32,17 @@ pub fn write_static(opts: OutputOptions) -> Result<()> {
|
|||||||
vm.ok = true;
|
vm.ok = true;
|
||||||
vm.plots.clear();
|
vm.plots.clear();
|
||||||
vm.bindings_html = String::from(r#"<p class="vars-skipped">skipped</p>"#);
|
vm.bindings_html = String::from(r#"<p class="vars-skipped">skipped</p>"#);
|
||||||
// Rebuild outline so Variables shows skipped.
|
vm.trace_json.clear();
|
||||||
|
// Rebuild outline + Structure without run annotations.
|
||||||
if let Ok(module) = crate::parse::parse_source(&vm.source) {
|
if let Ok(module) = crate::parse::parse_source(&vm.source) {
|
||||||
let wb = crate::view::render::render_writeback_outline(&vm.source);
|
let wb = crate::view::render::render_writeback_outline(&vm.source);
|
||||||
vm.outline_html =
|
vm.outline_html =
|
||||||
crate::view::render::render_right_rail(&module, &vm.bindings_html, &wb);
|
crate::view::render::render_right_rail(&module, &vm.bindings_html, &wb);
|
||||||
|
vm.structure_html = crate::view::render::render_module_structure_with_annots(
|
||||||
|
&module,
|
||||||
|
&vm.source,
|
||||||
|
&[],
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let links = LinkMode::Static {
|
let links = LinkMode::Static {
|
||||||
|
|||||||
+185
-17
@@ -45,6 +45,8 @@ pub struct FileViewModel {
|
|||||||
pub plots: Vec<String>,
|
pub plots: Vec<String>,
|
||||||
/// HTML for Variables panel (entry bindings after run).
|
/// HTML for Variables panel (entry bindings after run).
|
||||||
pub bindings_html: String,
|
pub bindings_html: String,
|
||||||
|
/// ViewExecutionReport JSON for AI / call-picker (empty if no run).
|
||||||
|
pub trace_json: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Collect prompt strings from every `input` / `输入` call in the module (pre-order).
|
/// Collect prompt strings from every `input` / `输入` call in the module (pre-order).
|
||||||
@@ -187,14 +189,36 @@ fn prompt_expr_text(expr: &Expr) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Browse Structure without run annotations (empty callouts).
|
||||||
pub fn render_module_structure(module: &Module, source: &str) -> String {
|
pub fn render_module_structure(module: &Module, source: &str) -> String {
|
||||||
render_module_structure_mode(module, source, StructureMode::Browse)
|
render_module_structure_mode(module, source, StructureMode::Browse)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Browse Structure: document surface with optional result annotations.
|
||||||
|
pub fn render_module_structure_with_annots(
|
||||||
|
module: &Module,
|
||||||
|
source: &str,
|
||||||
|
annots: &[crate::view::annot::ViewAnnot],
|
||||||
|
) -> String {
|
||||||
|
crate::view::document::render_module_document(module, source, annots)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn render_module_structure_mode(
|
pub fn render_module_structure_mode(
|
||||||
module: &Module,
|
module: &Module,
|
||||||
source: &str,
|
source: &str,
|
||||||
mode: StructureMode,
|
mode: StructureMode,
|
||||||
|
) -> String {
|
||||||
|
match mode {
|
||||||
|
StructureMode::Browse => render_module_structure_with_annots(module, source, &[]),
|
||||||
|
StructureMode::Debug => render_module_structure_cards(module, source, mode),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Legacy AST-card Structure (debug + tests that need card markup).
|
||||||
|
pub fn render_module_structure_cards(
|
||||||
|
module: &Module,
|
||||||
|
source: &str,
|
||||||
|
mode: StructureMode,
|
||||||
) -> String {
|
) -> String {
|
||||||
let lines = classify_source(source);
|
let lines = classify_source(source);
|
||||||
let writebacks = writeback::writeback_map(source);
|
let writebacks = writeback::writeback_map(source);
|
||||||
@@ -905,7 +929,7 @@ fn emit_comments(lines: &[ClassifiedLine], from_line: u32, before_line: u32) ->
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Render narrative comments as Markdown (links, emphasis, code, lists, …).
|
/// Render narrative comments as Markdown (links, emphasis, code, lists, …).
|
||||||
fn comment_markdown_to_html(md: &str) -> String {
|
pub(crate) fn comment_markdown_to_html(md: &str) -> String {
|
||||||
let mut opts = Options::empty();
|
let mut opts = Options::empty();
|
||||||
opts.insert(Options::ENABLE_STRIKETHROUGH);
|
opts.insert(Options::ENABLE_STRIKETHROUGH);
|
||||||
opts.insert(Options::ENABLE_TABLES);
|
opts.insert(Options::ENABLE_TABLES);
|
||||||
@@ -947,10 +971,11 @@ fn render_fun(
|
|||||||
("chip", "explicit + param")
|
("chip", "explicit + param")
|
||||||
};
|
};
|
||||||
s.push_str(&format!(
|
s.push_str(&format!(
|
||||||
"<span class=\"{cls}\" title=\"{title}\">{name}</span>",
|
"<span class=\"{cls}\" data-param-name=\"{name}\" data-fn=\"{fn}\" title=\"{title}\">{name}<span class=\"chip-val\"></span></span>",
|
||||||
cls = cls,
|
cls = cls,
|
||||||
title = title,
|
title = title,
|
||||||
name = escape(&p.name),
|
name = escape(&p.name),
|
||||||
|
fn = escape(&fun.name),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
s.push_str("</div>");
|
s.push_str("</div>");
|
||||||
@@ -1045,17 +1070,89 @@ fn stmt_end_line(stmt: &Stmt) -> u32 {
|
|||||||
|
|
||||||
fn output_card(line: u32, writebacks: &HashMap<u32, String>) -> String {
|
fn output_card(line: u32, writebacks: &HashMap<u32, String>) -> String {
|
||||||
match writebacks.get(&line) {
|
match writebacks.get(&line) {
|
||||||
Some(body) => {
|
Some(body) => render_output_card(line, body),
|
||||||
let badges = writeback_badges(body);
|
|
||||||
format!(
|
|
||||||
r#"<div class="card output-card" id="wb-{line}"><div class="wb-badges">{badges}</div><pre class="output-body">{}</pre></div>"#,
|
|
||||||
escape(body)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
None => String::new(),
|
None => String::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Live view + static site: text `<pre>` and/or `<img>` for image writebacks.
|
||||||
|
pub fn render_output_card(line: u32, combined: &str) -> String {
|
||||||
|
if combined.trim().is_empty() {
|
||||||
|
return String::new();
|
||||||
|
}
|
||||||
|
let badges = writeback_badges(combined);
|
||||||
|
let mut body_html = String::new();
|
||||||
|
let mut buf_text = String::new();
|
||||||
|
let flush_text = |buf: &mut String, out: &mut String| {
|
||||||
|
if buf.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
out.push_str(&format!(
|
||||||
|
r#"<pre class="output-body">{}</pre>"#,
|
||||||
|
escape(buf.trim_end())
|
||||||
|
));
|
||||||
|
buf.clear();
|
||||||
|
};
|
||||||
|
for line_s in combined.lines() {
|
||||||
|
let t = line_s.trim();
|
||||||
|
if let Some(url) = extract_md_image_url(t) {
|
||||||
|
flush_text(&mut buf_text, &mut body_html);
|
||||||
|
body_html.push_str(&format!(
|
||||||
|
r#"<figure class="wb-figure"><img class="wb-image" src="{src}" alt="writeback"/><figcaption class="wb-image-url">{cap}</figcaption></figure>"#,
|
||||||
|
src = escape(&url),
|
||||||
|
cap = escape(&url),
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
if !buf_text.is_empty() {
|
||||||
|
buf_text.push('\n');
|
||||||
|
}
|
||||||
|
buf_text.push_str(line_s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush_text(&mut buf_text, &mut body_html);
|
||||||
|
let has_img = body_html.contains("wb-image");
|
||||||
|
format!(
|
||||||
|
r#"<div class="card output-card{img_cls}" id="wb-{line}" data-wb="1"><div class="wb-badges">{badges}</div>{body}</div>"#,
|
||||||
|
line = line,
|
||||||
|
img_cls = if has_img { " output-card-image" } else { "" },
|
||||||
|
badges = badges,
|
||||||
|
body = body_html,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_md_image_url(line: &str) -> Option<String> {
|
||||||
|
let t = line.trim();
|
||||||
|
let rest = t.strip_prefix("?;
|
||||||
|
let after = &rest[alt_end + 2..];
|
||||||
|
let url_end = after.rfind(')')?;
|
||||||
|
let url = after[..url_end].trim();
|
||||||
|
if url.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(url.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Document-surface marker for a writeback source line (comment or image).
|
||||||
|
pub fn render_writeback_source_line(line_no: u32, text: &str) -> String {
|
||||||
|
let trimmed = text.trim();
|
||||||
|
let is_image = trimmed.starts_with("![") && trimmed.contains("marqdo-out");
|
||||||
|
let kind = if is_image { "image" } else { "comment" };
|
||||||
|
let label = if is_image {
|
||||||
|
"writeback · image"
|
||||||
|
} else {
|
||||||
|
"writeback"
|
||||||
|
};
|
||||||
|
format!(
|
||||||
|
r#"<div class="doc-block doc-writeback" data-line="{line}" data-wb-kind="{kind}"><span class="wb-source-badge">{label}</span><code class="wb-source-text">{text}</code></div>"#,
|
||||||
|
line = line_no,
|
||||||
|
kind = kind,
|
||||||
|
label = label,
|
||||||
|
text = escape(trimmed),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn writeback_badges(body: &str) -> String {
|
fn writeback_badges(body: &str) -> String {
|
||||||
let mut keys = Vec::new();
|
let mut keys = Vec::new();
|
||||||
for line in body.lines() {
|
for line in body.lines() {
|
||||||
@@ -1162,12 +1259,14 @@ fn render_stmt(
|
|||||||
<span class="badge">code</span>
|
<span class="badge">code</span>
|
||||||
<code class="expr">`{name}` =</code>
|
<code class="expr">`{name}` =</code>
|
||||||
<span class="code-lang">{lang}</span>
|
<span class="code-lang">{lang}</span>
|
||||||
|
</div>
|
||||||
|
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
|
||||||
|
<div class="code-foot">
|
||||||
<div class="code-actions">
|
<div class="code-actions">
|
||||||
<input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/>
|
<input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/>
|
||||||
<button type="button" class="code-run">Run</button>
|
<button type="button" class="code-run">Run</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
|
|
||||||
<pre class="code-out" hidden></pre>
|
<pre class="code-out" hidden></pre>
|
||||||
</div>"#,
|
</div>"#,
|
||||||
lang = lang,
|
lang = lang,
|
||||||
@@ -1412,6 +1511,49 @@ fn expr_prec(expr: &Expr, parent_prec: u8) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Best-effort ASCII formula → TeX for KaTeX in view Structure.
|
/// Best-effort ASCII formula → TeX for KaTeX in view Structure.
|
||||||
|
pub(crate) fn formula_ascii_to_tex_pub(ascii: &str) -> String {
|
||||||
|
formula_ascii_to_tex(ascii)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Formula assign card for document surface embedding (single visual layer).
|
||||||
|
pub(crate) fn render_formula_assign_card(name: &str, tex: &str) -> String {
|
||||||
|
format!(
|
||||||
|
r#"<div class="card formula-card" data-formula-name="{name}">
|
||||||
|
<div class="formula-head"><span class="badge">formula</span> <span class="formula-name">{name}</span></div>
|
||||||
|
<div class="math-block">$${tex}$$</div>
|
||||||
|
</div>"#,
|
||||||
|
name = escape(name),
|
||||||
|
tex = escape(tex),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Foreign code assign card for document surface embedding (single visual layer).
|
||||||
|
/// Head → body → foot(actions) so the source is never collapsed under the Run row.
|
||||||
|
pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> String {
|
||||||
|
let placeholder = escape(&crate::foreign::default_cmd_display(lang));
|
||||||
|
format!(
|
||||||
|
r#"<div class="card code-card" data-lang="{lang}" data-code-name="{name}">
|
||||||
|
<div class="code-head">
|
||||||
|
<span class="badge">code</span>
|
||||||
|
<span class="code-name">{name}</span>
|
||||||
|
<span class="code-lang">{lang}</span>
|
||||||
|
</div>
|
||||||
|
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
|
||||||
|
<div class="code-foot">
|
||||||
|
<div class="code-actions">
|
||||||
|
<input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/>
|
||||||
|
<button type="button" class="code-run">Run</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<pre class="code-out" hidden></pre>
|
||||||
|
</div>"#,
|
||||||
|
lang = escape(lang),
|
||||||
|
name = escape(name),
|
||||||
|
placeholder = placeholder,
|
||||||
|
src = escape(source),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn formula_ascii_to_tex(ascii: &str) -> String {
|
fn formula_ascii_to_tex(ascii: &str) -> String {
|
||||||
let mut out = String::new();
|
let mut out = String::new();
|
||||||
let chars: Vec<char> = ascii.chars().collect();
|
let chars: Vec<char> = ascii.chars().collect();
|
||||||
@@ -1525,7 +1667,7 @@ mod tests {
|
|||||||
let src = include_str!("../../tests/structure/nested-call.mq.md");
|
let src = include_str!("../../tests/structure/nested-call.mq.md");
|
||||||
let module = crate::parse::parse_source(src).unwrap();
|
let module = crate::parse::parse_source(src).unwrap();
|
||||||
let html = render_module_structure(&module, src);
|
let html = render_module_structure(&module, src);
|
||||||
assert!(html.contains("comment-card"));
|
assert!(html.contains("doc-prose") || html.contains("打印一句问候"), "{html}");
|
||||||
assert!(html.contains("print"));
|
assert!(html.contains("print"));
|
||||||
assert!(!html.contains("Binary {"));
|
assert!(!html.contains("Binary {"));
|
||||||
assert!(!html.contains("Literal(Int"));
|
assert!(!html.contains("Literal(Int"));
|
||||||
@@ -1536,9 +1678,9 @@ mod tests {
|
|||||||
let src = "段首说明\n续行仍属同段\n\n下一段\n\n# main\n\n> print text=x\n";
|
let src = "段首说明\n续行仍属同段\n\n下一段\n\n# main\n\n> print text=x\n";
|
||||||
let module = crate::parse::parse_source(src).unwrap();
|
let module = crate::parse::parse_source(src).unwrap();
|
||||||
let html = render_module_structure(&module, src);
|
let html = render_module_structure(&module, src);
|
||||||
let cards = html.matches("comment-card").count();
|
let blocks = html.matches("doc-prose").count();
|
||||||
assert_eq!(cards, 2, "blank line should split comment paragraphs: {html}");
|
assert!(blocks >= 2, "blank line should split comment paragraphs: {html}");
|
||||||
assert!(html.contains("段首说明 续行仍属同段") || html.contains("段首说明</p>"));
|
assert!(html.contains("段首说明 续行仍属同段") || html.contains("段首说明</p>") || html.contains("段首说明"));
|
||||||
assert!(html.contains("下一段"));
|
assert!(html.contains("下一段"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1575,11 +1717,10 @@ mod tests {
|
|||||||
let src = "---\ntitle: t\nimport text:lib/text.mq.md\n---\n\n# main\n\n> print text=hi\n";
|
let src = "---\ntitle: t\nimport text:lib/text.mq.md\n---\n\n# main\n\n> print text=hi\n";
|
||||||
let local = crate::parse::parse_source(src).unwrap();
|
let local = crate::parse::parse_source(src).unwrap();
|
||||||
let html = render_module_structure(&local, src);
|
let html = render_module_structure(&local, src);
|
||||||
assert!(html.contains("badge\">import"), "{html}");
|
assert!(html.contains("doc-imports") || html.contains("lib/text.mq.md"), "{html}");
|
||||||
assert!(html.contains("lib/text.mq.md"), "{html}");
|
assert!(html.contains("lib/text.mq.md"), "{html}");
|
||||||
assert!(html.contains("main"), "{html}");
|
assert!(html.contains("main"), "{html}");
|
||||||
assert!(!html.contains("trim"), "{html}");
|
assert!(!html.contains("trim"), "{html}");
|
||||||
assert!(html.contains("class=\"stmt\""), "{html}");
|
|
||||||
assert!(html.contains("data-line="), "{html}");
|
assert!(html.contains("data-line="), "{html}");
|
||||||
assert_eq!(local.functions.len(), 1);
|
assert_eq!(local.functions.len(), 1);
|
||||||
assert_eq!(local.functions[0].name, "main");
|
assert_eq!(local.functions[0].name, "main");
|
||||||
@@ -1624,9 +1765,21 @@ mod tests {
|
|||||||
let browse = render_module_structure_mode(&module, src, StructureMode::Browse);
|
let browse = render_module_structure_mode(&module, src, StructureMode::Browse);
|
||||||
let debug = render_module_structure_mode(&module, src, StructureMode::Debug);
|
let debug = render_module_structure_mode(&module, src, StructureMode::Debug);
|
||||||
assert!(browse.contains("id=\"fn-"), "{browse}");
|
assert!(browse.contains("id=\"fn-"), "{browse}");
|
||||||
|
assert!(browse.contains("document-surface"), "{browse}");
|
||||||
assert!(!browse.contains("bp-gutter"), "{browse}");
|
assert!(!browse.contains("bp-gutter"), "{browse}");
|
||||||
assert!(debug.contains("bp-gutter"), "{debug}");
|
assert!(debug.contains("bp-gutter"), "{debug}");
|
||||||
assert!(debug.contains("id=\"stmt-"), "{debug}");
|
assert!(debug.contains("id=\"stmt-"), "{debug}");
|
||||||
|
assert!(debug.contains("card"), "{debug}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn browse_preserves_prose_unified_line() {
|
||||||
|
let src = include_str!("../../tests/markup-v03/inc-prose.mq.md");
|
||||||
|
let module = crate::parse::parse_source(src).unwrap();
|
||||||
|
let html = render_module_structure(&module, src);
|
||||||
|
assert!(html.contains("对于输入变量"), "{html}");
|
||||||
|
assert!(html.contains("mq-anchor"), "{html}");
|
||||||
|
assert!(!html.contains("badge\">bind"), "{html}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1663,6 +1816,20 @@ mod tests {
|
|||||||
assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}");
|
assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn output_card_renders_image_writeback() {
|
||||||
|
let html = render_output_card(3, "[ok]\n");
|
||||||
|
assert!(html.contains("output-card-image"), "{html}");
|
||||||
|
assert!(html.contains(r#"src="plots/a.svg""#), "{html}");
|
||||||
|
assert!(html.contains("wb-ok") || html.contains(">ok<"), "{html}");
|
||||||
|
let text = render_output_card(1, "plain-42");
|
||||||
|
assert!(text.contains("output-body"), "{text}");
|
||||||
|
assert!(!text.contains("wb-image"), "{text}");
|
||||||
|
let src = render_writeback_source_line(4, "");
|
||||||
|
assert!(src.contains(r#"data-wb-kind="image""#), "{src}");
|
||||||
|
assert!(src.contains("writeback · image"), "{src}");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn structure_marks_inferred_params() {
|
fn structure_marks_inferred_params() {
|
||||||
let src = include_str!("../../tests/markup-v03/inc-prose.mq.md");
|
let src = include_str!("../../tests/markup-v03/inc-prose.mq.md");
|
||||||
@@ -1675,7 +1842,8 @@ mod tests {
|
|||||||
assert!(add.params.iter().any(|p| p.name == "n" && p.inferred));
|
assert!(add.params.iter().any(|p| p.name == "n" && p.inferred));
|
||||||
let html = render_module_structure(&module, src);
|
let html = render_module_structure(&module, src);
|
||||||
assert!(
|
assert!(
|
||||||
html.contains("chip inferred") && html.contains(">n<"),
|
html.contains("chip inferred")
|
||||||
|
&& (html.contains(">n<") || html.contains(r#"data-param-name="n""#)),
|
||||||
"expected inferred chip for n: {html}"
|
"expected inferred chip for n: {html}"
|
||||||
);
|
);
|
||||||
let outline = render_function_outline(&module);
|
let outline = render_function_outline(&module);
|
||||||
|
|||||||
@@ -3365,3 +3365,33 @@ fn markup_v03_decl_ident_only() {
|
|||||||
fn markup_v03_bold_expr() {
|
fn markup_v03_bold_expr() {
|
||||||
assert_out_v03("tests/markup-v03/bold-expr.mq.md", "42");
|
assert_out_v03("tests/markup-v03/bold-expr.mq.md", "42");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn markup_v03_formula_meta_var() {
|
||||||
|
assert_out_v03("tests/markup-v03/formula-meta-var.mq.md", "x^2 - 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn markup_v03_inline_dollar_formula() {
|
||||||
|
assert_out_v03("tests/markup-v03/inline-dollar-formula.mq.md", "x + 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn markup_v03_branch_arm_prose() {
|
||||||
|
assert_out_v03("tests/markup-v03/branch-arm-prose.mq.md", "正");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn markup_v03_branch_cond_narrative() {
|
||||||
|
assert_out_v03("tests/markup-v03/branch-cond-narrative.mq.md", "正");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn markup_v03_foreach_narrative() {
|
||||||
|
assert_out_v03("tests/markup-v03/foreach-narrative.mq.md", "a\nb\n1\n2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn markup_v03_foreach_nested_link() {
|
||||||
|
assert_out_v03("tests/markup-v03/foreach-nested-link.mq.md", "x\ny");
|
||||||
|
}
|
||||||
@@ -17,6 +17,8 @@
|
|||||||
|
|
||||||
代码即文档叙述面(G1–G4):`module-hr` / `soft-emphasis` / `float-discount` / `dynamic-footnote` —— 设计见 [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md)。
|
代码即文档叙述面(G1–G4):`module-hr` / `soft-emphasis` / `float-discount` / `dynamic-footnote` —— 设计见 [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md)。
|
||||||
|
|
||||||
|
块公式 meta / 控制流叙述:`formula-meta-var` / `inline-dollar-formula` / `branch-arm-prose` / `branch-cond-narrative` / `foreach-narrative` / `foreach-nested-link` —— 见 [fence-meta-and-control-prose.md](../../doc/design/fence-meta-and-control-prose.md)。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo test --test gold markup_v03
|
cargo test --test gold markup_v03
|
||||||
marqdo run tests/markup-v03/inc-prose.mq.md
|
marqdo run tests/markup-v03/inc-prose.mq.md
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
---
|
||||||
|
title: v0.3 分支臂内叙述
|
||||||
|
description: 臂内 prose 不得逃逸;n>0 时仅 then
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
**n = 1**
|
||||||
|
|
||||||
|
1. `n` > 0
|
||||||
|
此时`n`为正,我们 **打印 内容="正"**
|
||||||
|
2. *
|
||||||
|
否则 **打印 内容="非正"**
|
||||||
|
|
||||||
|
*None*
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
---
|
||||||
|
title: v0.3 条件行夹叙述
|
||||||
|
description: 当`n`大于 0 时 / 否则 *
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
**n = 1**
|
||||||
|
|
||||||
|
1. 当`n`大于 0 时
|
||||||
|
我们 **打印 内容="正"**
|
||||||
|
2. 否则 *
|
||||||
|
我们 **打印 内容="非正"**
|
||||||
|
|
||||||
|
*None*
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: v0.3 循环头叙述糖
|
||||||
|
description: 对`xs`的每一项`项` / for each `item` in `ys`
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
`xs` =
|
||||||
|
|
||||||
|
| v |
|
||||||
|
|---|
|
||||||
|
| a |
|
||||||
|
| b |
|
||||||
|
|
||||||
|
- 对`xs`的每一项`项`
|
||||||
|
**打印 内容=`项`**
|
||||||
|
|
||||||
|
`ys` =
|
||||||
|
|
||||||
|
| v |
|
||||||
|
|---|
|
||||||
|
| 1 |
|
||||||
|
| 2 |
|
||||||
|
|
||||||
|
- for each `item` in `ys`
|
||||||
|
**print text=`item`**
|
||||||
|
|
||||||
|
*None*
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
---
|
||||||
|
title: v0.3 推荐循环头嵌套
|
||||||
|
description: `- [o](外层)` 内再 `- [i](内层)`
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
`外层` =
|
||||||
|
|
||||||
|
| a |
|
||||||
|
|---|
|
||||||
|
| x |
|
||||||
|
| y |
|
||||||
|
|
||||||
|
`内层` =
|
||||||
|
|
||||||
|
| b |
|
||||||
|
|---|
|
||||||
|
| 1 |
|
||||||
|
|
||||||
|
- [o](外层)
|
||||||
|
- [i](内层)
|
||||||
|
**print text=`o`**
|
||||||
|
|
||||||
|
*None*
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
---
|
||||||
|
title: v0.3 块公式 % marqdo: var=
|
||||||
|
description: 无空 RHS;块内 TeX 注释绑定 formula
|
||||||
|
import math:lib/math.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
$$
|
||||||
|
% marqdo: var=f
|
||||||
|
x^2 - 2
|
||||||
|
$$
|
||||||
|
|
||||||
|
**print text=`f`**
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
---
|
||||||
|
title: v0.3 行内 $ 传统绑定
|
||||||
|
description: `g` = $x+1$ → formula(无 % marqdo)
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
`g` = $x + 1$
|
||||||
|
|
||||||
|
**print text=`g`**
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
---
|
||||||
|
title: View 文档面演示(叙述 · 分支 · 循环)
|
||||||
|
description: 给 marqdo view Browse 用的稍长样例:散文保真、变量高亮、分支命中与循环次数标注
|
||||||
|
markup: v0.3
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
本页演示 **view 文档面**:叙述文字保留,可执行标记高亮,跑完后把变量值、分支命中与循环次数引出到段落下方。
|
||||||
|
|
||||||
|
先准备一份小测验的原始分数表`分数表`:
|
||||||
|
|
||||||
|
`分数表` =
|
||||||
|
|
||||||
|
| 分 |
|
||||||
|
|----|
|
||||||
|
| 92 |
|
||||||
|
| 67 |
|
||||||
|
| 45 |
|
||||||
|
| 88 |
|
||||||
|
|
||||||
|
我们用累加器`总分`和计数器`人数`从零开始,遍历每一行分数:
|
||||||
|
|
||||||
|
**总分 = 0**
|
||||||
|
**人数 = 0**
|
||||||
|
|
||||||
|
- [分](分数表)
|
||||||
|
**总分 = 总分 + 分**
|
||||||
|
**人数 = 人数 + 1**
|
||||||
|
> print text=录入分数 `分`
|
||||||
|
|
||||||
|
遍历结束后计算平均分`均分`(人数不为零时):
|
||||||
|
|
||||||
|
**均分 = 总分 / 人数**
|
||||||
|
|
||||||
|
接着按均分给出等级文案`等级`——这是一条三路分支:
|
||||||
|
|
||||||
|
1. `均分` >= 85
|
||||||
|
**等级 = "优秀"**
|
||||||
|
2. `均分` >= 60
|
||||||
|
**等级 = "及格"**
|
||||||
|
3. *
|
||||||
|
**等级 = "需补习"**
|
||||||
|
|
||||||
|
最后打印摘要,并两次调用下方的「等级说明」(便于 view 下拉切换调用帧):
|
||||||
|
|
||||||
|
> print text=人数 `人数` · 均分 `均分` · 等级 `等级`
|
||||||
|
**说明 = > 等级说明 等级=等级**
|
||||||
|
> print text=`说明`
|
||||||
|
**对照 = > 等级说明 等级="优秀"**
|
||||||
|
> print text=对照:`对照`
|
||||||
|
|
||||||
|
## 等级说明
|
||||||
|
|
||||||
|
对于输入变量`等级`,我们按字面再分支一次,返回一句说明文字。
|
||||||
|
|
||||||
|
1. `等级` == "优秀"
|
||||||
|
*"均分很高,保持节奏即可。"*
|
||||||
|
2. `等级` == "及格"
|
||||||
|
*"已过线,仍可把薄弱项补一补。"*
|
||||||
|
3. *
|
||||||
|
*"建议安排复习周,再测一次。"*
|
||||||
Reference in new issue
Block a user