Compare commits

...
2 Commits
Author SHA1 Message Date
cflmyandCursor 0a8f76d9b4 release: v1.3.3 — view document-surface Structure
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:18:51 +08:00
cflmyandCursor 4e2419b598 feat(view): document-surface Structure with frame-aware annotations
Browse Structure keeps narration and surfaces post-stmt values, branch
arms, and call/loop pickers; static `view output` shares the same render
path so exported HTML matches live view.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:12:53 +08:00
25 changed files with 3373 additions and 44 deletions

No files matched your search

+2
View File
@@ -126,6 +126,8 @@ jobs:
## Marqdo ${{ github.ref_name }}
### 亮点 / Highlights
- **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 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`
+28
View File
@@ -8,6 +8,34 @@
### Changed
## 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
### Highlights
Generated
+2 -2
View File
@@ -572,7 +572,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "marqdo"
version = "1.3.0"
version = "1.3.3"
dependencies = [
"anyhow",
"assert_cmd",
@@ -603,7 +603,7 @@ dependencies = [
[[package]]
name = "marqdo-wasm"
version = "1.3.0"
version = "1.3.3"
dependencies = [
"marqdo",
"serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "1.3.0"
version = "1.3.3"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
+6 -5
View File
@@ -149,15 +149,16 @@ marqdo catalog public -o .marqdo
---
## 现状(v1.3.0)
## 现状(v1.3.3)
- **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)
- **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.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/`
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [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 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))
@@ -176,7 +177,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))
- 选型:[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.3.3)
**安装解释器(任选其一)**
@@ -191,7 +192,7 @@ marqdo catalog public -o .marqdo
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v1.3.0 # 或留在 main
git checkout v1.3.3 # 或留在 main
cargo build --release
export PATH="$PWD/target/release:$PATH"
marqdo version
@@ -230,7 +231,7 @@ marqdo wasm build
# → dist/wasm/ … 见 examples/browser-hello/
# 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.3.3
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo-wasm"
version = "1.3.0"
version = "1.3.3"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
+8
View File
@@ -1,3 +1,11 @@
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: Engineering Knowledge Compiler (EKC) — L0–L4 catalog,
+3 -3
View File
@@ -4,14 +4,14 @@
|---|---|
| 状态 | **v1(独立 debug 页)** |
| 日期 | 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 debug` | 调试宿主(默认端口 **7430**):IDE 式布局;**仅 live** |
| `marqdo view` | 文档浏览器:**叙述保真文档面** Structure + Execution + Source;函数大纲与搜索;跑后引出标注;**无断点**(见 [view-document-annotations.md](view-document-annotations.md)) |
| `marqdo debug` | 调试宿主(默认端口 **7430**):IDE 式布局;AST Structure + BP;**仅 live** |
静态 `gh-pages` / `view output` **不能**真断点。
+113
View File
@@ -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) · [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 |
+103
View File
@@ -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、源码常显 |
+123
View File
@@ -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 |
+6 -4
View File
@@ -4,7 +4,7 @@
|---|---|
| 状态 | 已定(v0.0.2 方向) |
| 日期 | 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) · [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 run` 一致(导入即用);view/导出仅对 `exit`/`sleep` 做软化,避免拖垮进程。详见 [stdlib-modules.md](stdlib-modules.md) §6。
- 金样例浏览仍可用:`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. 信息架构
侧栏文件索引 + 主区:结构(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** | 原函数大纲 + 搜索;可折叠(默认展开) |
| **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)。
+1 -1
View File
@@ -1 +1 @@
1.3.2
1.3.3
+4 -2
View File
@@ -5,12 +5,14 @@ description: Local browse and static export from the interpreter
# main
Milestone: `marqdo view` and `view output`.
Milestone: `marqdo view` and `view output` (v1.3.3 document surface).
Local: `marqdo view 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.
+3 -2
View File
@@ -5,12 +5,13 @@ description: 本地浏览与静态导出由解释器生成
# main
里程碑:`marqdo view` 与 `view output`。
里程碑:`marqdo view` 与 `view output`(v1.3.3 文档面)。
本地浏览:`marqdo view public`
静态导出:`marqdo view output public -o public`
用户可执行文档在 `public/`;生成的 HTML(`index.html` / `pages/`)供静态托管,CI 发布到 `gh-pages`。
Browse Structure 保真叙述、高亮可执行标记,并挂载运行结果(变量值、分支命中臂、调用/循环帧)。
用户站与 live view 同源渲染;CI 发布到 `gh-pages`。
> 打印 内容=文档站:由 Marqdo 解释器生成,不是手写 HTML。
+94 -1
View File
@@ -1,7 +1,98 @@
//! Captured program run (for tests and `view`).
use crate::value::Value;
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)]
pub struct RunCapture {
@@ -10,4 +101,6 @@ pub struct RunCapture {
pub plots: Vec<PlotArtifact>,
/// Entry-function bindings after a successful tree-backend run (empty for bytecode).
pub bindings: std::collections::HashMap<String, Value>,
/// Branch/loop/stmt hits collected during tree capture (empty for bytecode).
pub view_trace: ViewTrace,
}
+290 -1
View File
@@ -17,6 +17,9 @@ use crate::debug::{emit_trace, DebugController};
use crate::diagnostics::{bail_at, Span};
use crate::host::{call_host, HostContext, HostFn};
use crate::input_feed::InputFeed;
use crate::capture::{
BranchHit, CallFrame, LoopFrame, LoopHit, LoopIter, StmtEvent, StmtEventKind, ViewTrace,
};
use crate::value::Value;
use std::sync::Arc;
@@ -27,6 +30,14 @@ pub struct Interpreter {
pub captured_stdout: String,
/// Bindings in the entry (`# main` / sole object) env after it finishes.
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,
input: InputFeed,
host: HostContext,
@@ -82,6 +93,12 @@ impl Interpreter {
capture: false,
captured_stdout: String::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),
input: InputFeed::new(false, Vec::new()),
host: HostContext::for_run(path, Default::default(), Vec::new()),
@@ -97,6 +114,12 @@ impl Interpreter {
capture: true,
captured_stdout: String::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),
input: InputFeed::new(true, Vec::new()),
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).
pub fn invoke_function(
&mut self,
@@ -337,6 +526,7 @@ impl Interpreter {
}
let ret = Value::None;
self.push_view_call(fun, &env);
self.host.push_call_frame(&fun.name);
let body_result = (|| -> Result<Value> {
for stmt in &fun.body {
@@ -347,6 +537,7 @@ impl Interpreter {
Ok(ret)
})();
self.host.pop_call_frame();
self.pop_view_call();
let ret = body_result?;
if capture_entry_env {
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);
Ok(None)
}
@@ -425,6 +628,18 @@ impl Interpreter {
&[("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))
}
Stmt::Call { call, span } => {
@@ -463,12 +678,15 @@ impl Interpreter {
&[("kind", "branch")],
);
}
for arm in arms {
for (arm_index, arm) in arms.iter().enumerate() {
let take = match &arm.condition {
None => true,
Some(cond) => self.eval_expr(module, fun, env, cond)?.truthy(),
};
if take {
if self.capture {
self.record_branch_hit(span.line, arm_index);
}
for s in &arm.body {
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
return Ok(Some(v));
@@ -493,18 +711,38 @@ impl Interpreter {
&[("kind", "while")],
);
}
let loop_id = if self.capture {
Some(self.begin_view_loop(span.line, None, None))
} else {
None
};
let mut guard = 0u32;
while self.eval_expr(module, fun, env, condition)?.truthy() {
guard += 1;
if guard > 1_000_000 {
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 {
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));
}
}
}
if self.capture {
if let Some(lid) = loop_id {
self.end_view_loop(lid);
}
self.record_loop_hit(span.line, guard, None);
}
Ok(None)
}
Stmt::ForEach {
@@ -534,14 +772,56 @@ impl Interpreter {
Ok(_) => unreachable!(),
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 {
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);
for s in body {
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));
}
}
}
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)
}
}
@@ -1399,6 +1679,15 @@ 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
}
}
fn stmt_span(stmt: &Stmt) -> Span {
match stmt {
Stmt::Assign { span, .. }
+4
View File
@@ -306,6 +306,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
value,
plots,
bindings: interp.entry_bindings,
view_trace: interp.view_trace,
})
}
Backend::Bytecode => {
@@ -331,6 +332,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
value,
plots,
bindings: Default::default(),
view_trace: Default::default(),
})
}
}
@@ -366,6 +368,7 @@ pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
value,
plots,
bindings: interp.entry_bindings,
view_trace: interp.view_trace,
})
}
Backend::Bytecode => {
@@ -391,6 +394,7 @@ pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
value,
plots,
bindings: Default::default(),
view_trace: Default::default(),
})
}
}
+852
View File
@@ -0,0 +1,852 @@
//! View annotations: bind values, returns, writebacks, branch/loop trace → Structure callouts.
use std::collections::HashMap;
use crate::ast::{Function, Module, Stmt};
use crate::capture::{RunCapture, StmtEventKind};
use crate::host::writeback;
use crate::parse::{scan_prose_line, ProseBit};
use crate::value::Value;
use crate::view::html::escape;
/// One result callout anchored to a source span.
#[derive(Debug, Clone)]
pub struct ViewAnnot {
pub id: String,
pub kind: AnnotKind,
pub anchor_line: u32,
pub anchor_byte_start: Option<usize>,
pub anchor_byte_end: Option<usize>,
pub label: String,
pub value: String,
pub detail: String,
pub arm_index: Option<usize>,
pub call_id: Option<u32>,
pub loop_id: Option<u32>,
/// 0-based iteration index when inside a loop frame.
pub iter: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnnotKind {
Bind,
Return,
#[allow(dead_code)]
Call,
#[allow(dead_code)]
Expr,
Branch,
Loop,
Writeback,
/// Synthetic: one per CallFrame for function picker (label = fn name, value = args_brief).
CallFrame,
/// Synthetic: one per loop iteration for loop picker.
LoopFrame,
}
impl AnnotKind {
pub fn as_str(self) -> &'static str {
match self {
AnnotKind::Bind => "bind",
AnnotKind::Return => "return",
AnnotKind::Call => "call",
AnnotKind::Expr => "expr",
AnnotKind::Branch => "branch",
AnnotKind::Loop => "loop",
AnnotKind::Writeback => "writeback",
AnnotKind::CallFrame => "callframe",
AnnotKind::LoopFrame => "loopframe",
}
}
}
/// Truncate display text for callout chips.
pub fn brief_value(v: &Value) -> String {
let s = v.as_display();
if s.chars().count() > 48 {
format!("{}…", s.chars().take(48).collect::<String>())
} else {
s
}
}
fn brief_str(s: &str) -> String {
if s.chars().count() > 48 {
format!("{}…", s.chars().take(48).collect::<String>())
} else {
s.to_string()
}
}
/// Build annotations from capture + source (post-stmt events preferred).
pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec<ViewAnnot> {
let mut out = Vec::new();
let mut id_seq = 0u32;
let mut next_id = |prefix: &str| -> String {
id_seq += 1;
format!("{prefix}{id_seq}")
};
let name_sites = collect_name_sites(module, source);
let lines: Vec<&str> = source.lines().collect();
// Prefer StmtEvent assign/return (post-stmt). Keep one chip per (line,name,call,loop,iter).
type AssignKey = (u32, String, u32, Option<u32>, Option<u32>);
let mut last_assign: HashMap<AssignKey, &crate::capture::StmtEvent> = HashMap::new();
let mut assign_counts: HashMap<AssignKey, u32> = HashMap::new();
for ev in &cap.view_trace.events {
if ev.kind == StmtEventKind::Assign {
if let Some(ref name) = ev.name {
let key = (ev.line, name.clone(), ev.call_id, ev.loop_id, ev.iter);
*assign_counts.entry(key.clone()).or_insert(0) += 1;
last_assign.insert(key, ev);
}
}
}
if !last_assign.is_empty() {
for ((line, name, _cid, _lid, _iter), ev) in &last_assign {
let (start, end) = name_sites
.get(name.as_str())
.and_then(|(l, s, e)| if l == line { Some((*s, *e)) } else { None })
.unwrap_or_else(|| {
find_name_in_line(
lines
.get((*line as usize).saturating_sub(1))
.copied()
.unwrap_or(""),
name,
)
});
let key = (*line, name.clone(), ev.call_id, ev.loop_id, ev.iter);
let mut value = ev.value_after.clone().unwrap_or_else(|| "?".into());
let count = assign_counts.get(&key).copied().unwrap_or(1);
if count > 1 {
value = format!("{value} · ×{count}");
}
out.push(ViewAnnot {
id: next_id("b"),
kind: AnnotKind::Bind,
anchor_line: *line,
anchor_byte_start: start,
anchor_byte_end: end,
label: name.clone(),
value: brief_str(&value),
detail: ev.value_after.clone().unwrap_or_default(),
arm_index: None,
call_id: Some(ev.call_id),
loop_id: ev.loop_id,
iter: ev.iter,
});
}
} else {
// Fallback (bytecode / empty events): final bindings — only when no events.
for (name, val) in &cap.bindings {
let (line, start, end) = name_sites
.get(name.as_str())
.copied()
.unwrap_or((0, None, None));
if line == 0 {
continue;
}
out.push(ViewAnnot {
id: next_id("b"),
kind: AnnotKind::Bind,
anchor_line: line,
anchor_byte_start: start,
anchor_byte_end: end,
label: name.clone(),
value: brief_value(val),
detail: val.as_display(),
arm_index: None,
call_id: None,
loop_id: None,
iter: None,
});
}
}
// BindRef: foreach item = collection[i] (one per iteration).
for ev in &cap.view_trace.events {
if ev.kind != StmtEventKind::BindRef {
continue;
}
let Some(ref name) = ev.name else { continue };
let value = ev.value_after.clone().unwrap_or_default();
// Label is `分`; value is `分数表[3] · 88` (not `分 = …` again).
let display = if let Some((left, right)) = value.split_once('=') {
format!("{left} · {right}")
} else {
value.clone()
};
out.push(ViewAnnot {
id: next_id("brf"),
kind: AnnotKind::Bind,
anchor_line: ev.line,
anchor_byte_start: None,
anchor_byte_end: None,
label: name.clone(),
value: brief_str(&display),
detail: format!("{name} = {display}"),
arm_index: None,
call_id: Some(ev.call_id),
loop_id: ev.loop_id,
iter: ev.iter,
});
}
// Return events (last per line+call+iter).
type RetKey = (u32, u32, Option<u32>, Option<u32>);
let mut last_ret: HashMap<RetKey, &crate::capture::StmtEvent> = HashMap::new();
for ev in &cap.view_trace.events {
if ev.kind == StmtEventKind::Return {
last_ret.insert((ev.line, ev.call_id, ev.loop_id, ev.iter), ev);
}
}
for ((line, _, _, _), ev) in last_ret {
let text = lines
.get(line.saturating_sub(1) as usize)
.copied()
.unwrap_or("");
let mut start = None;
let mut end = None;
for bit in scan_prose_line(text) {
if let ProseBit::ItalicReturn { at, .. } = &bit {
start = Some(*at);
end = Some(prose_bit_end(text, &bit));
}
}
let value = ev.value_after.clone().unwrap_or_default();
out.push(ViewAnnot {
id: next_id("r"),
kind: AnnotKind::Return,
anchor_line: line,
anchor_byte_start: start,
anchor_byte_end: end,
label: "return".into(),
value: brief_str(&value),
detail: value,
arm_index: None,
call_id: Some(ev.call_id),
loop_id: ev.loop_id,
iter: ev.iter,
});
}
// Writebacks.
let wb = writeback::writeback_map(source);
for (line, body) in wb {
let brief = body.lines().next().unwrap_or(body.as_str());
out.push(ViewAnnot {
id: next_id("w"),
kind: AnnotKind::Writeback,
anchor_line: line,
anchor_byte_start: None,
anchor_byte_end: None,
label: "output".into(),
value: brief_str(brief),
detail: body,
arm_index: None,
call_id: None,
loop_id: None,
iter: None,
});
}
// Branch hits — one annot per (line, arm, call) with call_id for frame filtering.
for hit in &cap.view_trace.branches {
out.push(ViewAnnot {
id: next_id("br"),
kind: AnnotKind::Branch,
anchor_line: hit.line,
anchor_byte_start: None,
anchor_byte_end: None,
label: format!("arm {}", hit.arm_index + 1),
value: if hit.count > 1 {
format!("taken ×{}", hit.count)
} else {
"taken".into()
},
detail: format!(
"arm {} hit {} time(s) call {}",
hit.arm_index + 1,
hit.count,
hit.call_id
),
arm_index: Some(hit.arm_index),
call_id: Some(hit.call_id),
loop_id: None,
iter: None,
});
}
// Per-iteration frames for the picker. Foreach item binding is already a BindRef chip
// (`分` → `分数表[i] · v`); do not emit a second Loop summary on the same line.
for fr in &cap.view_trace.loop_frames {
let item = fr.item_name.as_deref().unwrap_or("item");
let coll = fr.collection.as_deref().unwrap_or("?");
let has_item_bind = fr.item_name.is_some() && !fr.iterations.is_empty();
if !has_item_bind {
// while / empty: keep a single summary chip (no BindRef duplicate).
let last = fr.iterations.last();
let summary = if let Some(it) = last {
format!("{} iters · last={}", fr.iterations.len(), it.item_value)
} else {
format!("{} iters", fr.iterations.len())
};
out.push(ViewAnnot {
id: next_id("lp"),
kind: AnnotKind::Loop,
anchor_line: fr.line,
anchor_byte_start: None,
anchor_byte_end: None,
label: "loop".into(),
value: brief_str(&summary),
detail: summary,
arm_index: None,
call_id: last.map(|it| it.call_id),
loop_id: Some(fr.loop_id),
iter: None,
});
}
for it in &fr.iterations {
let value = format!("{} = {}[{}] · {}", item, coll, it.index, it.item_value);
out.push(ViewAnnot {
id: format!("lf{}-{}", fr.loop_id, it.index),
kind: AnnotKind::LoopFrame,
anchor_line: fr.line,
anchor_byte_start: None,
anchor_byte_end: None,
label: format!("{}", it.index + 1),
value: brief_str(&value),
detail: value,
arm_index: None,
call_id: Some(it.call_id),
loop_id: Some(fr.loop_id),
iter: Some(it.index),
});
}
}
// Fallback LoopHit when no LoopFrame (legacy / while without frames).
if cap.view_trace.loop_frames.is_empty() {
for hit in &cap.view_trace.loops {
let mut value = format!("{} iters", hit.iterations);
if let Some(ref last) = hit.last_item {
value.push_str(" · last=");
value.push_str(last);
}
out.push(ViewAnnot {
id: next_id("lp"),
kind: AnnotKind::Loop,
anchor_line: hit.line,
anchor_byte_start: None,
anchor_byte_end: None,
label: "loop".into(),
value,
detail: format!("iterations={}", hit.iterations),
arm_index: None,
call_id: None,
loop_id: None,
iter: None,
});
}
}
// Call frames for picker (label = fn name).
for fr in &cap.view_trace.calls {
out.push(ViewAnnot {
id: format!("cf{}", fr.call_id),
kind: AnnotKind::CallFrame,
anchor_line: fr.fn_line,
anchor_byte_start: None,
anchor_byte_end: None,
label: fr.fn_name.clone(),
value: fr.args_brief.clone(),
detail: format!("call #{} {}", fr.ordinal, fr.args_brief),
arm_index: None,
call_id: Some(fr.call_id),
loop_id: None,
iter: None,
});
}
out
}
/// Serialize ViewExecutionReport JSON for AI / page embed.
pub fn view_execution_report_json(path: &str, ok: bool, cap: &RunCapture) -> String {
use serde_json::{json, Map};
let mut bindings = Map::new();
for (k, v) in &cap.bindings {
bindings.insert(k.clone(), json!(v.as_display()));
}
let calls: Vec<_> = cap
.view_trace
.calls
.iter()
.map(|c| {
json!({
"call_id": c.call_id,
"fn": c.fn_name,
"fn_line": c.fn_line,
"ordinal": c.ordinal,
"args_brief": c.args_brief,
})
})
.collect();
let events: Vec<_> = cap
.view_trace
.events
.iter()
.map(|e| {
json!({
"line": e.line,
"kind": e.kind.as_str(),
"name": e.name,
"value_after": e.value_after,
"arm_index": e.arm_index,
"iter": e.iter,
"call_id": e.call_id,
"loop_id": e.loop_id,
})
})
.collect();
let loops: Vec<_> = cap
.view_trace
.loop_frames
.iter()
.map(|fr| {
json!({
"loop_id": fr.loop_id,
"line": fr.line,
"item": fr.item_name,
"collection": fr.collection,
"iters": fr.iterations.iter().map(|it| json!({
"index": it.index,
"value": it.item_value,
"call_id": it.call_id,
})).collect::<Vec<_>>(),
})
})
.collect();
json!({
"version": 1,
"path": path,
"ok": ok,
"calls": calls,
"loops": loops,
"events": events,
"bindings_final": bindings,
})
.to_string()
}
fn collect_name_sites(
module: &Module,
source: &str,
) -> HashMap<String, (u32, Option<usize>, Option<usize>)> {
let mut map = HashMap::new();
let lines: Vec<&str> = source.lines().collect();
for fun in &module.functions {
collect_name_sites_fun(fun, &lines, &mut map);
}
for (i, text) in lines.iter().enumerate() {
let line_no = (i + 1) as u32;
for bit in scan_prose_line(text) {
if let ProseBit::Decl { name, at, .. } = &bit {
let end = prose_bit_end(text, &bit);
map.entry(name.clone())
.or_insert((line_no, Some(*at), Some(end)));
}
}
}
map
}
fn collect_name_sites_fun(
fun: &Function,
lines: &[&str],
map: &mut HashMap<String, (u32, Option<usize>, Option<usize>)>,
) {
for stmt in &fun.body {
if let Stmt::Assign { name, span, .. } = stmt {
let text = lines
.get(span.line.saturating_sub(1) as usize)
.copied()
.unwrap_or("");
let (start, end) = find_name_in_line(text, name);
// Prefer first site for fallback map; post-stmt uses line from event.
map.entry(name.clone())
.or_insert((span.line, start, end));
}
walk_stmt_nested(stmt, lines, map);
}
for child in &fun.children {
collect_name_sites_fun(child, lines, map);
}
}
fn walk_stmt_nested(
stmt: &Stmt,
lines: &[&str],
map: &mut HashMap<String, (u32, Option<usize>, Option<usize>)>,
) {
match stmt {
Stmt::Branch { arms, .. } => {
for arm in arms {
for s in &arm.body {
if let Stmt::Assign { name, span, .. } = s {
let text = lines
.get(span.line.saturating_sub(1) as usize)
.copied()
.unwrap_or("");
let (start, end) = find_name_in_line(text, name);
map.entry(name.clone())
.or_insert((span.line, start, end));
}
walk_stmt_nested(s, lines, map);
}
}
}
Stmt::While { body, .. } | Stmt::ForEach { body, .. } => {
for s in body {
if let Stmt::Assign { name, span, .. } = s {
let text = lines
.get(span.line.saturating_sub(1) as usize)
.copied()
.unwrap_or("");
let (start, end) = find_name_in_line(text, name);
map.entry(name.clone())
.or_insert((span.line, start, end));
}
walk_stmt_nested(s, lines, map);
}
}
_ => {}
}
}
fn find_name_in_line(text: &str, name: &str) -> (Option<usize>, Option<usize>) {
for bit in scan_prose_line(text) {
match &bit {
ProseBit::Decl { name: n, at, .. } if n == name => {
return (Some(*at), Some(prose_bit_end(text, &bit)));
}
ProseBit::BoldCode { inner, at } if inner.contains(name) => {
return (Some(*at), Some(prose_bit_end(text, &bit)));
}
_ => {}
}
}
if let Some(at) = text.find(name) {
return (Some(at), Some(at + name.len()));
}
(None, None)
}
/// Byte end (exclusive) of a prose bit in `line`.
pub fn prose_bit_end(line: &str, bit: &ProseBit) -> usize {
match bit {
ProseBit::Decl { name, default, at } => {
let after_ticks = *at + 1 + name.len() + 1;
match default {
None => after_ticks,
Some(d) => {
let mut end = after_ticks;
if line.get(end..end + 1) == Some("=") {
end += 1 + d.len();
}
end.min(line.len())
}
}
}
ProseBit::BoldCode { inner, at } => (*at + 2 + inner.len() + 2).min(line.len()),
ProseBit::ItalicReturn { inner, at } => (*at + 1 + inner.len() + 1).min(line.len()),
}
}
pub fn bit_at(bit: &ProseBit) -> usize {
match bit {
ProseBit::Decl { at, .. }
| ProseBit::BoldCode { at, .. }
| ProseBit::ItalicReturn { at, .. } => *at,
}
}
pub fn bit_kind_class(bit: &ProseBit) -> &'static str {
match bit {
ProseBit::Decl { .. } => "decl",
ProseBit::BoldCode { .. } => "code",
ProseBit::ItalicReturn { .. } => "return",
}
}
/// Render annotation band HTML for a set of annots (already filtered to one block).
///
/// Chips with `iter` default to the **last** iteration per `loop_id` (SSR); the loop
/// picker toggles `hidden` / `is-frame-hidden` so only the selected iter is shown.
pub fn render_annot_band(annots: &[ViewAnnot], max_visible: usize) -> String {
let annots: Vec<&ViewAnnot> = annots
.iter()
.filter(|a| a.kind != AnnotKind::CallFrame && a.kind != AnnotKind::LoopFrame)
.collect();
if annots.is_empty() {
return String::new();
}
// Default visible iteration = max index per loop_id (matches picker default = last).
let mut default_iter: HashMap<Option<u32>, u32> = HashMap::new();
for a in &annots {
if let Some(i) = a.iter {
let e = default_iter.entry(a.loop_id).or_insert(i);
if i > *e {
*e = i;
}
}
}
let mut s = String::from(r#"<div class="annot-band" data-annot-band>"#);
s.push_str(r#"<div class="annot-leaders" aria-hidden="true"></div>"#);
s.push_str(r#"<div class="annot-chips">"#);
let mut shown = 0usize;
let mut overflow_count = 0usize;
for a in &annots {
let frame_miss = a
.iter
.zip(default_iter.get(&a.loop_id))
.map(|(i, d)| i != *d)
.unwrap_or(false);
let overflow = if frame_miss {
false
} else if shown >= max_visible {
overflow_count += 1;
true
} else {
shown += 1;
false
};
let mut classes = format!("annot-chip annot-{}", a.kind.as_str());
if overflow {
classes.push_str(" annot-chip-overflow");
}
if frame_miss {
classes.push_str(" is-frame-hidden");
}
let call_attr = a
.call_id
.map(|c| format!(r#" data-call-id="{c}""#))
.unwrap_or_default();
let loop_attr = a
.loop_id
.map(|c| format!(r#" data-loop-id="{c}""#))
.unwrap_or_default();
let iter_attr = a
.iter
.map(|c| format!(r#" data-iter="{c}""#))
.unwrap_or_default();
let arm_attr = a
.arm_index
.map(|c| format!(r#" data-arm-index="{c}""#))
.unwrap_or_default();
let hidden_attr = if frame_miss { " hidden" } else { "" };
s.push_str(&format!(
r#"<button type="button" class="{classes}" data-annot-id="{id}" data-annot-kind="{kind}"{call}{loop_id}{iter}{arm}{hidden} title="{detail}">
<span class="annot-label">{label}</span>
<span class="annot-value">{value}</span>
</button>"#,
classes = classes,
kind = a.kind.as_str(),
id = escape(&a.id),
call = call_attr,
loop_id = loop_attr,
iter = iter_attr,
arm = arm_attr,
hidden = hidden_attr,
detail = escape(&a.detail),
label = escape(&a.label),
value = escape(&a.value),
));
}
if overflow_count > 0 {
s.push_str(&format!(
r#"<button type="button" class="annot-more" data-annot-more>+{}</button>"#,
overflow_count
));
}
s.push_str("</div></div>");
s
}
/// Group annots by anchor line.
pub fn annots_by_line(annots: &[ViewAnnot]) -> HashMap<u32, Vec<&ViewAnnot>> {
let mut m: HashMap<u32, Vec<&ViewAnnot>> = HashMap::new();
for a in annots {
if a.kind == AnnotKind::CallFrame || a.kind == AnnotKind::LoopFrame {
continue;
}
m.entry(a.anchor_line).or_default().push(a);
}
m
}
#[cfg(test)]
mod tests {
use super::*;
use crate::capture::{RunCapture, ViewTrace};
#[test]
fn prose_bit_end_bold_and_return() {
let line = "操作**n=n+1**接着返回*n*。";
let bits = scan_prose_line(line);
assert!(bits.len() >= 2, "{bits:?}");
for bit in &bits {
let end = prose_bit_end(line, bit);
assert!(end <= line.len());
assert!(end > bit_at(bit));
}
}
#[test]
fn post_stmt_init_not_final() {
let src = include_str!("../../tests/view/document-annot-demo.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap();
let annots = build_view_annots(&module, src, &cap);
// Find bind for 总分 on the init line (**总分 = 0**).
let init = annots.iter().find(|a| {
a.kind == AnnotKind::Bind && a.label == "总分" && a.value.starts_with('0')
});
assert!(
init.is_some(),
"expected 总分=0 post-stmt annot, got: {:?}",
annots
.iter()
.filter(|a| a.label == "总分")
.map(|a| (&a.value, a.anchor_line))
.collect::<Vec<_>>()
);
}
#[test]
fn build_annots_branch_and_loop() {
let src = include_str!("../../tests/view/document-annot-demo.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap();
let annots = build_view_annots(&module, src, &cap);
assert!(annots.iter().any(|a| a.kind == AnnotKind::Branch));
assert!(!cap.view_trace.events.is_empty(), "expected stmt events");
// Branch annots must carry call_id so call picker can filter.
assert!(
annots
.iter()
.filter(|a| a.kind == AnnotKind::Branch)
.all(|a| a.call_id.is_some()),
"branch annots missing call_id"
);
assert!(!cap.view_trace.loop_frames.is_empty(), "expected loop frames");
assert!(annots.iter().any(|a| a.kind == AnnotKind::LoopFrame));
// Foreach: BindRef chips only — no duplicate Loop summary on the same line.
let loop_line = cap.view_trace.loop_frames[0].line;
let on_loop: Vec<_> = annots
.iter()
.filter(|a| a.anchor_line == loop_line)
.collect();
assert!(
on_loop.iter().any(|a| a.kind == AnnotKind::Bind && a.label == "分"),
"expected BindRef for 分"
);
assert!(
!on_loop.iter().any(|a| a.kind == AnnotKind::Loop),
"foreach must not emit duplicate Loop summary chip: {:?}",
on_loop.iter().map(|a| a.kind.as_str()).collect::<Vec<_>>()
);
}
#[test]
fn call_frames_filter_branch_arms() {
let src = include_str!("../../tests/view/document-annot-demo.mq.md");
let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap();
let grade_calls: Vec<_> = cap
.view_trace
.calls
.iter()
.filter(|c| c.fn_name == "等级说明")
.collect();
assert!(grade_calls.len() >= 2, "expected ≥2 calls to 等级说明");
let c1 = grade_calls[0].call_id;
let c2 = grade_calls[1].call_id;
let arm_for = |cid: u32| {
cap.view_trace
.events
.iter()
.find(|e| e.kind == StmtEventKind::Branch && e.call_id == cid)
.and_then(|e| e.arm_index)
};
let a1 = arm_for(c1).expect("branch for call 1");
let a2 = arm_for(c2).expect("branch for call 2");
assert_ne!(a1, a2, "two calls should take different arms");
}
#[test]
fn loop_frame_item_binding() {
let src = include_str!("../../tests/view/document-annot-demo.mq.md");
let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap();
let fr = cap.view_trace.loop_frames.first().expect("loop frame");
assert_eq!(fr.item_name.as_deref(), Some("分"));
assert_eq!(fr.collection.as_deref(), Some("分数表"));
assert_eq!(fr.iterations.len(), 4);
assert_eq!(fr.iterations.last().unwrap().item_value, "88");
assert_eq!(fr.iterations.last().unwrap().index, 3);
}
#[test]
fn loop_band_ssr_hides_non_default_iters() {
let src = include_str!("../../tests/view/document-annot-demo.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap();
let annots = build_view_annots(&module, src, &cap);
// Collect bind annots on the 总分 assign line inside the loop.
let total_line = annots
.iter()
.find(|a| a.kind == AnnotKind::Bind && a.label == "总分" && a.iter == Some(3))
.map(|a| a.anchor_line)
.expect("last-iter 总分");
let on_line: Vec<_> = annots
.iter()
.filter(|a| a.anchor_line == total_line && a.kind == AnnotKind::Bind)
.cloned()
.collect();
assert!(on_line.len() >= 4, "expected per-iter 总分 chips");
let html = render_annot_band(&on_line, 8);
// Non-last iters are SSR-hidden; last remains visible.
assert!(html.contains(r#"data-iter="3""#), "{html}");
assert!(
html.contains(r#"data-iter="0""#) && html.contains("is-frame-hidden"),
"expected non-default iters hidden: {html}"
);
let visible_totals = html.matches(r#"data-iter="3""#).count();
assert_eq!(visible_totals, 1);
// Hidden attribute on iter 0 chip.
assert!(
html.contains(r#"data-iter="0""#)
&& html
.split("<button")
.filter(|b| b.contains(r#"data-iter="0""#))
.all(|b| b.contains(" hidden") || b.contains("is-frame-hidden")),
"{html}"
);
}
#[test]
fn report_json_has_version() {
let cap = RunCapture {
stdout: String::new(),
value: Value::None,
plots: Vec::new(),
bindings: HashMap::new(),
view_trace: ViewTrace::default(),
};
let j = view_execution_report_json("x.mq.md", true, &cap);
assert!(j.contains("\"version\":1"), "{j}");
assert!(j.contains("events"), "{j}");
assert!(j.contains("loops"), "{j}");
}
}
+1082
View File
File diff suppressed because it is too large. Load diff
+440
View File
@@ -330,6 +330,234 @@ section.block > h2 {
background: transparent;
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.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.35rem 0 0.15rem;
min-height: 1.6rem;
padding-top: 0.55rem;
}
.annot-leaders {
position: absolute;
inset: 0;
pointer-events: none;
overflow: visible;
}
.annot-leader {
position: absolute;
box-sizing: border-box;
border-left: 1.5px solid var(--line-strong);
border-bottom: 1.5px solid var(--line-strong);
border-color: #8e8e93;
pointer-events: none;
}
.annot-leader.annot-bind { border-color: #5ac8fa; }
.annot-leader.annot-return { border-color: #30d158; }
.annot-leader.annot-code,
.annot-leader.annot-call,
.annot-leader.annot-expr { border-color: #ff9f0a; }
.annot-leader.annot-branch { border-color: #bf5af2; }
.annot-leader.annot-loop { border-color: #64d2ff; }
.annot-leader.annot-writeback { border-color: #8e8e93; }
.annot-chips {
display: flex;
flex-wrap: wrap;
gap: 0.4rem 0.55rem;
position: relative;
z-index: 1;
}
.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-overflow { display: none; }
.annot-band.is-expanded .annot-chip-overflow:not([hidden]):not(.is-frame-hidden) {
display: inline-flex;
}
.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-leaders { display: none; }
.annot-band.is-keyed .annot-chip::before {
content: attr(data-annot-key) " ";
color: var(--muted);
}
@media (max-width: 640px) {
.annot-band { padding-top: 0.25rem; }
.annot-leaders { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.annot-leaders { display: none; }
}
.badge {
display: inline-block;
font-family: var(--mono);
@@ -1740,6 +1968,19 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
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 +2179,208 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
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; }}
}}
/** 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 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;
chip.hidden = cid !== callId;
}});
var trace = readViewTrace();
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");
}});
}});
}}
initAnnotLeaders();
}}
if (sel.dataset.bound !== "1") {{
sel.dataset.bound = "1";
sel.addEventListener("change", apply);
}}
apply();
}});
}}
function setFrameHidden(el, hide) {{
el.hidden = !!hide;
if (hide) el.classList.add("is-frame-hidden");
else el.classList.remove("is-frame-hidden");
}}
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);
}});
initAnnotLeaders();
}}
if (sel.dataset.bound !== "1") {{
sel.dataset.bound = "1";
sel.addEventListener("change", apply);
}}
apply();
}});
}}
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 leaders = band.querySelector(".annot-leaders");
var chips = band.querySelectorAll(".annot-chip:not(.annot-chip-overflow):not([hidden]):not(.is-frame-hidden)");
if (!leaders) return;
leaders.innerHTML = "";
if (reduce || narrow || chips.length > 4) {{
band.classList.add("is-keyed");
chips.forEach(function (chip, i) {{
chip.setAttribute("data-annot-key", String(i + 1));
}});
return;
}}
band.classList.remove("is-keyed");
var bandRect = band.getBoundingClientRect();
chips.forEach(function (chip) {{
if (chip.hidden || chip.classList.contains("is-frame-hidden")) return;
var id = chip.getAttribute("data-annot-id") || "";
var kind = chip.getAttribute("data-annot-kind") || "";
var anchor = id
? document.querySelector('.mq-anchor[data-annot-id="' + id + '"]')
: null;
if (!anchor) {{
var block = band.closest(".doc-block");
anchor = block ? block.querySelector(".mq-anchor") : null;
}}
if (!anchor) return;
var a = anchor.getBoundingClientRect();
var c = chip.getBoundingClientRect();
var x0 = a.left + a.width / 2 - bandRect.left;
var y0 = 0;
var x1 = c.left + Math.min(12, c.width / 2) - bandRect.left;
var y1 = c.top - bandRect.top + c.height / 2;
var left = Math.min(x0, x1);
var width = Math.max(2, Math.abs(x1 - x0));
var height = Math.max(2, y1 - y0);
var el = document.createElement("div");
el.className = "annot-leader annot-" + kind;
el.style.left = left + "px";
el.style.top = y0 + "px";
el.style.width = width + "px";
el.style.height = height + "px";
if (x1 < x0) {{
el.style.borderLeft = "none";
el.style.borderRight = "1.5px solid";
el.style.borderBottom = "1.5px solid";
}}
leaders.appendChild(el);
}});
}}
function layoutAll() {{
bands.forEach(layoutBand);
}}
layoutAll();
if (typeof ResizeObserver !== "undefined") {{
var ro = new ResizeObserver(function () {{ layoutAll(); }});
bands.forEach(function (b) {{ ro.observe(b); }});
var surface = document.querySelector(".document-surface");
if (surface) ro.observe(surface);
}}
window.addEventListener("resize", layoutAll);
document.querySelectorAll("[data-annot-more]").forEach(function (btn) {{
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) {{
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") {{
document.addEventListener("DOMContentLoaded", function () {{
initForeignCards();
initOutlineSearch();
initStreamPanel();
initVarsPanel();
initAnnotLeaders();
initCallPickers();
initLoopPickers();
}});
}} else {{
initForeignCards();
initOutlineSearch();
initStreamPanel();
initVarsPanel();
initAnnotLeaders();
initCallPickers();
initLoopPickers();
}}
function initOutlineSearch() {{
@@ -2293,6 +2724,9 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
.to_string(),
_ => String::new(),
};
let trace_safe = vm
.trace_json
.replace("</", "<\\/");
let main = format!(
r#"
<script>
@@ -2300,6 +2734,7 @@ window.MARQDO_VIEW_LIVE = {live};
window.MARQDO_FILE_PATH = {path_js};
window.MARQDO_AUTO_STREAM = {auto_stream};
</script>
<script type="application/json" id="mq-view-trace">{trace}</script>
<h1 class="page">{title}<span class="status-pill {status}">{status_label}</span></h1>
<p class="meta">{rel}</p>
<section class="block">
@@ -2322,6 +2757,11 @@ window.MARQDO_AUTO_STREAM = {auto_stream};
live = live_flag,
path_js = escape_js_string(rel),
auto_stream = if vm.auto_stream { "true" } else { "false" },
trace = if trace_safe.is_empty() {
"{}"
} else {
trace_safe.as_str()
},
title = escape(title),
status = status,
status_label = status_label,
+57 -13
View File
@@ -1,8 +1,10 @@
//! `marqdo view` — local HTML browser for `.mq.md` structure + output.
//! `marqdo debug` — separate debugger host (tree-walk breakpoints).
mod annot;
mod debug_api;
mod debug_page;
mod document;
mod html;
mod output;
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::view::debug_page::{build_debug_model, page_debug};
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::{
collect_input_prompts, render_bindings_html, render_module_structure, render_right_rail,
uses_stream_panel, FileViewModel,
collect_input_prompts, render_bindings_html, render_module_structure,
render_module_structure_with_annots, render_right_rail, uses_stream_panel, FileViewModel,
};
use crate::{run_file_capture, RunOptions};
@@ -212,6 +215,24 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
let json = files_json(&root.files);
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),
_ => {
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) };
// Optional: sandbox to the whole view tree so sibling folders are reachable.
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 {
(
String::new(),
@@ -355,13 +377,13 @@ pub(crate) fn build_file_view(
)
} else {
match run_file_capture(abs, &opts) {
Ok(cap) => (
cap.stdout,
String::new(),
true,
cap.plots.into_iter().map(|p| p.svg).collect(),
render_bindings_html(&cap.bindings),
),
Ok(cap) => {
let stdout = cap.stdout.clone();
let plots = cap.plots.iter().map(|p| p.svg.clone()).collect();
let bindings_html = render_bindings_html(&cap.bindings);
captured = Some(cap);
(stdout, String::new(), true, plots, bindings_html)
}
Err(e) => (
String::new(),
tidy_user_error(&format!("{e:#}"), abs, rel),
@@ -375,10 +397,14 @@ pub(crate) fn build_file_view(
if !awaiting_input && !auto_stream {
if let Ok(next) = fs::read_to_string(abs) {
source = next;
if let Ok(module) = crate::parse::parse_source(&source) {
structure = render_module_structure(&module, &source);
module_opt = Some(module);
}
}
if let Ok(module) = crate::parse::parse_source(&source) {
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);
@@ -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 {
rel_path: rel.to_string(),
source,
@@ -407,6 +437,7 @@ pub(crate) fn build_file_view(
show_stream,
plots,
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.
let preview: String = cap.stdout.chars().take(500).collect();
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!({
"type": "done",
"run_id": run_id,
@@ -648,6 +690,8 @@ fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> {
"ok": true,
"result": preview,
"bindings_html": bindings_html,
"structure_html": structure_html,
"trace_json": trace_json,
});
crate::host::event_bus::EventBus::global().publish_json(&done.to_string());
}
+7 -1
View File
@@ -32,11 +32,17 @@ pub fn write_static(opts: OutputOptions) -> Result<()> {
vm.ok = true;
vm.plots.clear();
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) {
let wb = crate::view::render::render_writeback_outline(&vm.source);
vm.outline_html =
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 {
+81 -7
View File
@@ -45,6 +45,8 @@ pub struct FileViewModel {
pub plots: Vec<String>,
/// HTML for Variables panel (entry bindings after run).
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).
@@ -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 {
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(
module: &Module,
source: &str,
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 {
let lines = classify_source(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, …).
fn comment_markdown_to_html(md: &str) -> String {
pub(crate) fn comment_markdown_to_html(md: &str) -> String {
let mut opts = Options::empty();
opts.insert(Options::ENABLE_STRIKETHROUGH);
opts.insert(Options::ENABLE_TABLES);
@@ -1412,6 +1436,45 @@ fn expr_prec(expr: &Expr, parent_prec: u8) -> String {
}
/// 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.
pub(crate) fn render_formula_assign_card(name: &str, tex: &str) -> String {
format!(
"<div class=\"card formula-card\"><span class=\"badge\">formula</span> \
<code class=\"expr\">`{}` =</code> \
<div class=\"math-block\">$${}$$</div></div>",
escape(name),
escape(tex),
)
}
/// Foreign code assign card for document surface embedding.
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}">
<div class="code-head">
<span class="badge">code</span>
<code class="expr">`{name}` =</code>
<span class="code-lang">{lang}</span>
<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-body"><code class="language-{lang}">{src}</code></pre>
<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 {
let mut out = String::new();
let chars: Vec<char> = ascii.chars().collect();
@@ -1525,7 +1588,7 @@ mod tests {
let src = include_str!("../../tests/structure/nested-call.mq.md");
let module = crate::parse::parse_source(src).unwrap();
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("Binary {"));
assert!(!html.contains("Literal(Int"));
@@ -1536,9 +1599,9 @@ mod tests {
let src = "段首说明\n续行仍属同段\n\n下一段\n\n# main\n\n> print text=x\n";
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
let cards = html.matches("comment-card").count();
assert_eq!(cards, 2, "blank line should split comment paragraphs: {html}");
assert!(html.contains("段首说明 续行仍属同段") || html.contains("段首说明</p>"));
let blocks = html.matches("doc-prose").count();
assert!(blocks >= 2, "blank line should split comment paragraphs: {html}");
assert!(html.contains("段首说明 续行仍属同段") || html.contains("段首说明</p>") || html.contains("段首说明"));
assert!(html.contains("下一段"));
}
@@ -1575,11 +1638,10 @@ mod tests {
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 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("main"), "{html}");
assert!(!html.contains("trim"), "{html}");
assert!(html.contains("class=\"stmt\""), "{html}");
assert!(html.contains("data-line="), "{html}");
assert_eq!(local.functions.len(), 1);
assert_eq!(local.functions[0].name, "main");
@@ -1624,9 +1686,21 @@ mod tests {
let browse = render_module_structure_mode(&module, src, StructureMode::Browse);
let debug = render_module_structure_mode(&module, src, StructureMode::Debug);
assert!(browse.contains("id=\"fn-"), "{browse}");
assert!(browse.contains("document-surface"), "{browse}");
assert!(!browse.contains("bp-gutter"), "{browse}");
assert!(debug.contains("bp-gutter"), "{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]
+62
View File
@@ -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. *
*"建议安排复习周,再测一次。"*