From 54a507d906fd944eb7d7712d98eb22a370e85dcd Mon Sep 17 00:00:00 2001 From: cflmy Date: Wed, 5 Aug 2026 15:40:29 +0800 Subject: [PATCH] Ship v0.1.0: dedicated debug host, view outline, code-as-docs README. Add marqdo debug (breakpoints/step/locals), restore view as docs with function search, and emphasize OKF-aligned knowledge-base direction. Co-authored-by: Cursor --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 48 +- doc/design/view-debug.md | 42 ++ doc/design/view.md | 14 +- doc/roadmap/next-phase.md | 9 +- scripts/publish-release.py | 34 +- src/debug/ctrl.rs | 345 +++++++++++++ src/debug/mod.rs | 6 +- src/interp.rs | 28 +- src/main.rs | 33 +- src/view/debug_api.rs | 203 ++++++++ src/view/debug_page.rs | 973 +++++++++++++++++++++++++++++++++++++ src/view/html.rs | 173 ++++++- src/view/mod.rs | 131 ++++- src/view/render.rs | 178 +++++-- 16 files changed, 2136 insertions(+), 85 deletions(-) create mode 100644 doc/design/view-debug.md create mode 100644 src/debug/ctrl.rs create mode 100644 src/view/debug_api.rs create mode 100644 src/view/debug_page.rs diff --git a/Cargo.lock b/Cargo.lock index d925f75..dc3ad20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -344,7 +344,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" [[package]] name = "marqdo" -version = "0.0.4" +version = "0.1.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index f8ff71a..79a904a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "marqdo" -version = "0.0.4" +version = "0.1.0" edition = "2021" license = "Apache-2.0" description = "Marqdo — Markdown markers as an interpreted programming language" diff --git a/README.md b/README.md index e24c439..73fc8b7 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,25 @@ # Marqdo -**代码即文档。文档即代码。** +**代码即文档。文档即代码。文档即知识库。** -Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程序。 +Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,既是给人读的文稿,也是给机器跑的程序。写文档的过程就是在写可执行逻辑——大型项目里,说明、示例与实现不再分叉成三份真相。 -欢迎访问[marqdo官方网站](https://www.marqdo.com/)阅读marqdo更多特性 +欢迎访问 [marqdo 官方网站](https://www.marqdo.com/) 阅读更多特性与可执行文档。 -语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 调用实参:[call-arguments.md](doc/design/call-arguments.md) · 测试布局:[examples-and-tests.md](doc/design/examples-and-tests.md) · 用户站:[user-site.md](doc/design/user-site.md) · 浏览:[view.md](doc/design/view.md) · 金样例:[tests/](tests/) · 用户文档:[public/](public/) +语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 调用实参:[call-arguments.md](doc/design/call-arguments.md) · 用户站:[user-site.md](doc/design/user-site.md) · 浏览:[view.md](doc/design/view.md) · 调试:[view-debug.md](doc/design/view-debug.md) · 金样例:[tests/](tests/) · 用户文档:[public/](public/) + +--- + +## 为什么重要 + +| 痛点 | Marqdo 的答案 | +|------|----------------| +| 文档过期、示例跑不通 | **一份源文件**:叙述、结构与执行结果同源 | +| 知识散落在 Wiki / 注释 / 脚本里 | **`.mq.md` 即知识单元**,可浏览、可运行、可检索 | +| 人写给人看,AI / 工具另起一套 | **人机同读同写同构**:标记语言对人类友好,对解释器确定 | +| 大仓里「文档站」与「代码仓」脱节 | `view` 文档站 + `debug` 调试面 + `catalog` 清单,同一棵树长大 | + +这不是「再做一个 Markdown 渲染器」,而是:**把文档升格为可解释的程序与可生长的知识库**,让协作在大型项目里依然站得住。 --- @@ -39,33 +52,34 @@ Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程 ## 理念 -1. 叙述默认安全(无标记 = 注释)。 -2. 返回是架构;打印只是函数。 -3. 依赖清单由工具生成(OKF 风格),不是手填配置。 -4. **正经解释器(Rust)**:词法/行分类 → 递归下降语法 → 语义 → 树遍历 → 日后字节码;**不用 Flex/Bison**。见 [路线图](doc/roadmap/interpreter.md) 与 [依赖说明](doc/design/dependencies.md)。 +1. **叙述默认安全**(无标记 = 注释)。 +2. **返回是架构;打印只是函数。** +3. **代码即文档即知识库**:文稿可执行,执行可回看结构,结构可导航与调试。 +4. **计划对齐 [OKF](doc/design/generated-yaml-manifest.md) 规范**:依赖与模块清单由工具生成(`marqdo catalog` / `sync`),不是手填配置——知识图谱与仓库结构同源生长。见 [catalog-cli.md](doc/design/catalog-cli.md)。 +5. **正经解释器(Rust)**:词法/行分类 → 语法 → 语义 → 树遍历(及字节码);**不用 Flex/Bison**。见 [路线图](doc/roadmap/interpreter.md)。 --- -## 现状 +## 现状(v0.1.0) -- 映射 v0.1:[markdown-mapping.md](doc/design/markdown-mapping.md) -- 解释器路线图:[interpreter.md](doc/roadmap/interpreter.md) -- **Phase I(树遍历)已通**:`tests/structure/` 与 `tests/keywords/` 金样例均可 `marqdo run` -- **view**:`marqdo view public` 浏览用户文档;金样例用 `marqdo view tests` -- **用户静态站**:可执行文稿在 `public/`(无 errors);`view output` 生成 HTML(ignore),CI 发布到 `gh-pages` — 见 [user-site.md](doc/design/user-site.md) -- 依赖(Rust,无 Flex/Bison):[dependencies.md](doc/design/dependencies.md) -- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) +- 映射与解释器:Phase I 树遍历 + 字节码后端可用;金样例在 `tests/` +- **`marqdo view`**:文档浏览器(Structure + 函数大纲/搜索 + Execution + Source) +- **`marqdo debug`**:独立调试页(断点 / 单步 / locals;默认端口 7430) +- 标准库:文本、文件、系统、时间、JSON、网络、数学(公式/绘图)、外联(Python 等) +- **用户静态站**:`public/` → `view output` → CI 发布 [gh-pages](https://cflmy.github.io/marqdo/) +- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) ```bash cargo run -- run tests/structure/hello.mq.md cargo run -- run tests/structure/hello.mq.md --backend bytecode cargo run -- view public --no-open +cargo run -- debug public --no-open cargo run -- view output public -o public powershell -File ./scripts/build-public.ps1 cargo run -- catalog tests -o .marqdo ``` -文档:用户站见 [public/](public/) 与 [user-site.md](doc/design/user-site.md);设计文稿见 [doc/](doc/);`view` 皮肤见 [view.md](doc/design/view.md);OKF 清单见 [catalog-cli.md](doc/design/catalog-cli.md)。 +文档:用户站 [public/](public/) · 设计 [doc/](doc/) · OKF / catalog [catalog-cli.md](doc/design/catalog-cli.md) · 调试 [view-debug.md](doc/design/view-debug.md) --- diff --git a/doc/design/view-debug.md b/doc/design/view-debug.md new file mode 100644 index 0000000..d32a402 --- /dev/null +++ b/doc/design/view-debug.md @@ -0,0 +1,42 @@ +# View 调试(`marqdo debug`) + +| | | +|---|---| +| 状态 | **v1(独立 debug 页)** | +| 日期 | 2026-08-05 | +| 相关 | [next-phase.md](../roadmap/next-phase.md) P3 · [view.md](view.md) · [pipeline-debug.md](pipeline-debug.md) | + +## 分工 + +| 命令 | 角色 | +|------|------| +| `marqdo view` | 文档浏览器:Structure + Execution + Source;函数大纲与搜索;**无断点** | +| `marqdo debug` | 调试宿主(默认端口 **7430**):IDE 式布局;**仅 live** | + +静态 `gh-pages` / `view output` **不能**真断点。 + +## Debug 布局(对齐常见调试器) + +参考 VS Code / Chrome DevTools / Jupyter debugger: + +``` +┌ Toolbar: Start · Continue (F5) · Step (F10) · Stop · status ─┐ +├ Files ─┬─ Structure (gutter BP) + outline ─┬─ Variables ┤ +│ │ ├─ Breakpoints │ +│ │ └─ Call stack │ +├────────┴────────────────────────────────────┴────────────────┤ +│ Debug Console (session stdout) │ +└──────────────────────────────────────────────────────────────┘ +``` + +- 暂停粒度:语句起点(树遍历)。 +- 无断点时 Start 停在第一句。 +- Structure 为断点面(非 Source 行)。 + +## API + +与此前相同:`POST /api/debug/start|continue|step|stop|breakpoints`(仅 debug 服务)。 + +## View 大纲 + +Structure 旁(或窄屏下方)函数树:`#fn-{line}` 锚点 + 搜索框过滤 `data-fn` / `data-fn-path`。 diff --git a/doc/design/view.md b/doc/design/view.md index 7f7e39e..eb1af26 100644 --- a/doc/design/view.md +++ b/doc/design/view.md @@ -25,14 +25,14 @@ | 规则 | 要求 | |------|------| | 色板 | 页底 `#f5f5f7`;内容面 `#ffffff`;正文 `#1d1d1f`;次要字 `#6e6e73`;分隔 `#d2d2d7`;选中侧栏项反白 | -| 布局 | 壳层 `max-width ≈ 1400px` 居中;侧栏 ≈280px sticky;主内容 `max-width ≈ 58rem`(宽屏可读、不过窄);**≤800px 侧栏收起**,顶栏汉堡(checkbox,无 JS) | +| 布局 | 壳层 `max-width ≈ 1680px`;侧栏 ≈280px;主内容 `max-width ≈ 76rem`;Structure 旁函数大纲;**≤800px 侧栏收起** | | 默认页 | 打开目录时 **直接展示排序后的第一个 `.mq.md`**(实时 `/` 与静态 `index.html` 同),不要求用户先从欢迎页点选 | | 字体 | 仅系统栈:`-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif`;等宽 `ui-monospace, SFMono-Regular, Menlo, Consolas, monospace` | | 外链 | **禁止** Google Fonts / CDN 样式;CSS 全部内联于 HTML | | 装饰 | 无多层阴影、无渐变、无发光;圆角 ≈12px;结构区为分组列表(底部分隔),非堆叠厚卡片 | | 诊断路径 | 展示时去掉 Windows `\\?\` 前缀,并优先用相对 view 根的路径 | -验收:首屏无外网字体请求;宽屏主栏明显宽于早期 `40rem` 方案。 +验收:首屏无外网字体请求;宽屏主栏明显宽于早期 `58rem` 方案(现约 `76rem` / 壳 `1680px`)。 --- @@ -88,9 +88,10 @@ marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc --- -## 4. 信息架构(不变) +## 4. 信息架构 -侧栏索引 + 主区三节:结构(AST+注释插回)· 执行 · 源码。表达式为表面语法,非 Debug。 +侧栏文件索引 + 主区:结构(AST+注释;旁侧函数大纲可搜索)· 执行 · 源码。表达式为表面语法。 +**断点调试**不在 view 内,见 [`marqdo debug`](view-debug.md)。 --- @@ -108,7 +109,8 @@ marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc ## 6. 验收 -1. 实时 `view`:HIG 风极简、无外链字体、结构与执行正确;打开目录即见首个文件。 +1. 实时 `view`:HIG 风极简、无外链字体、结构与执行正确;打开目录即见首个文件;函数大纲可搜索跳转。 2. `view output public -o public`(或临时目录)生成可点的 `index.html`(首文件)与各 `pages/…`。 3. 静态页中执行区与 `marqdo run` 一致(未加 `--no-exec` 时);失败诊断路径无 `\\?\`。 -4. 冷启动无明显外网依赖。 +4. 冷启动无明显外网依赖。 +5. 调试用 `marqdo debug`(默认端口 7430),与 view 页面分离。 diff --git a/doc/roadmap/next-phase.md b/doc/roadmap/next-phase.md index c75f170..5ce0259 100644 --- a/doc/roadmap/next-phase.md +++ b/doc/roadmap/next-phase.md @@ -2,10 +2,10 @@ | | | |---|---| -| 状态 | **进行中**(P2 完成;下一:P3-D2 调试会话) | -| 日期 | 2026-08-04 | +| 状态 | **进行中**(P3-D1–D3 live view 断点 v1) | +| 日期 | 2026-08-05 | | 目标 | 交互 I/O、可信诊断、可生长标准库;view 渐进成为调试宿主 | -| 相关 | [interpreter.md](interpreter.md) · [keywords.md](../design/keywords.md) · [pipeline-debug.md](../design/pipeline-debug.md) · [view.md](../design/view.md) | +| 相关 | [interpreter.md](interpreter.md) · [keywords.md](../design/keywords.md) · [pipeline-debug.md](../design/pipeline-debug.md) · [view.md](../design/view.md) · [view-debug.md](../design/view-debug.md) | --- @@ -16,7 +16,8 @@ | **`print`** | 树遍历 + 字节码均可用 | 够用 | | **`input`** | CLI 双后端 + `--stdin-file`;frontmatter `stdin:`/`输入:`;live view 表单覆盖;无预置时 capture 提示补线 | **P1a + P1b 完成** | | **诊断** | 语句级 `path:line:col: message`;字节码指令带 `spans`;errors 金样例双后端断言位置 | **P0 完成** | -| **view** | 结构 + 一次执行 + 源码;注释已 Markdown 渲染;无暂停/断点 | **文档浏览器,不是调试器** | +| **view** | 结构 + 执行 + 源码 + 函数大纲/搜索;无断点 | 文档浏览器 | +| **debug** | 独立 `marqdo debug`:断点 / 单步 / locals(树遍历) | **P3-D3 v1** | | **标准库** | S0–S3 完成;本波扩展 = 文件/系统/时间/JSON/网络([stdlib-modules.md](../design/stdlib-modules.md));数学/外联暂缓 | **P2 完成;五库扩展设计中** | | **模块** | `> file.mq.md` 顶层函数合并,无命名空间 | 短期可继续用 | diff --git a/scripts/publish-release.py b/scripts/publish-release.py index 4fa92cc..e981295 100644 --- a/scripts/publish-release.py +++ b/scripts/publish-release.py @@ -51,25 +51,36 @@ def api(method: str, url: str, token: str, data: bytes | None = None, content_ty raise SystemExit(f"HTTP {e.code} {url}: {err}") from e +def find_assets(stem: str) -> list[Path]: + assets: list[Path] = [] + for base in (Path("dist"), Path("target/dist")): + for name in (f"{stem}.exe", f"{stem}.zip"): + p = base / name + if p.exists() and all(p.resolve() != a.resolve() for a in assets): + assets.append(p) + if len(assets) >= 2: + break + if len(assets) < 2: + raise SystemExit( + f"missing assets for {stem}.exe/.zip under dist/ or target/dist/" + ) + return assets + + def main() -> None: ver = crate_version() tag = f"v{ver}" stem = f"marqdo-{ver}-x86_64-pc-windows-msvc" - assets = [ - Path(f"target/dist/{stem}.exe"), - Path(f"target/dist/{stem}.zip"), - ] - for p in assets: - if not p.exists(): - raise SystemExit(f"missing asset: {p}") + assets = find_assets(stem) notes = f"""## Marqdo {tag} ### Highlights -- Function body end via `---` / `***` or empty `****` return -- Blank-line paragraph comments (lex + view rendering) -- Brand logo / favicon from s3.cflmy.cn -- Welcome docs and call-arg spaced named values +- **Code as docs as knowledge**: `.mq.md` is narrative + program in one tree +- **`marqdo debug`**: dedicated debugger (breakpoints / step / locals); view stays docs-only +- **View**: wider layout, function outline + search +- Foreign code Run works in debug; math / stdlib / foreign as before +- Roadmap: deeper **OKF**-aligned catalog so docs grow into a knowledge base for human–AI collaboration ### Assets - `{stem}.exe` — Windows x64 binary @@ -79,6 +90,7 @@ def main() -> None: marqdo --version marqdo run public/00-welcome.mq.md marqdo view public +marqdo debug public ``` """ diff --git a/src/debug/ctrl.rs b/src/debug/ctrl.rs new file mode 100644 index 0000000..4d0a756 --- /dev/null +++ b/src/debug/ctrl.rs @@ -0,0 +1,345 @@ +//! Interactive debug controller for tree-walk (view + tests). + +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; + +use crate::value::Value; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DebugAction { + Continue, + Step, + Stop, +} + +#[derive(Debug, Clone)] +pub struct DebugPause { + pub line: u32, + pub fun: String, + pub locals: Vec<(String, String)>, + pub stdout: String, +} + +#[derive(Debug, Clone)] +pub enum DebugSnapshot { + Idle, + Running, + Paused(DebugPause), + Done { + ok: bool, + stdout: String, + stderr: String, + }, +} + +struct Gate { + action: Mutex>, + cv: Condvar, +} + +/// Shared between the interpreter thread and HTTP/CLI control. +pub struct DebugController { + breakpoints: Mutex>, + /// Pause at the next statement (step). + step_once: AtomicBool, + stop: AtomicBool, + /// Skip re-breaking on this line once after continue-from-pause (same entry). + suppress_line: Mutex>, + gate: Gate, + snapshot: Mutex, + /// Notifies waiters that snapshot changed. + snap_cv: Condvar, +} + +impl DebugController { + pub fn new(breakpoints: HashSet) -> Arc { + Arc::new(Self { + breakpoints: Mutex::new(breakpoints), + step_once: AtomicBool::new(false), + stop: AtomicBool::new(false), + suppress_line: Mutex::new(None), + gate: Gate { + action: Mutex::new(None), + cv: Condvar::new(), + }, + snapshot: Mutex::new(DebugSnapshot::Idle), + snap_cv: Condvar::new(), + }) + } + + pub fn set_breakpoints(&self, lines: HashSet) { + *self.breakpoints.lock().unwrap() = lines; + } + + /// Pause at the next statement (used when starting with no breakpoints). + pub fn request_step(&self) { + self.step_once.store(true, Ordering::SeqCst); + } + + pub fn breakpoints(&self) -> HashSet { + self.breakpoints.lock().unwrap().clone() + } + + pub fn snapshot(&self) -> DebugSnapshot { + self.snapshot.lock().unwrap().clone() + } + + pub fn set_running(&self) { + *self.snapshot.lock().unwrap() = DebugSnapshot::Running; + self.snap_cv.notify_all(); + } + + pub fn set_done(&self, ok: bool, stdout: String, stderr: String) { + *self.snapshot.lock().unwrap() = DebugSnapshot::Done { + ok, + stdout, + stderr, + }; + self.snap_cv.notify_all(); + // Unblock any waiter in on_stmt + self.send_action(DebugAction::Stop); + } + + pub fn send_action(&self, action: DebugAction) { + // Clear stale Paused so wait_until_* does not return the previous pause. + { + let mut snap = self.snapshot.lock().unwrap(); + if matches!(&*snap, DebugSnapshot::Paused(_)) { + *snap = DebugSnapshot::Running; + self.snap_cv.notify_all(); + } + } + let mut g = self.gate.action.lock().unwrap(); + *g = Some(action); + self.gate.cv.notify_all(); + } + + /// Wait until snapshot is Paused or Done (or timeout). + pub fn wait_until_paused_or_done(&self, timeout: Duration) -> DebugSnapshot { + let mut snap = self.snapshot.lock().unwrap(); + let deadline = std::time::Instant::now() + timeout; + loop { + match &*snap { + DebugSnapshot::Paused(_) | DebugSnapshot::Done { .. } => return snap.clone(), + _ => {} + } + let now = std::time::Instant::now(); + if now >= deadline { + return snap.clone(); + } + let (s, _) = self + .snap_cv + .wait_timeout(snap, deadline - now) + .unwrap(); + snap = s; + } + } + + /// Called at the start of each statement. + pub fn on_stmt( + &self, + line: u32, + fun: &str, + locals: &HashMap, + stdout: &str, + ) -> Result<(), String> { + if self.stop.load(Ordering::SeqCst) { + return Err("debug stopped".into()); + } + + let step = self.step_once.swap(false, Ordering::SeqCst); + let is_bp = self.breakpoints.lock().unwrap().contains(&line); + let suppressed = *self.suppress_line.lock().unwrap() == Some(line); + if suppressed { + *self.suppress_line.lock().unwrap() = None; + } + let should_pause = step || (is_bp && !suppressed); + if !should_pause { + return Ok(()); + } + + let mut locals_v: Vec<(String, String)> = locals + .iter() + .map(|(k, v)| (k.clone(), v.as_display())) + .collect(); + locals_v.sort_by(|a, b| a.0.cmp(&b.0)); + + { + let mut snap = self.snapshot.lock().unwrap(); + *snap = DebugSnapshot::Paused(DebugPause { + line, + fun: fun.to_string(), + locals: locals_v, + stdout: stdout.to_string(), + }); + self.snap_cv.notify_all(); + } + + // Wait for Continue / Step / Stop + let mut guard = self.gate.action.lock().unwrap(); + loop { + while guard.is_none() { + guard = self.gate.cv.wait(guard).unwrap(); + } + let action = guard.take().unwrap(); + match action { + DebugAction::Continue => { + // Don't immediately re-break on this same line entry. + *self.suppress_line.lock().unwrap() = Some(line); + return Ok(()); + } + DebugAction::Step => { + self.step_once.store(true, Ordering::SeqCst); + *self.suppress_line.lock().unwrap() = Some(line); + return Ok(()); + } + DebugAction::Stop => { + self.stop.store(true, Ordering::SeqCst); + return Err("debug stopped".into()); + } + } + } + } +} + +/// Serialize snapshot for JSON APIs. +pub fn snapshot_json(s: &DebugSnapshot) -> serde_json::Value { + match s { + DebugSnapshot::Idle => serde_json::json!({ "status": "idle" }), + DebugSnapshot::Running => serde_json::json!({ "status": "running" }), + DebugSnapshot::Paused(p) => { + let locals: serde_json::Map = p + .locals + .iter() + .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone()))) + .collect(); + serde_json::json!({ + "status": "paused", + "line": p.line, + "fun": p.fun, + "locals": locals, + "stdout": p.stdout, + }) + } + DebugSnapshot::Done { + ok, + stdout, + stderr, + } => serde_json::json!({ + "status": "done", + "ok": ok, + "stdout": stdout, + "stderr": stderr, + }), + } +} + +/// Channel pair helper if needed by callers. +#[allow(dead_code)] +pub fn action_channel() -> (Sender, Receiver) { + mpsc::channel() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::thread; + use std::time::Duration; + + #[test] + fn pause_continue_and_locals() { + let ctrl = DebugController::new(HashSet::from([2])); + let c2 = ctrl.clone(); + let handle = thread::spawn(move || { + let mut locals = HashMap::new(); + locals.insert("x".into(), Value::Int(1)); + c2.on_stmt(1, "main", &locals, "").unwrap(); // no bp + locals.insert("x".into(), Value::Int(2)); + c2.on_stmt(2, "main", &locals, "hi\n").unwrap(); // pauses + locals.insert("x".into(), Value::Int(3)); + c2.on_stmt(3, "main", &locals, "hi\n").unwrap(); + c2.set_done(true, "hi\n".into(), String::new()); + }); + + let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); + match snap { + DebugSnapshot::Paused(p) => { + assert_eq!(p.line, 2); + assert_eq!(p.fun, "main"); + assert!(p.locals.iter().any(|(k, v)| k == "x" && v == "2")); + assert_eq!(p.stdout, "hi\n"); + } + other => panic!("expected paused, got {other:?}"), + } + ctrl.send_action(DebugAction::Continue); + let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); + match snap { + DebugSnapshot::Done { ok, stdout, .. } => { + assert!(ok); + assert_eq!(stdout, "hi\n"); + } + other => panic!("expected done, got {other:?}"), + } + handle.join().unwrap(); + } + + #[test] + fn step_once() { + let ctrl = DebugController::new(HashSet::new()); + ctrl.request_step(); + let c2 = ctrl.clone(); + let handle = thread::spawn(move || { + let locals = HashMap::new(); + c2.on_stmt(10, "main", &locals, "").unwrap(); + c2.set_done(true, String::new(), String::new()); + }); + let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); + assert!(matches!(snap, DebugSnapshot::Paused(p) if p.line == 10)); + ctrl.send_action(DebugAction::Continue); + let _ = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); + handle.join().unwrap(); + } + + #[test] + fn interpreter_pauses_on_breakpoint() { + use crate::interp::Interpreter; + use crate::parse::parse_source; + + let src = "# main\n\n*`x` = 1*\n> print text=`x`\n*`x` = 2*\n> print text=`x`\n"; + let module = parse_source(src).expect("parse"); + // Line 4 is first `> print` + let ctrl = DebugController::new(HashSet::from([4u32])); + let c2 = ctrl.clone(); + let handle = thread::spawn(move || { + let mut interp = Interpreter::with_capture(None, false).with_debug(c2.clone()); + let r = interp.run_module(&module); + let out = interp.captured_stdout.clone(); + match r { + Ok(_) => c2.set_done(true, out, String::new()), + Err(e) => c2.set_done(false, out, e.to_string()), + } + }); + + let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); + match snap { + DebugSnapshot::Paused(p) => { + assert_eq!(p.line, 4, "locals={:?}", p.locals); + assert!(p.locals.iter().any(|(k, v)| k == "x" && v == "1")); + } + other => panic!("expected pause on line 4, got {other:?}"), + } + ctrl.send_action(DebugAction::Continue); + let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); + match snap { + DebugSnapshot::Done { ok, stdout, stderr } => { + assert!(ok, "stderr={stderr}"); + assert!(stdout.contains('1') && stdout.contains('2'), "{stdout:?}"); + } + other => panic!("expected done, got {other:?}"), + } + handle.join().unwrap(); + } +} diff --git a/src/debug/mod.rs b/src/debug/mod.rs index 9aa1eef..3c313b1 100644 --- a/src/debug/mod.rs +++ b/src/debug/mod.rs @@ -1,6 +1,10 @@ -//! Pipeline dump helpers (see doc/design/pipeline-debug.md). +//! Pipeline dump helpers + interactive debug (see doc/design/pipeline-debug.md, view-debug). +mod ctrl; mod trace; pub use crate::lex::format_lines_dump; +pub use ctrl::{ + snapshot_json, DebugAction, DebugController, DebugPause, DebugSnapshot, +}; pub use trace::emit_trace; diff --git a/src/interp.rs b/src/interp.rs index b43b829..7e42020 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -11,11 +11,12 @@ use crate::builtin::{ builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim, builtin_type, }; -use crate::debug::emit_trace; +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::value::Value; +use std::sync::Arc; pub struct Interpreter { pub path: Option, @@ -25,6 +26,7 @@ pub struct Interpreter { current_span: Span, input: InputFeed, host: HostContext, + debug: Option>, } struct Env { @@ -62,6 +64,7 @@ impl Interpreter { current_span: Span::new(1, 1), input: InputFeed::new(false, Vec::new()), host: HostContext::for_run(path, Default::default(), Vec::new()), + debug: None, } } @@ -74,6 +77,7 @@ impl Interpreter { current_span: Span::new(1, 1), input: InputFeed::new(true, Vec::new()), host: HostContext::for_capture(path, Default::default()), + debug: None, } } @@ -87,6 +91,11 @@ impl Interpreter { self } + pub fn with_debug(mut self, debug: Arc) -> Self { + self.debug = Some(debug); + self + } + pub fn take_plots(&mut self) -> Vec { std::mem::take(&mut self.host.plots) } @@ -184,6 +193,12 @@ impl Interpreter { env: &mut Env, stmt: &Stmt, ) -> Result> { + let span = stmt_span(stmt); + self.current_span = span; + if let Some(dbg) = &self.debug { + dbg.on_stmt(span.line, &fun.name, &env.vars, &self.captured_stdout) + .map_err(|m| self.err(m))?; + } match stmt { Stmt::Assign { name, value, span, .. } => { self.current_span = *span; @@ -697,3 +712,14 @@ fn cmp_ord(l: &Value, r: &Value, f: impl Fn(std::cmp::Ordering) -> bool) -> Resu _ => bail!("comparison needs two ints/nums or two texts"), } } + +fn stmt_span(stmt: &Stmt) -> Span { + match stmt { + Stmt::Assign { span, .. } + | Stmt::Return { span, .. } + | Stmt::Call { span, .. } + | Stmt::Branch { span, .. } + | Stmt::While { span, .. } + | Stmt::ForEach { span, .. } => *span, + } +} diff --git a/src/main.rs b/src/main.rs index 522ddd7..d56369e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,11 +6,11 @@ use clap::{Parser, Subcommand, ValueEnum}; use marqdo::catalog::{write_catalog, CatalogOptions}; use marqdo::input_feed::load_stdin_file; -use marqdo::view::{serve, write_static, OutputOptions, ViewOptions}; +use marqdo::view::{serve, serve_debug, write_static, DebugOptions, OutputOptions, ViewOptions}; use marqdo::{Backend, RunOptions}; #[derive(Parser, Debug)] -#[command(name = "marqdo", version, about = "Marqdo interpreter — run, view, and catalog .mq.md")] +#[command(name = "marqdo", version, about = "Marqdo interpreter — run, view, debug, and catalog .mq.md")] struct Cli { #[command(subcommand)] command: Commands, @@ -78,6 +78,21 @@ enum Commands { #[arg(long, global = true)] no_open: bool, }, + /// Interactive debugger (tree-walk breakpoints; separate UI from `view`) + Debug { + /// Path to a `.mq.md` file or directory (default: `.`) + #[arg(value_name = "PATH")] + path: Option, + + #[arg(long, default_value = "127.0.0.1")] + host: String, + + #[arg(long, default_value_t = 7430)] + port: u16, + + #[arg(long)] + no_open: bool, + }, /// Generate OKF-compatible catalog YAML + module pages Catalog { #[arg(value_name = "PATH")] @@ -196,6 +211,20 @@ fn try_main() -> Result { Ok(0) } }, + Commands::Debug { + path, + host, + port, + no_open, + } => { + serve_debug(DebugOptions { + path: path.unwrap_or_else(|| PathBuf::from(".")), + host, + port, + open_browser: !no_open, + })?; + Ok(0) + } Commands::Catalog { path, out } | Commands::Sync { path, out } => { write_catalog(CatalogOptions { path: path.unwrap_or_else(|| PathBuf::from(".")), diff --git a/src/view/debug_api.rs b/src/view/debug_api.rs new file mode 100644 index 0000000..16b393c --- /dev/null +++ b/src/view/debug_api.rs @@ -0,0 +1,203 @@ +//! Live-view debug session APIs (tree-walk only). + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::thread; +use std::time::Duration; + +use crate::debug::{snapshot_json, DebugAction, DebugController, DebugSnapshot}; +use crate::host::HostContext; +use crate::input_feed::{effective_stdin, split_stdin_text}; +use crate::interp::Interpreter; +use crate::load::load_module; +use crate::RunOptions; + +struct Session { + ctrl: Arc, + #[allow(dead_code)] + path: PathBuf, +} + +fn sessions() -> &'static Mutex>> { + static S: OnceLock>>> = OnceLock::new(); + S.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn new_id() -> String { + use std::time::{SystemTime, UNIX_EPOCH}; + let t = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + format!("dbg-{t}") +} + +fn parse_breakpoints(v: &serde_json::Value) -> HashSet { + v.get("breakpoints") + .and_then(|b| b.as_array()) + .map(|arr| { + arr.iter() + .filter_map(|x| x.as_u64().map(|n| n as u32)) + .collect() + }) + .unwrap_or_default() +} + +pub fn api_debug_start(root: &Path, body: &str) -> serde_json::Value { + let v: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null); + let rel = v.get("path").and_then(|p| p.as_str()).unwrap_or(""); + if rel.is_empty() { + return serde_json::json!({ "ok": false, "error": "missing path" }); + } + let abs = root.join(rel.replace('/', std::path::MAIN_SEPARATOR_STR)); + if !abs.is_file() { + return serde_json::json!({ "ok": false, "error": format!("file not found: {rel}") }); + } + + let bps = parse_breakpoints(&v); + let stdin_raw = v.get("stdin").and_then(|s| s.as_str()).unwrap_or(""); + let stdin_lines = split_stdin_text(stdin_raw); + + let ctrl = DebugController::new(bps.clone()); + if bps.is_empty() { + // No breakpoints: pause on the first statement so Debug is always useful. + ctrl.request_step(); + } + ctrl.set_running(); + let id = new_id(); + let session = Arc::new(Session { + ctrl: ctrl.clone(), + path: abs.clone(), + }); + sessions().lock().unwrap().insert(id.clone(), session); + + let opts = RunOptions { + sleep_limit_ms: Some(0), + fs_root: Some(root.to_path_buf()), + ..RunOptions::default() + }; + let path_for_thread = abs; + let root_for_thread = root.to_path_buf(); + let ctrl_t = ctrl.clone(); + thread::spawn(move || { + let source = match std::fs::read_to_string(&path_for_thread) { + Ok(s) => s, + Err(e) => { + ctrl_t.set_done(false, String::new(), format!("read: {e}")); + return; + } + }; + let stdin = effective_stdin(&source, &stdin_lines); + let module = match load_module(&path_for_thread) { + Ok(m) => m, + Err(e) => { + ctrl_t.set_done(false, String::new(), e.to_string()); + return; + } + }; + let mut host = HostContext::for_capture(Some(&path_for_thread), opts.host_caps()); + host.fs_root = Some(root_for_thread); + if let Some(lim) = opts.sleep_limit_ms { + host.sleep_limit_ms = Some(lim); + } + let mut interp = Interpreter::with_capture(Some(&path_for_thread), false) + .with_stdin(stdin) + .with_host(host) + .with_debug(ctrl_t.clone()); + match interp.run_module(&module) { + Ok(_) => { + ctrl_t.set_done(true, interp.captured_stdout.clone(), String::new()); + } + Err(e) => { + let msg = e.to_string(); + if msg.contains("debug stopped") { + ctrl_t.set_done(true, interp.captured_stdout.clone(), "stopped".into()); + } else { + ctrl_t.set_done(false, interp.captured_stdout.clone(), msg); + } + } + } + }); + + let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(30)); + wrap_ok(&id, &snap) +} + +pub fn api_debug_action(body: &str, action: DebugAction) -> serde_json::Value { + let v: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null); + let id = v.get("session").and_then(|s| s.as_str()).unwrap_or(""); + let sessions = sessions().lock().unwrap(); + let Some(sess) = sessions.get(id) else { + return serde_json::json!({ "ok": false, "error": "unknown session" }); + }; + let ctrl = sess.ctrl.clone(); + drop(sessions); + + if v.get("breakpoints").map(|b| b.is_array()).unwrap_or(false) { + ctrl.set_breakpoints(parse_breakpoints(&v)); + } + + match ctrl.snapshot() { + DebugSnapshot::Done { .. } => return wrap_ok(id, &ctrl.snapshot()), + DebugSnapshot::Paused(_) => {} + other => { + return serde_json::json!({ + "ok": false, + "error": format!("session not paused (status={})", status_name(&other)), + "session": id, + }); + } + } + + ctrl.send_action(action); + let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(30)); + wrap_ok(id, &snap) +} + +pub fn api_debug_stop(body: &str) -> serde_json::Value { + let v: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null); + let id = v.get("session").and_then(|s| s.as_str()).unwrap_or(""); + let mut map = sessions().lock().unwrap(); + if let Some(sess) = map.remove(id) { + sess.ctrl.send_action(DebugAction::Stop); + return serde_json::json!({ "ok": true, "status": "stopped", "session": id }); + } + serde_json::json!({ "ok": false, "error": "unknown session" }) +} + +pub fn api_debug_set_breakpoints(body: &str) -> serde_json::Value { + let v: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null); + let id = v.get("session").and_then(|s| s.as_str()).unwrap_or(""); + let bps = parse_breakpoints(&v); + let map = sessions().lock().unwrap(); + let Some(sess) = map.get(id) else { + return serde_json::json!({ "ok": false, "error": "unknown session" }); + }; + sess.ctrl.set_breakpoints(bps.clone()); + let mut lines: Vec = bps.into_iter().collect(); + lines.sort_unstable(); + serde_json::json!({ + "ok": true, + "session": id, + "breakpoints": lines, + }) +} + +fn wrap_ok(id: &str, snap: &DebugSnapshot) -> serde_json::Value { + let mut out = snapshot_json(snap); + if let Some(obj) = out.as_object_mut() { + obj.insert("ok".into(), serde_json::Value::Bool(true)); + obj.insert("session".into(), serde_json::Value::String(id.to_string())); + } + out +} + +fn status_name(s: &DebugSnapshot) -> &'static str { + match s { + DebugSnapshot::Idle => "idle", + DebugSnapshot::Running => "running", + DebugSnapshot::Paused(_) => "paused", + DebugSnapshot::Done { .. } => "done", + } +} diff --git a/src/view/debug_page.rs b/src/view/debug_page.rs new file mode 100644 index 0000000..6893397 --- /dev/null +++ b/src/view/debug_page.rs @@ -0,0 +1,973 @@ +//! Dedicated `marqdo debug` UI — VS Code / Chrome DevTools–style layout. +//! +//! Toolbar · Structure (breakpoints) · Variables / Breakpoints / Frame · Console + +use std::path::{Path, PathBuf}; + +use crate::view::html::{escape, nav_html, LinkMode}; +use crate::view::render::{render_function_outline, render_module_structure_mode, StructureMode}; + +pub struct DebugPageModel { + #[allow(dead_code)] + pub rel_path: String, + #[allow(dead_code)] + pub source: String, + pub structure_html: String, + pub outline_html: String, + pub stdin_preset: String, + pub has_input: bool, +} + +pub fn build_debug_model(abs: &Path, rel: &str, source: &str) -> DebugPageModel { + let _ = abs; + let (structure, outline, has_input) = match crate::parse::parse_source(source) { + Ok(module) => ( + render_module_structure_mode(&module, source, StructureMode::Debug), + render_function_outline(&module), + !crate::view::render::collect_input_prompts(&module).is_empty(), + ), + Err(e) => ( + format!( + "
parse error: {}
", + escape(&e.to_string()) + ), + String::new(), + false, + ), + }; + let stdin_preset = crate::input_feed::effective_stdin(source, &[]).join("\n"); + DebugPageModel { + rel_path: rel.to_string(), + source: source.to_string(), + structure_html: structure, + outline_html: outline, + stdin_preset, + has_input, + } +} + +pub fn page_debug(files: &[PathBuf], rel: &str, vm: &DebugPageModel) -> String { + let nav = nav_html(files, Some(rel), &LinkMode::Live); + let title = Path::new(rel) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or(rel) + .trim_end_matches(".mq.md"); + + let stdin_box = if vm.has_input { + format!( + r#""#, + stdin = escape(&vm.stdin_preset), + ) + } else { + String::new() + }; + + let outline = if vm.outline_html.is_empty() { + String::new() + } else { + format!(r#"
{}
"#, vm.outline_html) + }; + + let body = format!( + r#" + +
+
+ marqdo + debug +
+
+ + + + +
+
Idle — set breakpoints, then Start · drag edges to resize panes
+
+
+
+ +
+
+
+

{title}

+

{rel}

+ {stdin} +
+
+
+

Structure gutter = breakpoint

+
{structure}
+
+ {outline} +
+
+
+ +
+
+
+

Debug Console

+
(idle)
+
+
+"#, + path_js = escape_js_string(rel), + nav = nav, + title = escape(title), + rel = escape(rel), + stdin = stdin_box, + structure = vm.structure_html, + outline = outline, + ); + + layout_debug(rel, &body) +} + +fn escape_js_string(s: &str) -> String { + let mut out = String::from('"'); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +fn layout_debug(title: &str, main: &str) -> String { + format!( + r##" + + + + +debug · {title} · marqdo + + + +{main} + + + +"##, + title = escape(title), + css = debug_css(), + main = main, + js = debug_js(), + ) +} + +fn debug_css() -> &'static str { + r#" +:root { + --bg: #1e1e1e; + --panel: #252526; + --ink: #d4d4d4; + --muted: #858585; + --line: #3c3c3c; + --accent: #0e639c; + --accent-hover: #1177bb; + --current: #264f78; + --bp: #e51400; + --ok: #4ec9b0; + --nav-w: 168px; + --side-w: 220px; + --console-h: 120px; + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; +} +* { box-sizing: border-box; } +html, body { margin: 0; height: 100%; } +.dbg-body { + font-family: var(--sans); + font-size: 12.5px; + color: var(--ink); + background: var(--bg); + display: flex; + flex-direction: column; + height: 100vh; + overflow: hidden; +} +.dbg-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem 0.85rem; + padding: 0.35rem 0.65rem; + background: #333; + border-bottom: 1px solid #000; + flex-shrink: 0; +} +.dbg-brand { display: flex; align-items: baseline; gap: 0.35rem; } +.dbg-mark { font-weight: 700; letter-spacing: -0.02em; color: #fff; font-size: 0.9rem; } +.dbg-mode { + font-size: 0.65rem; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--ok); + font-weight: 600; +} +.dbg-actions { display: flex; gap: 0.3rem; } +.dbg-btn { + font: 0.72rem/1 var(--sans); + padding: 0.32rem 0.6rem; + border: 1px solid #555; + border-radius: 3px; + background: #3c3c3c; + color: #fff; + cursor: pointer; +} +.dbg-btn:hover:not(:disabled) { background: #505050; } +.dbg-btn:disabled { opacity: 0.4; cursor: default; } +.dbg-btn.primary { background: var(--accent); border-color: var(--accent); } +.dbg-btn.primary:hover:not(:disabled) { background: var(--accent-hover); } +.dbg-btn.danger { background: #5a1d1d; border-color: #7a2d2d; } +.dbg-status { color: var(--muted); font-family: var(--mono); font-size: 0.7rem; flex: 1; min-width: 8rem; } +.dbg-work { + flex: 1; + display: flex; + flex-direction: column; + min-height: 0; + overflow: hidden; +} +.dbg-shell { + flex: 1; + display: flex; + min-height: 0; + overflow: hidden; +} +.dbg-nav, .dbg-side { + flex-shrink: 0; + background: var(--panel); + overflow: auto; + padding: 0.35rem 0.3rem 0.6rem; +} +.dbg-nav { width: var(--nav-w); border-right: none; } +.dbg-side { width: var(--side-w); } +.dbg-split-v { + flex: 0 0 4px; + background: var(--line); + cursor: col-resize; + position: relative; + z-index: 2; +} +.dbg-split-v:hover, .dbg-split-v.dragging { background: var(--accent); } +.dbg-split-h { + flex: 0 0 5px; + background: var(--line); + cursor: row-resize; + position: relative; + z-index: 2; +} +.dbg-split-h:hover, .dbg-split-h.dragging { background: var(--accent); } +.dbg-nav h2, .dbg-side h2, .dbg-structure-pane h2, .dbg-console h2 { + margin: 0.2rem 0.35rem 0.3rem; + font-size: 0.6rem; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--muted); + font-weight: 600; +} +.dbg-nav ul { list-style: none; margin: 0; padding: 0; } +.dbg-nav a.file { + display: block; + padding: 0.22rem 0.4rem; + border-radius: 3px; + color: var(--ink); + text-decoration: none; + font-family: var(--mono); + font-size: 0.68rem; + line-height: 1.25; +} +.dbg-nav a.file:hover { background: #2a2d2e; } +.dbg-nav a.file.active { background: #094771; color: #fff; } +.dbg-nav .folder { margin: 0.2rem 0; } +.dbg-nav .folder > summary { + color: var(--muted); + cursor: pointer; + font-size: 0.68rem; + padding: 0.15rem 0.35rem; + line-height: 1.25; +} +.dbg-main { + flex: 1; + display: flex; + flex-direction: column; + min-width: 0; + overflow: hidden; + background: var(--bg); +} +.dbg-main-head { + padding: 0.4rem 0.75rem 0.3rem; + border-bottom: 1px solid var(--line); + flex-shrink: 0; +} +.dbg-main-head h1 { margin: 0; font-size: 0.95rem; font-weight: 600; color: #fff; line-height: 1.2; } +.dbg-main-head .meta { + margin: 0.1rem 0 0; + color: var(--muted); + font-family: var(--mono); + font-size: 0.65rem; + line-height: 1.2; +} +.dbg-stdin-label { + display: block; + margin-top: 0.3rem; + color: var(--muted); + font-size: 0.65rem; +} +.dbg-stdin-label textarea { + display: block; + width: 100%; + margin-top: 0.15rem; + background: #1e1e1e; + border: 1px solid var(--line); + color: var(--ink); + font-family: var(--mono); + font-size: 0.7rem; + border-radius: 3px; + padding: 0.25rem 0.35rem; + line-height: 1.3; + max-height: 4rem; +} +.dbg-center { + flex: 1; + display: flex; + min-height: 0; + overflow: hidden; +} +.dbg-structure-pane { + flex: 1; + overflow: auto; + padding: 0.35rem 0.55rem 0.6rem; + min-width: 0; +} +.dbg-outline { + flex: 0 0 9.5rem; + border-left: 1px solid var(--line); + overflow: auto; + padding: 0.35rem; + background: var(--panel); +} +.outline-panel { background: transparent; border: none; padding: 0; box-shadow: none; } +.fn-search { + width: 100%; + margin-bottom: 0.3rem; + padding: 0.25rem 0.35rem; + background: #1e1e1e; + border: 1px solid var(--line); + color: var(--ink); + border-radius: 3px; + font-size: 0.68rem; +} +.outline-tree, .outline-tree ul { list-style: none; margin: 0; padding: 0; } +.outline-tree ul { padding-left: 0.5rem; border-left: 1px solid var(--line); } +.outline-item { margin: 0.05rem 0; font-size: 0.68rem; line-height: 1.25; } +.outline-item.hidden { display: none; } +.outline-item a { color: #9cdcfe; text-decoration: none; font-family: var(--mono); } +.outline-item .ol-meta { color: var(--muted); margin-left: 0.15rem; font-size: 0.6rem; } + +/* Compact structure — dense like an editor, not a docs card list */ +.structure.debug-surface { + background: #1e1e1e; + border: 1px solid var(--line); + border-radius: 3px; + padding: 0; + line-height: 1.25; +} +.structure.debug-surface .card { + border: none; + border-bottom: 1px solid #2d2d2d; + border-radius: 0; + padding: 0.18rem 0.45rem; + margin: 0; + background: transparent; + color: var(--ink); + line-height: 1.25; +} +.structure.debug-surface .fun-card, +.structure.debug-surface .call-card, +.structure.debug-surface .branch-card, +.structure.debug-surface .loop-card, +.structure.debug-surface .ret-card { + border-left: 2px solid #555; + padding-left: 0.4rem; +} +.structure.debug-surface .badge { + background: transparent; + border: none; + color: #808080; + font-size: 0.58rem; + padding: 0 0.2rem 0 0; + margin-right: 0.25rem; +} +.structure.debug-surface .chip { + background: #2d2d2d; + color: #9cdcfe; + font-size: 0.62rem; + padding: 0.05rem 0.28rem; + margin: 0.05rem 0.1rem 0 0; + border-radius: 3px; +} +.structure.debug-surface .params { margin: 0.1rem 0 0; } +.structure.debug-surface code.expr { + color: #dcdcaa; + font-family: var(--mono); + font-size: 0.72rem; + line-height: 1.25; +} +.structure.debug-surface strong { font-size: 0.78rem; font-weight: 600; color: #fff; } +.structure.debug-surface .comment-card { + border-left: 2px solid #3a4a30; + background: #1a1f18; + padding: 0.1rem 0.4rem; +} +.structure.debug-surface .comment-card .badge { display: none; } +.structure.debug-surface .comment-text { + color: #6a9955; + font-size: 0.68rem; + line-height: 1.3; + max-height: 2.6em; + overflow: hidden; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; +} +.structure.debug-surface .comment-text p { + margin: 0; + display: inline; +} +.structure.debug-surface .comment-text p + p::before { content: " · "; color: #4a6a40; } +.structure.debug-surface .nested { + margin: 0.08rem 0 0.08rem 0.15rem; + padding-left: 0.4rem; + border-left: 1px solid #333; +} +.structure.debug-surface .arm { + margin: 0.12rem 0; + padding: 0.15rem 0.35rem; + background: #252525; + border-radius: 2px; +} +/* Foreign code cards (Run → /api/foreign-run) */ +.structure.debug-surface .code-card { + padding: 0 !important; + overflow: hidden; +} +.structure.debug-surface .code-head { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.35rem 0.5rem; + padding: 0.3rem 0.45rem; + border-bottom: 1px solid #2d2d2d; + background: #252526; +} +.structure.debug-surface .code-lang { + font: 0.62rem/1 var(--mono); + color: var(--muted); + text-transform: lowercase; +} +.structure.debug-surface .code-actions { + margin-left: auto; + display: flex; + align-items: center; + gap: 0.3rem; +} +.structure.debug-surface .code-cmd { + min-width: 6rem; + max-width: 12rem; + padding: 0.2rem 0.35rem; + border: 1px solid var(--line); + border-radius: 3px; + font: 0.68rem/1.2 var(--mono); + color: var(--ink); + background: #1e1e1e; +} +.structure.debug-surface .code-run { + padding: 0.2rem 0.55rem; + border: none; + border-radius: 3px; + background: var(--accent); + color: #fff; + font: 0.68rem/1.2 var(--sans); + font-weight: 600; + cursor: pointer; +} +.structure.debug-surface .code-run:disabled { opacity: 0.45; cursor: not-allowed; } +.structure.debug-surface .code-body { + margin: 0; + padding: 0.4rem 0.55rem; + overflow: auto; + max-height: 12rem; + background: #1e1e1e; + color: #d4d4d4; + font: 0.7rem/1.35 var(--mono); + white-space: pre; +} +.structure.debug-surface .code-body code { + font: inherit; + background: none; + padding: 0; + color: inherit; +} +.structure.debug-surface .code-out { + margin: 0; + padding: 0.4rem 0.55rem; + border-top: 1px solid #2d2d2d; + background: #1a1a1a; + font: 0.7rem/1.35 var(--mono); + white-space: pre-wrap; + word-break: break-word; + color: #b5cea8; +} +.structure.debug-surface .code-out.err { color: #f48771; background: #2a1515; } +.structure.debug-surface .code-out[hidden] { display: none !important; } +.stmt { + display: grid; + grid-template-columns: 1rem 1fr; + align-items: stretch; +} +.stmt .bp-gutter { + border: 0; + background: transparent; + cursor: pointer; + padding: 0; + display: flex; + align-items: flex-start; + justify-content: center; + padding-top: 0.28rem; +} +.stmt .bp-gutter:hover { background: #3a1d1d; } +.stmt.bp .bp-gutter::after { + content: ""; + width: 0.42rem; + height: 0.42rem; + border-radius: 50%; + background: var(--bp); + display: block; +} +.stmt.current { + background: var(--current); + box-shadow: inset 2px 0 0 #75beff; +} +.stmt-body > .card { border-bottom: 1px solid #2d2d2d; } +.dbg-panel { + margin-bottom: 0.45rem; + padding-bottom: 0.35rem; + border-bottom: 1px solid var(--line); +} +.dbg-vars, .dbg-frame { + font-family: var(--mono); + font-size: 0.7rem; + padding: 0.15rem 0.4rem; + white-space: pre-wrap; + color: #b5cea8; + min-height: 1.5rem; + line-height: 1.3; +} +.dbg-bps { list-style: none; margin: 0; padding: 0 0.35rem; } +.dbg-bps li { + font-family: var(--mono); + font-size: 0.68rem; + padding: 0.12rem 0; + color: #f48771; + cursor: pointer; + line-height: 1.25; +} +.dbg-bps li.muted { color: var(--muted); cursor: default; } +.dbg-console { + flex-shrink: 0; + height: var(--console-h); + border-top: none; + background: var(--panel); + display: flex; + flex-direction: column; + min-height: 48px; + max-height: 55vh; + overflow: hidden; +} +.dbg-out { + margin: 0; + padding: 0.3rem 0.55rem 0.45rem; + overflow: auto; + font-family: var(--mono); + font-size: 0.72rem; + color: var(--ink); + white-space: pre-wrap; + flex: 1; + line-height: 1.35; +} +.hint { color: var(--muted); font-weight: 400; text-transform: none; letter-spacing: 0; font-size: 0.62rem; } +.err { color: #f48771; padding: 0.5rem; } +body.resizing-col { cursor: col-resize; user-select: none; } +body.resizing-row { cursor: row-resize; user-select: none; } +@media (max-width: 900px) { + .dbg-shell { flex-wrap: wrap; } + .dbg-nav, .dbg-side { width: 100% !important; max-height: 120px; } + .dbg-split-v { display: none; } + .dbg-outline { display: none; } +} +"# +} + +fn debug_js() -> &'static str { + r#" +(function () { + function initResizers() { + var root = document.documentElement; + var KEY = "marqdo.debug.layout"; + try { + var saved = JSON.parse(localStorage.getItem(KEY) || "{}"); + if (saved.nav) root.style.setProperty("--nav-w", saved.nav + "px"); + if (saved.side) root.style.setProperty("--side-w", saved.side + "px"); + if (saved.console) root.style.setProperty("--console-h", saved.console + "px"); + } catch (e) {} + function persist() { + var nav = parseInt(getComputedStyle(root).getPropertyValue("--nav-w"), 10) || 168; + var side = parseInt(getComputedStyle(root).getPropertyValue("--side-w"), 10) || 220; + var cons = parseInt(getComputedStyle(root).getPropertyValue("--console-h"), 10) || 120; + try { localStorage.setItem(KEY, JSON.stringify({ nav: nav, side: side, console: cons })); } catch (e) {} + } + function bindCol(splitId, prop, min, max, fromRight) { + var el = document.getElementById(splitId); + if (!el) return; + el.addEventListener("mousedown", function (ev) { + ev.preventDefault(); + el.classList.add("dragging"); + document.body.classList.add("resizing-col"); + function move(e) { + var x = e.clientX; + var w; + if (fromRight) { + w = Math.min(max, Math.max(min, window.innerWidth - x)); + } else { + w = Math.min(max, Math.max(min, x)); + } + root.style.setProperty(prop, w + "px"); + } + function up() { + el.classList.remove("dragging"); + document.body.classList.remove("resizing-col"); + document.removeEventListener("mousemove", move); + document.removeEventListener("mouseup", up); + persist(); + } + document.addEventListener("mousemove", move); + document.addEventListener("mouseup", up); + }); + } + function bindRow(splitId, prop, min, max) { + var el = document.getElementById(splitId); + if (!el) return; + el.addEventListener("mousedown", function (ev) { + ev.preventDefault(); + el.classList.add("dragging"); + document.body.classList.add("resizing-row"); + function move(e) { + var h = Math.min(max, Math.max(min, window.innerHeight - e.clientY)); + root.style.setProperty(prop, h + "px"); + } + function up() { + el.classList.remove("dragging"); + document.body.classList.remove("resizing-row"); + document.removeEventListener("mousemove", move); + document.removeEventListener("mouseup", up); + persist(); + } + document.addEventListener("mousemove", move); + document.addEventListener("mouseup", up); + }); + } + bindCol("split-nav", "--nav-w", 120, 360, false); + bindCol("split-side", "--side-w", 140, 420, true); + bindRow("split-console", "--console-h", 48, Math.floor(window.innerHeight * 0.55)); + } + initResizers(); + + var structure = document.getElementById("structure"); + var startBtn = document.getElementById("dbg-start"); + var contBtn = document.getElementById("dbg-continue"); + var stepBtn = document.getElementById("dbg-step"); + var stopBtn = document.getElementById("dbg-stop"); + var statusEl = document.getElementById("dbg-status"); + var localsEl = document.getElementById("dbg-locals"); + var stdoutEl = document.getElementById("dbg-stdout"); + var frameEl = document.getElementById("dbg-frame"); + var bpsEl = document.getElementById("dbg-bps"); + if (!structure || !startBtn) return; + + var bps = new Set(); + var session = null; + var path = window.MARQDO_FILE_PATH || ""; + + function bpList() { + return Array.from(bps).sort(function (a, b) { return a - b; }); + } + function setStatus(t) { if (statusEl) statusEl.textContent = t; } + function setPausedUi(paused) { + startBtn.disabled = !!session; + contBtn.disabled = !paused; + stepBtn.disabled = !paused; + stopBtn.disabled = !session; + } + function clearCurrent() { + structure.querySelectorAll(".stmt.current").forEach(function (el) { + el.classList.remove("current"); + }); + } + function renderBps() { + if (!bpsEl) return; + var list = bpList(); + if (!list.length) { + bpsEl.innerHTML = '
  • none
  • '; + return; + } + var html = ""; + list.forEach(function (n) { + html += '
  • line ' + n + '
  • '; + }); + bpsEl.innerHTML = html; + bpsEl.querySelectorAll("li[data-line]").forEach(function (li) { + li.addEventListener("click", function () { + var line = li.getAttribute("data-line"); + var row = structure.querySelector('.stmt[data-line="' + line + '"]'); + if (row) row.scrollIntoView({ block: "nearest", behavior: "smooth" }); + }); + }); + } + function showLocals(obj) { + if (!localsEl) return; + if (!obj || typeof obj !== "object") { + localsEl.textContent = "(none)"; + return; + } + var keys = Object.keys(obj).sort(); + if (!keys.length) { + localsEl.textContent = "(none)"; + return; + } + localsEl.textContent = keys.map(function (k) { + return k + " = " + obj[k]; + }).join("\n"); + } + function applySnap(data) { + if (!data) return; + if (data.session) session = data.session; + clearCurrent(); + if (data.status === "paused") { + setStatus("Paused at line " + data.line + " · " + (data.fun || "")); + var row = structure.querySelector('.stmt[data-line="' + data.line + '"]'); + if (row) { + row.classList.add("current"); + row.scrollIntoView({ block: "nearest", behavior: "smooth" }); + } + showLocals(data.locals); + if (frameEl) frameEl.textContent = data.fun || "(unknown)"; + if (stdoutEl) stdoutEl.textContent = data.stdout === "" ? "(empty)" : data.stdout; + setPausedUi(true); + } else if (data.status === "done") { + setStatus(data.ok === false ? "Terminated with error" : "Finished"); + showLocals(null); + if (frameEl) frameEl.textContent = "(done)"; + if (stdoutEl) { + var t = data.stdout || ""; + if (data.stderr) t = (t ? t + "\n" : "") + data.stderr; + stdoutEl.textContent = t || "(empty)"; + } + session = null; + setPausedUi(false); + startBtn.disabled = false; + stopBtn.disabled = true; + } else if (data.status === "running") { + setStatus("Running…"); + setPausedUi(false); + stopBtn.disabled = !session; + } else { + setStatus(data.status || "Idle"); + setPausedUi(false); + } + if (data.ok === false && data.error) setStatus(data.error); + } + function post(url, body) { + return fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body || {}) + }).then(function (r) { return r.json(); }); + } + function stdinText() { + var ta = document.getElementById("stdin"); + return ta ? ta.value : ""; + } + + structure.querySelectorAll(".stmt > .bp-gutter").forEach(function (btn) { + btn.addEventListener("click", function (ev) { + ev.preventDefault(); + ev.stopPropagation(); + var row = btn.closest(".stmt"); + if (!row) return; + var line = parseInt(row.getAttribute("data-line"), 10); + if (bps.has(line)) { + bps.delete(line); + row.classList.remove("bp"); + } else { + bps.add(line); + row.classList.add("bp"); + } + renderBps(); + if (session) { + post("/api/debug/breakpoints", { + session: session, + breakpoints: bpList() + }).catch(function () {}); + } + }); + }); + + startBtn.addEventListener("click", function () { + startBtn.disabled = true; + setStatus("Starting…"); + clearCurrent(); + post("/api/debug/start", { + path: path, + breakpoints: bpList(), + stdin: stdinText() + }).then(applySnap).catch(function (e) { + setStatus(String(e)); + startBtn.disabled = false; + session = null; + }); + }); + contBtn.addEventListener("click", function () { + if (!session) return; + setStatus("Continue…"); + setPausedUi(false); + post("/api/debug/continue", { + session: session, + breakpoints: bpList() + }).then(applySnap).catch(function (e) { setStatus(String(e)); }); + }); + stepBtn.addEventListener("click", function () { + if (!session) return; + setStatus("Step…"); + setPausedUi(false); + post("/api/debug/step", { + session: session, + breakpoints: bpList() + }).then(applySnap).catch(function (e) { setStatus(String(e)); }); + }); + stopBtn.addEventListener("click", function () { + if (!session) return; + post("/api/debug/stop", { session: session }).then(function () { + session = null; + clearCurrent(); + setStatus("Stopped"); + setPausedUi(false); + startBtn.disabled = false; + stopBtn.disabled = true; + }).catch(function (e) { setStatus(String(e)); }); + }); + + document.addEventListener("keydown", function (ev) { + if (ev.key === "F5" && !contBtn.disabled) { + ev.preventDefault(); + contBtn.click(); + } else if (ev.key === "F10" && !stepBtn.disabled) { + ev.preventDefault(); + stepBtn.click(); + } + }); + + var input = document.getElementById("fn-search"); + var tree = document.querySelector(".outline-tree"); + if (input && tree) { + input.addEventListener("input", function () { + var q = (input.value || "").trim().toLowerCase(); + tree.querySelectorAll(".outline-item").forEach(function (li) { + if (!q) { li.classList.remove("hidden"); return; } + var name = (li.getAttribute("data-fn") || "").toLowerCase(); + var fpath = (li.getAttribute("data-fn-path") || "").toLowerCase(); + var selfMatch = name.indexOf(q) !== -1 || fpath.indexOf(q) !== -1; + var childMatch = false; + li.querySelectorAll(".outline-item").forEach(function (c) { + var cn = (c.getAttribute("data-fn") || "").toLowerCase(); + var cp = (c.getAttribute("data-fn-path") || "").toLowerCase(); + if (cn.indexOf(q) !== -1 || cp.indexOf(q) !== -1) childMatch = true; + }); + li.classList.toggle("hidden", !(selfMatch || childMatch)); + }); + }); + } + + renderBps(); + setPausedUi(false); + + // Foreign code cards (same API as view) + document.querySelectorAll(".code-card").forEach(function (card) { + var btn = card.querySelector(".code-run"); + var cmd = card.querySelector(".code-cmd"); + var out = card.querySelector(".code-out"); + var body = card.querySelector(".code-body code"); + if (!btn || !out || !body) return; + btn.addEventListener("click", function () { + btn.disabled = true; + out.hidden = false; + out.classList.remove("err"); + out.textContent = "Running…"; + fetch("/api/foreign-run", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + lang: card.getAttribute("data-lang") || "python", + source: body.textContent, + cmd: cmd ? cmd.value : "" + }) + }) + .then(function (r) { return r.json(); }) + .then(function (data) { + if (data.ok) { + out.classList.remove("err"); + out.textContent = data.stdout === "" ? "(no stdout)" : data.stdout; + } else { + out.classList.add("err"); + out.textContent = data.error || "foreign run failed"; + } + }) + .catch(function (e) { + out.classList.add("err"); + out.textContent = String(e); + }) + .finally(function () { btn.disabled = false; }); + }); + }); +})(); +"# +} diff --git a/src/view/html.rs b/src/view/html.rs index eb62604..68a9720 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -114,7 +114,7 @@ a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } display: grid; grid-template-columns: 280px minmax(0, 1fr); min-height: 100vh; - max-width: 1400px; + max-width: 1680px; margin: 0 auto; } .nav { @@ -219,10 +219,10 @@ a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } background: var(--bg); } main.panel { - padding: 2.25rem 2.5rem 4rem; - margin: 0 auto; + padding: 2rem 2.25rem 3.5rem; + margin: 0; width: 100%; - max-width: 58rem; + max-width: 76rem; } h1.page { font-size: clamp(1.75rem, 2.4vw, 2.35rem); @@ -377,6 +377,77 @@ section.block > h2 { line-height: 1.55; box-shadow: 0 1px 0 rgba(0,0,0,0.02); } +.stmt { display: block; } +.stmt-body { min-width: 0; } +.stmt-body > .card { border-bottom: 1px solid var(--line); } +.structure > .stmt:last-child > .stmt-body > .card, +.structure > .card:last-child { border-bottom: none; } +.struct-wrap { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(9.5rem, 12.5rem); + gap: 0.75rem; + align-items: start; +} +@media (max-width: 960px) { + .struct-wrap { grid-template-columns: 1fr; } + .outline-panel { position: static; } +} +.outline-panel { + position: sticky; + top: 1rem; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 0.55rem 0.6rem 0.65rem; + box-shadow: 0 1px 0 rgba(0,0,0,0.02); +} +.fn-search { + width: 100%; + box-sizing: border-box; + margin: 0 0 0.45rem; + padding: 0.4rem 0.5rem; + border: 1px solid var(--line); + border-radius: 8px; + font: 0.78rem/1.2 var(--sans); + color: var(--ink); + background: #fff; +} +.fn-search:focus { + outline: 2px solid var(--focus); + outline-offset: 1px; +} +.outline-tree, .outline-tree ul { + list-style: none; + margin: 0; + padding: 0; +} +.outline-tree ul { + padding-left: 0.7rem; + border-left: 1px solid var(--line); + margin-left: 0.25rem; +} +.outline-item { + margin: 0.12rem 0; + font-size: 0.78rem; + line-height: 1.35; +} +.outline-item.hidden { display: none; } +.outline-item > a { + font-family: var(--mono); + font-size: 0.76rem; + color: var(--ink); +} +.outline-item > a:hover { opacity: 1; text-decoration: underline; } +.outline-item .ol-meta { + color: var(--muted); + font-size: 0.66rem; + margin-left: 0.2rem; +} +.fun-card:target { + outline: 2px solid var(--focus); + outline-offset: 2px; + background: #f0f7ff; +} .out.ok { background: var(--ok-bg); } .out.fail { background: var(--fail-bg); @@ -549,7 +620,7 @@ code.expr { @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } @media (max-width: 900px) { .shell { grid-template-columns: 240px minmax(0, 1fr); } - main.panel { max-width: 48rem; padding: 1.75rem 1.5rem 3rem; } + main.panel { max-width: 64rem; padding: 1.75rem 1.5rem 3rem; } } @media (max-width: 800px) { .topbar { display: flex; } @@ -681,9 +752,51 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { }}); }} if (document.readyState === "loading") {{ - document.addEventListener("DOMContentLoaded", initForeignCards); + document.addEventListener("DOMContentLoaded", function () {{ + initForeignCards(); + initOutlineSearch(); + }}); }} else {{ initForeignCards(); + initOutlineSearch(); + }} + + function initOutlineSearch() {{ + var input = document.getElementById("fn-search"); + var tree = document.querySelector(".outline-tree"); + if (!input || !tree) return; + function applyFilter() {{ + var q = (input.value || "").trim().toLowerCase(); + var items = tree.querySelectorAll(".outline-item"); + items.forEach(function (li) {{ + if (!q) {{ + li.classList.remove("hidden"); + return; + }} + var name = (li.getAttribute("data-fn") || "").toLowerCase(); + var path = (li.getAttribute("data-fn-path") || "").toLowerCase(); + var selfMatch = name.indexOf(q) !== -1 || path.indexOf(q) !== -1; + var childMatch = false; + li.querySelectorAll(".outline-item").forEach(function (c) {{ + var cn = (c.getAttribute("data-fn") || "").toLowerCase(); + var cp = (c.getAttribute("data-fn-path") || "").toLowerCase(); + if (cn.indexOf(q) !== -1 || cp.indexOf(q) !== -1) childMatch = true; + }}); + li.classList.toggle("hidden", !(selfMatch || childMatch)); + }}); + }} + input.addEventListener("input", applyFilter); + tree.querySelectorAll("a[href^='#fn-']").forEach(function (a) {{ + a.addEventListener("click", function (ev) {{ + var id = (a.getAttribute("href") || "").slice(1); + var el = id ? document.getElementById(id) : null; + if (el) {{ + ev.preventDefault(); + el.scrollIntoView({{ behavior: "smooth", block: "start" }}); + history.replaceState(null, "", "#" + id); + }} + }}); + }}); }} }})(); @@ -932,14 +1045,37 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM LinkMode::Live => "true", LinkMode::Static { .. } => "false", }; + let outline_block = if vm.outline_html.is_empty() { + String::new() + } else { + vm.outline_html.clone() + }; + let structure_block = if outline_block.is_empty() { + format!( + r#"
    {structure}
    "#, + structure = vm.structure_html + ) + } else { + format!( + r#"
    +
    {structure}
    + {outline} +
    "#, + structure = vm.structure_html, + outline = outline_block, + ) + }; let main = format!( r#" - +

    {title}{status_label}

    {rel}

    Structure

    -
    {structure}
    + {structure_block}

    Execution

    @@ -953,11 +1089,12 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
    "#, live = live_flag, + path_js = escape_js_string(rel), title = escape(title), status = status, status_label = status_label, rel = escape(rel), - structure = vm.structure_html, + structure_block = structure_block, stdin_panel = stdin_panel, out = out_text, plots = plots_html, @@ -965,3 +1102,21 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM ); layout(rel, &nav, &main) } + +fn escape_js_string(s: &str) -> String { + let mut out = String::from('"'); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\u{2028}' => out.push_str("\\u2028"), + '\u{2029}' => out.push_str("\\u2029"), + c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} diff --git a/src/view/mod.rs b/src/view/mod.rs index 33ebd60..2f0fcc4 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -1,5 +1,8 @@ //! `marqdo view` — local HTML browser for `.mq.md` structure + output. +//! `marqdo debug` — separate debugger host (tree-walk breakpoints). +mod debug_api; +mod debug_page; mod html; mod output; mod render; @@ -15,6 +18,7 @@ use anyhow::{bail, Context, Result}; use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; use crate::input_feed::{effective_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::render::{collect_input_prompts, render_module_structure, FileViewModel}; use crate::{run_file_capture, RunOptions}; @@ -26,6 +30,14 @@ pub struct ViewOptions { pub open_browser: bool, } +/// Options for `marqdo debug` (separate from view). +pub struct DebugOptions { + pub path: PathBuf, + pub host: String, + pub port: u16, + pub open_browser: bool, +} + pub(crate) struct ViewRoot { pub root: PathBuf, pub only_file: Option, @@ -56,6 +68,30 @@ pub fn serve(opts: ViewOptions) -> Result<()> { Ok(()) } +/// Live debugger UI (distinct from `view`). Default port usually 7430. +pub fn serve_debug(opts: DebugOptions) -> Result<()> { + let root_info = build_root(&opts.path)?; + let addr: SocketAddr = format!("{}:{}", opts.host, opts.port) + .parse() + .context("invalid host/port")?; + let server = Server::http(addr).map_err(|e| anyhow::anyhow!("listen {addr}: {e}"))?; + let url = format!("http://{}:{}/", opts.host, opts.port); + eprintln!("marqdo debug: {url}"); + eprintln!("root: {}", root_info.root.display()); + eprintln!("{} .mq.md file(s). Ctrl+C to stop.", root_info.files.len()); + + if opts.open_browser { + let _ = open_url(&url); + } + + for request in server.incoming_requests() { + if let Err(err) = handle_debug(&root_info, request) { + eprintln!("debug request error: {err:#}"); + } + } + Ok(()) +} + pub(crate) fn build_root(path: &Path) -> Result { let path = if path.exists() { path.canonicalize().unwrap_or_else(|_| path.to_path_buf()) @@ -137,7 +173,6 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> { let (path_part, query) = split_url(&url); match path_part { "/" | "/index.html" => { - // Default: open the first file in the folder (sorted), no welcome pick screen. if let Some(first) = root.files.first() { let rel = first.to_string_lossy().replace('\\', "/"); let resolved = resolve_rel(root, &rel)?; @@ -170,6 +205,85 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> { } } +fn handle_debug(root: &ViewRoot, request: Request) -> Result<()> { + let url = request.url().to_string(); + let method = request.method().clone(); + + if method == Method::Post { + let (path_part, _) = split_url(&url); + match path_part { + "/api/foreign-run" => return api_foreign_run(root, request), + "/api/debug/start" => { + return api_debug_post(request, |body| { + debug_api::api_debug_start(&root.root, body) + }) + } + "/api/debug/continue" => { + return api_debug_post(request, |body| { + debug_api::api_debug_action(body, crate::debug::DebugAction::Continue) + }) + } + "/api/debug/step" => { + return api_debug_post(request, |body| { + debug_api::api_debug_action(body, crate::debug::DebugAction::Step) + }) + } + "/api/debug/stop" => { + return api_debug_post(request, |body| debug_api::api_debug_stop(body)) + } + "/api/debug/breakpoints" => { + return api_debug_post(request, |body| { + debug_api::api_debug_set_breakpoints(body) + }) + } + _ => { + let resp = + Response::from_string("method not allowed").with_status_code(StatusCode(405)); + let _ = request.respond(resp); + return Ok(()); + } + } + } + + if method != Method::Get { + let resp = Response::from_string("method not allowed").with_status_code(StatusCode(405)); + let _ = request.respond(resp); + return Ok(()); + } + + let (path_part, query) = split_url(&url); + match path_part { + "/" | "/index.html" => { + if let Some(first) = root.files.first() { + let rel = first.to_string_lossy().replace('\\', "/"); + let resolved = resolve_rel(root, &rel)?; + let source = fs::read_to_string(&resolved) + .with_context(|| format!("read {}", resolved.display()))?; + let vm = build_debug_model(&resolved, &rel, &source); + let body = page_debug(&root.files, &rel, &vm); + respond_html(request, body) + } else { + let body = page_index(&root.files, None, &LinkMode::Live); + respond_html(request, body) + } + } + "/file" => { + let rel = query_param(query, "path").unwrap_or_default(); + let resolved = resolve_rel(root, &rel)?; + let source = fs::read_to_string(&resolved) + .with_context(|| format!("read {}", resolved.display()))?; + let vm = build_debug_model(&resolved, &rel, &source); + let body = page_debug(&root.files, &rel, &vm); + respond_html(request, body) + } + _ => { + let resp = Response::from_string("not found").with_status_code(StatusCode(404)); + let _ = request.respond(resp); + Ok(()) + } + } +} + pub(crate) fn build_file_view( root: &ViewRoot, abs: &Path, @@ -179,9 +293,10 @@ pub(crate) fn build_file_view( ) -> Result { let source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?; // Structure shows this file only — do not merge imported lib bodies into the tree. - let (structure, input_prompts) = match crate::parse::parse_source(&source) { + let (structure, outline, input_prompts) = match crate::parse::parse_source(&source) { Ok(module) => ( render_module_structure(&module, &source), + crate::view::render::render_function_outline(&module), collect_input_prompts(&module), ), Err(e) => ( @@ -189,6 +304,7 @@ pub(crate) fn build_file_view( "
    parse/load error: {}
    ", escape(&tidy_user_error(&format!("{e:#}"), abs, rel)) ), + String::new(), Vec::new(), ), }; @@ -217,6 +333,7 @@ pub(crate) fn build_file_view( rel_path: rel.to_string(), source, structure_html: structure, + outline_html: outline, stdout, stderr, ok, @@ -349,6 +466,16 @@ fn escape_json(s: &str) -> String { s.replace('\\', "\\\\").replace('"', "\\\"") } +fn api_debug_post( + mut request: Request, + f: impl FnOnce(&str) -> serde_json::Value, +) -> Result<()> { + let mut body = Vec::new(); + std::io::Read::read_to_end(&mut request.as_reader(), &mut body)?; + let body = String::from_utf8_lossy(&body); + respond_json(request, f(&body).to_string()) +} + fn api_foreign_run(root: &ViewRoot, mut request: Request) -> Result<()> { let mut body = Vec::new(); std::io::Read::read_to_end(&mut request.as_reader(), &mut body)?; diff --git a/src/view/render.rs b/src/view/render.rs index 9382cf7..d514afd 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -10,11 +10,20 @@ use crate::lex::{classify_source, ClassifiedLine, LineKind}; use crate::view::html::escape; use pulldown_cmark::{html, Options, Parser}; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StructureMode { + /// Documentation browse: fun anchors, no breakpoint gutters + Browse, + /// Debugger: breakpoint gutters on statements + Debug, +} + pub struct FileViewModel { #[allow(dead_code)] pub rel_path: String, pub source: String, pub structure_html: String, + pub outline_html: String, pub stdout: String, pub stderr: String, pub ok: bool, @@ -140,6 +149,14 @@ fn prompt_expr_text(expr: &Expr) -> String { } pub fn render_module_structure(module: &Module, source: &str) -> String { + render_module_structure_mode(module, source, StructureMode::Browse) +} + +pub fn render_module_structure_mode( + module: &Module, + source: &str, + mode: StructureMode, +) -> String { let lines = classify_source(source); let mut out = String::new(); @@ -171,7 +188,7 @@ pub fn render_module_structure(module: &Module, source: &str) -> String { if i > 0 { out.push_str(&emit_comments(&lines, cursor, fun.span.line)); } - let (html, next) = render_fun(fun, &lines, 0); + let (html, next) = render_fun(fun, &lines, 0, "", mode); out.push_str(&html); cursor = next; } @@ -181,6 +198,52 @@ pub fn render_module_structure(module: &Module, source: &str) -> String { out } +pub fn render_function_outline(module: &Module) -> String { + if module.functions.is_empty() { + return String::new(); + } + let mut out = String::from( + r#"
    + +
      "#, + ); + for fun in &module.functions { + out.push_str(&outline_fun(fun, "")); + } + out.push_str("
    "); + out +} + +fn outline_fun(fun: &Function, parent_path: &str) -> String { + let fn_path = fn_path(parent_path, &fun.name); + let mut s = format!( + "
  • \ + {} h{}", + escape(&fun.name), + escape(&fn_path), + fun.span.line, + escape(&fun.name), + fun.level, + ); + if !fun.children.is_empty() { + s.push_str("
      "); + for child in &fun.children { + s.push_str(&outline_fun(child, &fn_path)); + } + s.push_str("
    "); + } + s.push_str("
  • "); + s +} + +fn fn_path(parent_path: &str, name: &str) -> String { + if parent_path.is_empty() { + name.to_string() + } else { + format!("{parent_path}/{name}") + } +} + /// Line after closing frontmatter `---`, or 1 if none. fn skip_frontmatter_end(lines: &[ClassifiedLine]) -> Option { let first_code = lines.iter().find(|l| l.kind == LineKind::Code)?; @@ -246,10 +309,22 @@ fn comment_markdown_to_html(md: &str) -> String { out } -fn render_fun(fun: &Function, lines: &[ClassifiedLine], depth: usize) -> (String, u32) { +fn render_fun( + fun: &Function, + lines: &[ClassifiedLine], + depth: usize, + parent_path: &str, + mode: StructureMode, +) -> (String, u32) { + let fn_path = fn_path(parent_path, &fun.name); let mut s = String::new(); let nest = if depth > 0 { " nested" } else { "" }; - s.push_str(&format!("
    ")); + s.push_str(&format!( + "
    ", + fun.span.line, + escape(&fun.name), + escape(&fn_path), + )); s.push_str(&format!( "
    fn · h{}{}
    ", fun.level, @@ -295,14 +370,14 @@ fn render_fun(fun: &Function, lines: &[ClassifiedLine], depth: usize) -> (String let stmt = &fun.body[bi]; let start = stmt_start(stmt); s.push_str(&emit_comments(lines, cursor, start)); - let (html, end) = render_stmt(stmt, lines); + let (html, end) = render_stmt(stmt, lines, mode); s.push_str(&html); cursor = end; bi += 1; } else { let child = &fun.children[ci]; s.push_str(&emit_comments(lines, cursor, child.span.line)); - let (html, end) = render_fun(child, lines, depth + 1); + let (html, end) = render_fun(child, lines, depth + 1, &fn_path, mode); s.push_str(&format!("
    {html}
    ")); cursor = end; ci += 1; @@ -347,9 +422,10 @@ fn stmt_end_line(stmt: &Stmt) -> u32 { } } -fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> (String, u32) { +fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (String, u32) { let end = stmt_end_line(stmt); - let html = match stmt { + let line = stmt_start(stmt); + let inner = match stmt { Stmt::Assign { name, value: Expr::Formula(e), @@ -406,7 +482,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> (String, u32) { escape(&call_display(call)) ), Stmt::Branch { arms, .. } => { - let mut inner = + let mut body = String::from("
    branch"); let mut arm_cursor = stmt_start(stmt) + 1; for arm in arms { @@ -416,44 +492,44 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> (String, u32) { }; // comments before first stmt in arm (approx: between arms hard; use body starts) let arm_first = arm.body.first().map(stmt_start); - inner.push_str(&format!( + body.push_str(&format!( "
    arm{}", escape(&label) )); if let Some(af) = arm_first { - inner.push_str(&emit_comments(lines, arm_cursor, af)); + body.push_str(&emit_comments(lines, arm_cursor, af)); arm_cursor = af; } - inner.push_str("
    "); + body.push_str("
    "); for st in &arm.body { let start = stmt_start(st); - inner.push_str(&emit_comments(lines, arm_cursor, start)); - let (h, e) = render_stmt(st, lines); - inner.push_str(&h); + body.push_str(&emit_comments(lines, arm_cursor, start)); + let (h, e) = render_stmt(st, lines, mode); + body.push_str(&h); arm_cursor = e; } - inner.push_str("
    "); + body.push_str("
    "); } - inner.push_str("
    "); - inner + body.push_str("
    "); + body } Stmt::While { condition, body, .. } => { - let mut inner = format!( + let mut body_html = format!( "
    while{}
    ", escape(&expr_display(condition)) ); let mut cursor = stmt_start(stmt) + 1; for st in body { let start = stmt_start(st); - inner.push_str(&emit_comments(lines, cursor, start)); - let (h, e) = render_stmt(st, lines); - inner.push_str(&h); + body_html.push_str(&emit_comments(lines, cursor, start)); + let (h, e) = render_stmt(st, lines, mode); + body_html.push_str(&h); cursor = e; } - inner.push_str("
    "); - inner + body_html.push_str(""); + body_html } Stmt::ForEach { item, @@ -461,7 +537,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> (String, u32) { body, .. } => { - let mut inner = format!( + let mut body_html = format!( "
    foreach[{}]({})
    ", escape(item), escape(collection) @@ -469,16 +545,31 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> (String, u32) { let mut cursor = stmt_start(stmt) + 1; for st in body { let start = stmt_start(st); - inner.push_str(&emit_comments(lines, cursor, start)); - let (h, e) = render_stmt(st, lines); - inner.push_str(&h); + body_html.push_str(&emit_comments(lines, cursor, start)); + let (h, e) = render_stmt(st, lines, mode); + body_html.push_str(&h); cursor = e; } - inner.push_str("
    "); - inner + body_html.push_str(""); + body_html } }; - (html, end) + (stmt_shell(line, &inner, mode), end) +} + +fn stmt_shell(line: u32, inner: &str, mode: StructureMode) -> String { + match mode { + StructureMode::Browse => format!( + r#"
    {inner}
    "#, + line = line, + inner = inner, + ), + StructureMode::Debug => format!( + r#"
    {inner}
    "#, + line = line, + inner = inner, + ), + } } fn call_display(call: &CallExpr) -> String { @@ -718,6 +809,8 @@ mod tests { 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"); } @@ -753,4 +846,29 @@ mod tests { assert_eq!(formula_ascii_to_tex("x^2 - 2"), "x^{2} - 2"); assert_eq!(formula_ascii_to_tex("2*x"), r"2 \cdot x"); } + + #[test] + fn structure_mode_browse_vs_debug() { + let src = include_str!("../../tests/structure/nested-call.mq.md"); + let module = crate::parse::parse_source(src).unwrap(); + 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("bp-gutter"), "{browse}"); + assert!(debug.contains("bp-gutter"), "{debug}"); + assert!(debug.contains("id=\"stmt-"), "{debug}"); + } + + #[test] + fn function_outline_lists_nested_names() { + let src = include_str!("../../tests/structure/nested-call.mq.md"); + let module = crate::parse::parse_source(src).unwrap(); + let outline = render_function_outline(&module); + assert!(outline.contains("outline-item"), "{outline}"); + assert!(outline.contains("data-fn=\"main\""), "{outline}"); + assert!(outline.contains("data-fn=\"问候\""), "{outline}"); + assert!(outline.contains("data-fn-path=\"main/问候\""), "{outline}"); + assert!(outline.contains("href=\"#fn-"), "{outline}"); + assert!(outline.contains("ol-meta\">h"), "{outline}"); + } }