From 4e2419b598a7dbb4d2d04dae49d37395ff1c480b Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 15 Oct 2026 13:12:53 +0800 Subject: [PATCH] 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 --- doc/design/view-debug.md | 6 +- doc/design/view-document-annotations.md | 113 +++ doc/design/view-execution-trace.md | 103 +++ doc/design/view-frame-selection.md | 123 +++ doc/design/view.md | 10 +- src/capture.rs | 95 +- src/interp.rs | 291 +++++- src/lib.rs | 4 + src/view/annot.rs | 852 ++++++++++++++++++ src/view/document.rs | 1082 +++++++++++++++++++++++ src/view/html.rs | 440 +++++++++ src/view/mod.rs | 70 +- src/view/output.rs | 8 +- src/view/render.rs | 88 +- tests/view/document-annot-demo.mq.md | 62 ++ 15 files changed, 3317 insertions(+), 30 deletions(-) create mode 100644 doc/design/view-document-annotations.md create mode 100644 doc/design/view-execution-trace.md create mode 100644 doc/design/view-frame-selection.md create mode 100644 src/view/annot.rs create mode 100644 src/view/document.rs create mode 100644 tests/view/document-annot-demo.mq.md diff --git a/doc/design/view-debug.md b/doc/design/view-debug.md index d32a402..cfd2304 100644 --- a/doc/design/view-debug.md +++ b/doc/design/view-debug.md @@ -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` **不能**真断点。 diff --git a/doc/design/view-document-annotations.md b/doc/design/view-document-annotations.md new file mode 100644 index 0000000..de57fee --- /dev/null +++ b/doc/design/view-document-annotations.md @@ -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 | diff --git a/doc/design/view-execution-trace.md b/doc/design/view-execution-trace.md new file mode 100644 index 0000000..cd07304 --- /dev/null +++ b/doc/design/view-execution-trace.md @@ -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 表 | `` | +| `-` 循环 | `
"#, + line = first_line + ); + let mut header_done = false; + for (idx, (_ln, row)) in rows.iter().enumerate() { + if looks_like_table_sep(row) { + continue; + } + let cells: Vec<&str> = row + .trim() + .trim_matches('|') + .split('|') + .map(|c| c.trim()) + .collect(); + if !header_done { + html.push_str(""); + for c in &cells { + html.push_str(&format!("", escape(c))); + } + html.push_str(""); + header_done = true; + // If next is sep, skip handled above; if only one data row treated as header+body empty ok + if idx + 1 < rows.len() && looks_like_table_sep(&rows[idx + 1].1) { + continue; + } + // Single-row table without sep: also emit as body + if rows.len() == 1 { + html.push_str(""); + for c in &cells { + html.push_str(&format!("", escape(c))); + } + html.push_str(""); + } + continue; + } + html.push_str(""); + for c in &cells { + html.push_str(&format!("", escape(c))); + } + html.push_str(""); + } + if header_done { + html.push_str(""); + } + html.push_str("
{}
{}
{}
"); + // Annots on first table line (bind of collection). + if let Some(list) = by_line.get(&first_line) { + if !list.is_empty() { + let owned: Vec = list.iter().map(|a| (*a).clone()).collect(); + html.push_str(&render_annot_band(&owned, MAX_VISIBLE_ANNOTS)); + } + } + if let Some(body) = writebacks.get(&first_line) { + html.push_str(&format!( + r#"
{}
"#, + escape(body), + line = first_line + )); + } + html.push_str(""); + (html, i) +} + +fn render_list_block( + lines: &[ClassifiedLine], + start: usize, + kind: ListKind, + _marker_len: usize, + by_line: &HashMap>, + special: &HashMap, + writebacks: &HashMap, + taken_arms: &HashMap, + all_annots: &[ViewAnnot], +) -> (String, usize) { + let base_indent = indent_level(&lines[start].text); + let tag = match kind { + ListKind::Ul => "ul", + ListKind::Ol => "ol", + }; + let cls = match kind { + ListKind::Ul => "doc-loop", + ListKind::Ol => "doc-branch", + }; + // Branch stmt line = list head line for taken-arm lookup. + let branch_line = lines[start].line_no; + let taken = taken_arms.get(&branch_line).copied(); + + let loop_id = all_annots + .iter() + .find(|a| { + a.kind == crate::view::annot::AnnotKind::LoopFrame && a.anchor_line == branch_line + }) + .and_then(|a| a.loop_id); + + let mut html = format!( + r#"<{tag} class="{cls}" data-line="{line}"{loop_attr} style="--doc-indent:{indent}">"#, + tag = tag, + cls = cls, + line = branch_line, + loop_attr = loop_id + .map(|id| format!(r#" data-loop-id="{id}""#)) + .unwrap_or_default(), + indent = base_indent.max(1), + ); + + // Loop iteration picker (default = last). + if matches!(kind, ListKind::Ul) { + let frames: Vec<&ViewAnnot> = all_annots + .iter() + .filter(|a| { + a.kind == crate::view::annot::AnnotKind::LoopFrame + && a.anchor_line == branch_line + }) + .collect(); + if frames.len() >= 2 { + html.push_str(r#"
  • "); + } + } + + let mut i = start; + let mut arm_index = 0usize; + while i < lines.len() { + let text = lines[i].text.trim_end_matches(['\r', '\n']); + let trimmed = text.trim_start(); + let ind = indent_level(text); + if lines[i].kind == LineKind::Blank { + // Blank inside list: peek ahead — if next is deeper/same list continue, else break. + if i + 1 < lines.len() { + let n = &lines[i + 1]; + let nt = n.text.trim_end_matches(['\r', '\n']); + if nt.trim().is_empty() { + i += 1; + continue; + } + let nind = indent_level(nt); + if nind > base_indent + || (nind == base_indent && list_marker(nt.trim_start()).is_some()) + { + i += 1; + continue; + } + } + break; + } + if ind < base_indent { + break; + } + if ind == base_indent { + if let Some((k, mlen)) = list_marker(trimmed) { + if !matches!( + (k, kind), + (ListKind::Ul, ListKind::Ul) | (ListKind::Ol, ListKind::Ol) + ) { + break; + } + let head = trimmed[mlen..].trim(); + let arm_cls = match (kind, taken) { + (ListKind::Ol, Some(t)) if t == arm_index => "arm-taken", + (ListKind::Ol, Some(_)) => "arm-miss", + (ListKind::Ol, None) => "", + _ => "", + }; + html.push_str(&format!( + r#"
  • "#, + arm_cls = arm_cls, + line = lines[i].line_no, + arm_idx = arm_index, + indent = ind.max(1), + )); + html.push_str(&format!( + r#"
    {}
    "#, + render_surface_line(lines[i].line_no, head, by_line) + )); + // Annots for this line; Branch chips on the arm they refer to (filtered by call frame in JS). + let mut head_annots: Vec = Vec::new(); + if let Some(list) = by_line.get(&lines[i].line_no) { + for a in list { + if a.kind == crate::view::annot::AnnotKind::Branch { + continue; + } + head_annots.push((*a).clone()); + } + } + if matches!(kind, ListKind::Ol) { + // Branch annots are keyed to the list's first line, not each arm head. + if let Some(list) = by_line.get(&branch_line) { + for a in list { + if a.kind == crate::view::annot::AnnotKind::Branch + && a.arm_index == Some(arm_index) + { + head_annots.push((*a).clone()); + } + } + } + } + if !head_annots.is_empty() { + html.push_str(&render_annot_band(&head_annots, MAX_VISIBLE_ANNOTS)); + } + // Body: following lines with greater indent until next sibling. + i += 1; + html.push_str(r#"
    "#); + while i < lines.len() { + let t2 = lines[i].text.trim_end_matches(['\r', '\n']); + if t2.trim().is_empty() { + // allow blank inside body + if i + 1 < lines.len() + && indent_level(&lines[i + 1].text) > base_indent + { + i += 1; + continue; + } + break; + } + let ind2 = indent_level(t2); + if ind2 <= base_indent { + break; + } + // Nested list at deeper indent. + let tr2 = t2.trim_start(); + if let Some((nk, _)) = list_marker(tr2) { + let (inner, next) = render_list_block( + lines, + i, + nk, + 0, + by_line, + special, + writebacks, + taken_arms, + all_annots, + ); + html.push_str(&inner); + i = next; + continue; + } + if looks_like_table_row(tr2) { + let (th, next) = render_table_block(lines, i, by_line, writebacks); + html.push_str(&th); + i = next; + continue; + } + let bits = scan_prose_line(t2); + html.push_str(&render_line_block( + lines[i].line_no, + t2, + &bits, + by_line + .get(&lines[i].line_no) + .map(|v| v.as_slice()) + .unwrap_or(&[]), + special.get(&lines[i].line_no), + writebacks.get(&lines[i].line_no), + Some(ind2), + )); + i += 1; + } + html.push_str("
  • "); + arm_index += 1; + continue; + } + break; + } + // Deeper than base but not under an open item — shouldn't happen; stop. + break; + } + html.push_str(&format!("", tag = tag)); + (html, i) +} + +fn render_surface_line( + line_no: u32, + head: &str, + by_line: &HashMap>, +) -> String { + let bits = scan_prose_line(head); + if bits.is_empty() { + // Else arm "*" or plain condition text. + if head.trim() == "*" { + return r#"else"#.into(); + } + format!( + r#"{}"#, + escape(head) + ) + } else { + let annots = by_line + .get(&line_no) + .map(|v| v.as_slice()) + .unwrap_or(&[]); + render_prose_with_marks(line_no, head, &bits, annots) + } +} + +/// SSR default: taken arm for the highest `call_id` per branch line (matches last-call picker). +fn taken_arms_by_branch_line(annots: &[ViewAnnot]) -> HashMap { + let mut best: HashMap = HashMap::new(); + for a in annots { + if a.kind != crate::view::annot::AnnotKind::Branch { + continue; + } + let Some(idx) = a.arm_index else { continue }; + let cid = a.call_id.unwrap_or(0); + let entry = best.entry(a.anchor_line).or_insert((cid, idx)); + if cid >= entry.0 { + *entry = (cid, idx); + } + } + best.into_iter().map(|(line, (_, arm))| (line, arm)).collect() +} + +fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String { + let mut s = format!( + r#"
    +
    +

    {name}

    "#, + line = fun.span.line, + name = escape(&fun.name), + ); + // Call picker placeholder: filled when ≥2 call frames exist for this fn. + let call_labels: Vec<&ViewAnnot> = annots + .iter() + .filter(|a| a.kind == crate::view::annot::AnnotKind::CallFrame && a.label == fun.name) + .collect(); + if call_labels.len() >= 2 { + s.push_str(r#""); + } + s.push_str("
    "); + if !fun.params.is_empty() { + s.push_str(r#"
    "#); + for p in &fun.params { + let cls = if p.inferred { + "chip inferred" + } else { + "chip" + }; + let title = if p.inferred { + "inferred from prose / body" + } else { + "explicit + param" + }; + s.push_str(&format!( + r#"{name}"#, + cls = cls, + title = title, + name = escape(&p.name), + )); + } + s.push_str("
    "); + } + s.push_str("
    "); + s +} + +fn render_line_block( + line_no: u32, + text: &str, + bits: &[ProseBit], + annots: &[&ViewAnnot], + special: Option<&SpecialAssign>, + writeback_body: Option<&String>, + indent: Option, +) -> String { + let indent_style = indent + .map(|n| format!(r#" style="--doc-indent:{n}""#)) + .unwrap_or_default(); + // Source structure always visible — do not stamp data-call-ids (frame filter is chips-only). + let mut s = format!( + r#"
    "#, + line = line_no, + indent = indent_style, + ); + + match special { + Some(SpecialAssign::Formula { name, tex }) => { + s.push_str(&render_formula_assign_card(name, tex)); + } + Some(SpecialAssign::Code { + name, + lang, + source, + }) => { + s.push_str(&render_code_assign_card(name, lang, source)); + } + None => { + let trimmed = text.trim_start(); + if bits.is_empty() { + if let Some(rest) = trimmed.strip_prefix("> ") { + s.push_str(&format!( + r#"
    > {}
    "#, + escape(rest) + )); + } else if let Some(rest) = trimmed.strip_prefix('>') { + s.push_str(&format!( + r#"
    > {}
    "#, + escape(rest.trim_start()) + )); + } else { + s.push_str(&format!( + r#"
    {}
    "#, + escape(trimmed) + )); + } + } else { + s.push_str(r#"
    "#); + s.push_str(&render_prose_with_marks(line_no, text, bits, annots)); + s.push_str("
    "); + } + } + } + + if let Some(body) = writeback_body { + s.push_str(&format!( + r#"
    {}
    "#, + escape(body), + line = line_no + )); + } + + if !annots.is_empty() { + let owned: Vec = annots.iter().map(|a| (*a).clone()).collect(); + s.push_str(&render_annot_band(&owned, MAX_VISIBLE_ANNOTS)); + } + + s.push_str("
    "); + s +} + +/// Render prose with markers stripped; show surface inner text only. +fn render_prose_with_marks( + line_no: u32, + text: &str, + bits: &[ProseBit], + annots: &[&ViewAnnot], +) -> String { + let mut html = String::new(); + let mut cursor = 0usize; + for bit in bits { + let start = bit_at(bit); + let end = prose_bit_end(text, bit); + if start > cursor { + html.push_str(&escape(&text[cursor..start])); + } + if start < end && end <= text.len() { + let (cls, display) = bit_display(bit); + let annot_id = match_annot_for_span(annots, start, end) + .map(|a| a.id.as_str()) + .unwrap_or(""); + html.push_str(&format!( + r#"{inner}"#, + cls = cls, + line = line_no, + start = start, + end = end, + aid = escape(annot_id), + inner = escape(&display), + )); + } + cursor = end.max(cursor); + } + if cursor < text.len() { + html.push_str(&escape(&text[cursor..])); + } + html +} + +fn bit_display(bit: &ProseBit) -> (&'static str, String) { + match bit { + ProseBit::Decl { name, default, .. } => { + let cls = bit_kind_class(bit); + let s = match default { + Some(d) => format!("{name}={d}"), + None => name.clone(), + }; + (cls, s) + } + ProseBit::BoldCode { inner, .. } => (bit_kind_class(bit), inner.clone()), + ProseBit::ItalicReturn { inner, .. } => (bit_kind_class(bit), inner.clone()), + } +} + +fn match_annot_for_span<'a>( + annots: &[&'a ViewAnnot], + start: usize, + end: usize, +) -> Option<&'a ViewAnnot> { + annots.iter().copied().find(|a| match (a.anchor_byte_start, a.anchor_byte_end) { + (Some(s), Some(e)) => s < end && e > start, + (Some(s), None) => s >= start && s < end, + _ => false, + }) +} + +#[derive(Clone)] +enum SpecialAssign { + Formula { name: String, tex: String }, + Code { name: String, lang: String, source: String }, +} + +fn index_functions(module: &Module) -> HashMap { + let mut m = HashMap::new(); + fn walk<'a>(fun: &'a Function, m: &mut HashMap) { + m.insert(fun.span.line, fun); + for c in &fun.children { + walk(c, m); + } + } + for f in &module.functions { + walk(f, &mut m); + } + m +} + +fn index_stmt_lines(module: &Module) -> HashSet { + let mut s = HashSet::new(); + fn walk(fun: &Function, s: &mut HashSet) { + for st in &fun.body { + s.insert(stmt_line(st)); + walk_stmt(st, s); + } + for c in &fun.children { + walk(c, s); + } + } + fn walk_stmt(st: &Stmt, s: &mut HashSet) { + match st { + Stmt::Branch { arms, .. } => { + for arm in arms { + for b in &arm.body { + s.insert(stmt_line(b)); + walk_stmt(b, s); + } + } + } + Stmt::While { body, .. } | Stmt::ForEach { body, .. } => { + for b in body { + s.insert(stmt_line(b)); + walk_stmt(b, s); + } + } + _ => {} + } + } + for f in &module.functions { + walk(f, &mut s); + } + s +} + +fn stmt_line(st: &Stmt) -> u32 { + match st { + Stmt::Assign { span, .. } + | Stmt::Return { span, .. } + | Stmt::Call { span, .. } + | Stmt::Expr { span, .. } + | Stmt::Branch { span, .. } + | Stmt::While { span, .. } + | Stmt::ForEach { span, .. } => span.line, + } +} + +fn index_special_assigns(module: &Module) -> HashMap { + let mut m = HashMap::new(); + fn walk(fun: &Function, m: &mut HashMap) { + for st in &fun.body { + record(st, m); + match st { + Stmt::Branch { arms, .. } => { + for arm in arms { + for b in &arm.body { + record(b, m); + } + } + } + Stmt::While { body, .. } | Stmt::ForEach { body, .. } => { + for b in body { + record(b, m); + } + } + _ => {} + } + } + for c in &fun.children { + walk(c, m); + } + } + fn record(st: &Stmt, m: &mut HashMap) { + match st { + Stmt::Assign { + name, + value: crate::ast::Expr::Formula(e), + span, + .. + } => { + let tex = match e { + crate::formula::Expr::Matrix { source, .. } => source.clone(), + _ => crate::view::render::formula_ascii_to_tex_pub(&e.as_display()), + }; + m.insert( + span.line, + SpecialAssign::Formula { + name: name.clone(), + tex, + }, + ); + } + Stmt::Assign { + name, + value: crate::ast::Expr::Code(c), + span, + .. + } => { + m.insert( + span.line, + SpecialAssign::Code { + name: name.clone(), + lang: c.lang.clone(), + source: c.source.clone(), + }, + ); + } + _ => {} + } + } + for f in &module.functions { + walk(f, &mut m); + } + m +} + +fn skip_frontmatter_end(lines: &[ClassifiedLine]) -> Option { + let first_code = lines.iter().find(|l| l.kind == LineKind::Code)?; + if first_code.text.trim() != "---" { + return Some(1); + } + for l in lines.iter().skip_while(|l| l.line_no <= first_code.line_no) { + if l.kind == LineKind::Code && l.text.trim() == "---" { + return Some(l.line_no + 1); + } + } + Some(1) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::view::annot::build_view_annots; + + #[test] + fn document_keeps_inc_prose_narration() { + let src = include_str!("../../tests/markup-v03/inc-prose.mq.md"); + let module = crate::parse::parse_source(src).unwrap(); + let html = render_module_document(&module, src, &[]); + assert!( + html.contains("对于输入变量") && html.contains("我们执行操作"), + "narration stripped: {html}" + ); + assert!(html.contains("mq-anchor"), "expected anchors: {html}"); + assert!(html.contains("document-surface"), "{html}"); + // Marker surface: no raw ** delimiters around assign. + assert!( + !html.contains("**n=n+1**") && !html.contains("**n = n + 1**"), + "raw bold delimiters leaked: {html}" + ); + assert!(html.contains("n=n+1") || html.contains(">n=n+1<") || html.contains("n=n+1"), "{html}"); + } + + #[test] + fn document_strips_marker_delimiters() { + let src = "# main\n\n**x = 1**\n"; + let module = crate::parse::parse_source(src).unwrap(); + let html = render_module_document(&module, src, &[]); + assert!(html.contains("mq-code"), "{html}"); + assert!(!html.contains("**x = 1**"), "{html}"); + assert!(html.contains(">x = 1<") || html.contains("x = 1"), "{html}"); + } + + #[test] + fn document_renders_table_and_lists() { + let src = include_str!("../../tests/view/document-annot-demo.mq.md"); + let module = crate::parse::parse_source(src).unwrap(); + let html = render_module_document(&module, src, &[]); + assert!(html.contains("doc-table") || html.contains("仓库"), + "{html}" + ); + } + + #[test] + fn document_annot_demo_keeps_narration_and_control_flow() { + 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); + let html = render_module_document(&module, src, &annots); + assert!(html.contains("本页演示"), "{html}"); + assert!(html.contains("annot-band"), "{html}"); + assert!( + annots + .iter() + .any(|a| a.kind == crate::view::annot::AnnotKind::LoopFrame + || (a.kind == crate::view::annot::AnnotKind::Bind && a.loop_id.is_some())), + "loop frame / item bind missing: {:?}", + cap.view_trace + ); + assert!( + annots.iter().any(|a| a.kind == crate::view::annot::AnnotKind::Branch), + "branch annot missing: {:?}", + cap.view_trace + ); + } + + #[test] + fn document_frame_pickers_and_all_arms() { + 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); + let html = render_module_document(&module, src, &annots); + // All three return arms of 等级说明 stay in the source surface. + assert!(html.contains("均分很高"), "arm1 return missing: {html}"); + assert!(html.contains("已过线"), "arm2 return missing: {html}"); + assert!(html.contains("建议安排复习周"), "arm3 return missing: {html}"); + assert!(html.contains("arm-miss"), "expected dimmed arms: {html}"); + assert!(html.contains("arm-taken"), "expected taken arm: {html}"); + // Call picker uses numeric call_id values (not cfN ids). + assert!(html.contains("call-picker"), "{html}"); + assert!( + html.contains(r#"value="2""#) || html.contains(r#"value="3""#), + "call picker should use numeric call_id: {html}" + ); + // Loop iteration picker defaults to last. + assert!(html.contains("loop-picker"), "{html}"); + assert!(html.contains("分数表[3]"), "expected last-iter binding: {html}"); + // Branch chips carry call_id for frame filter. + assert!( + html.contains(r#"data-call-id=""#) || html.contains("data-call-id="), + "{html}" + ); + } +} diff --git a/src/view/html.rs b/src/view/html.rs index aa3556b..d60134e 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -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(" @@ -2300,6 +2734,7 @@ window.MARQDO_VIEW_LIVE = {live}; window.MARQDO_FILE_PATH = {path_js}; window.MARQDO_AUTO_STREAM = {auto_stream}; +

    {title}{status_label}

    {rel}

    @@ -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, diff --git a/src/view/mod.rs b/src/view/mod.rs index bbb570c..5e31c2b 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -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 = 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()); } diff --git a/src/view/output.rs b/src/view/output.rs index 5ef951e..659f1ed 100644 --- a/src/view/output.rs +++ b/src/view/output.rs @@ -32,11 +32,17 @@ pub fn write_static(opts: OutputOptions) -> Result<()> { vm.ok = true; vm.plots.clear(); vm.bindings_html = String::from(r#"

    skipped

    "#); - // 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 { diff --git a/src/view/render.rs b/src/view/render.rs index 46f98d4..ddb0947 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -45,6 +45,8 @@ pub struct FileViewModel { pub plots: Vec, /// 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!( + "
    formula \ + `{}` = \ +
    $${}$$
    ", + 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#"
    +
    + code + `{name}` = + {lang} +
    + + +
    +
    +
    {src}
    + +
    "#, + 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 = 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("段首说明

    ")); + let blocks = html.matches("doc-prose").count(); + assert!(blocks >= 2, "blank line should split comment paragraphs: {html}"); + assert!(html.contains("段首说明 续行仍属同段") || html.contains("段首说明

    ") || 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] diff --git a/tests/view/document-annot-demo.mq.md b/tests/view/document-annot-demo.mq.md new file mode 100644 index 0000000..1c6f539 --- /dev/null +++ b/tests/view/document-annot-demo.mq.md @@ -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. * + *"建议安排复习周,再测一次。"*