Compare commits
56
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c6fea84d4 | ||
|
|
5c79902f70 | ||
|
|
2e5308e044 | ||
|
|
78b427b667 | ||
|
|
7faaac2aea | ||
|
|
c7011cc32e | ||
|
|
14a2470a12 | ||
|
|
4c7f41151a | ||
|
|
02e8c21118 | ||
|
|
b06a832472 | ||
|
|
25f970db7e | ||
|
|
44569ec26c | ||
|
|
70de478857 | ||
|
|
a6987f8877 | ||
|
|
2e9342b5fa | ||
|
|
9e7c8aafbd | ||
|
|
76213ccf0b | ||
|
|
dcedfdadff | ||
|
|
7597184909 | ||
|
|
3955ae8eca | ||
|
|
8598edb535 | ||
|
|
568fa4f2bf | ||
|
|
95a6375558 | ||
|
|
8fe8d51289 | ||
|
|
86a9513e51 | ||
|
|
9325cf327d | ||
|
|
e455235218 | ||
|
|
dd025016c3 | ||
|
|
31da360274 | ||
|
|
0ac3b2ab27 | ||
|
|
82ef21e816 | ||
|
|
00e25c1f69 | ||
|
|
f274a48f60 | ||
|
|
f75d34f64a | ||
|
|
2e10987982 | ||
|
|
c96a2de94c | ||
|
|
fd2254b2a8 | ||
|
|
db300977c2 | ||
|
|
f583062b4b | ||
|
|
84afb6bcb8 | ||
|
|
e8e11cffce | ||
|
|
d180b949f4 | ||
|
|
4a546d17bc | ||
|
|
12569f0afd | ||
|
|
155bed4ce9 | ||
|
|
78af67d1e0 | ||
|
|
9361992d11 | ||
|
|
d1b75d88c5 | ||
|
|
3887205ebb | ||
|
|
f4f798a4d0 | ||
|
|
e08cd839be | ||
|
|
5309848292 | ||
|
|
1271aafcdd | ||
|
|
54a507d906 | ||
|
|
ea17ae1074 | ||
|
|
fe9046cecf |
No files matched your search
@@ -0,0 +1,70 @@
|
||||
# Build and attach release binaries when a version tag is pushed.
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Build release
|
||||
run: cargo build --release
|
||||
|
||||
- name: Package
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ver = "${{ github.ref_name }}".TrimStart("v")
|
||||
$target = "x86_64-pc-windows-msvc"
|
||||
New-Item -ItemType Directory -Force -Path dist | Out-Null
|
||||
$exe = "marqdo-$ver-$target.exe"
|
||||
$zip = "marqdo-$ver-$target.zip"
|
||||
$stdlib = "marqdo-$ver-stdlib.zip"
|
||||
Copy-Item target/release/marqdo.exe "dist/$exe"
|
||||
$stage = "dist/stage-bundle"
|
||||
if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $stage | Out-Null
|
||||
Copy-Item target/release/marqdo.exe "$stage/marqdo.exe"
|
||||
Copy-Item lib "$stage/lib" -Recurse
|
||||
if (Test-Path "dist/$zip") { Remove-Item "dist/$zip" -Force }
|
||||
Compress-Archive -Path "$stage/*" -DestinationPath "dist/$zip" -Force
|
||||
$stageLib = "dist/stage-stdlib"
|
||||
if (Test-Path $stageLib) { Remove-Item $stageLib -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $stageLib | Out-Null
|
||||
Copy-Item lib "$stageLib/lib" -Recurse
|
||||
if (Test-Path "dist/$stdlib") { Remove-Item "dist/$stdlib" -Force }
|
||||
Compress-Archive -Path "$stageLib/*" -DestinationPath "dist/$stdlib" -Force
|
||||
echo "EXE=$exe" >> $env:GITHUB_ENV
|
||||
echo "ZIP=$zip" >> $env:GITHUB_ENV
|
||||
echo "STDLIB=$stdlib" >> $env:GITHUB_ENV
|
||||
|
||||
- name: Upload release assets
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
body: |
|
||||
## Downloads
|
||||
|
||||
| Asset | Contents |
|
||||
|-------|----------|
|
||||
| `marqdo-*-windows-msvc.exe` | **Executable only** — does **not** include the standard library |
|
||||
| `marqdo-*-windows-msvc.zip` | **Recommended**: `marqdo.exe` + `lib/` (keep them together) |
|
||||
| `marqdo-*-stdlib.zip` | Standard library only — unpack next to the exe, or set `MARQDO_LIB` |
|
||||
|
||||
> The standalone `.exe` does **not** ship `lib/`. Use the bundle zip or stdlib zip for `lib/…` imports.
|
||||
files: |
|
||||
dist/${{ env.EXE }}
|
||||
dist/${{ env.ZIP }}
|
||||
dist/${{ env.STDLIB }}
|
||||
fail_on_unmatched_files: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
+5
-2
@@ -1,7 +1,9 @@
|
||||
/target/
|
||||
/target/
|
||||
/dist/
|
||||
**/*.rs.bk
|
||||
.idea/
|
||||
.vscode/
|
||||
# Editor settings at repo root only (keep vscode-extension/.vscode for F5)
|
||||
/.vscode/
|
||||
*.pdb
|
||||
.DS_Store
|
||||
.marqdo/
|
||||
@@ -10,6 +12,7 @@
|
||||
/public/index.html
|
||||
/public/pages/
|
||||
|
||||
|
||||
# Python spike venv (local)
|
||||
spike/.venv/
|
||||
spike/__pycache__/
|
||||
|
||||
Generated
+1
-1
@@ -344,7 +344,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "marqdo"
|
||||
version = "0.0.3"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"assert_cmd",
|
||||
|
||||
+1
-1
@@ -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"
|
||||
|
||||
@@ -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) · OKF 清单:[catalog-cli.md](doc/design/catalog-cli.md) · VS Code 扩展:[vscode-extension.md](doc/design/vscode-extension.md)(分支 `vscode-extension`) · 金样例:[tests/](tests/) · 用户文档:[public/](public/)
|
||||
|
||||
---
|
||||
|
||||
## 为什么重要
|
||||
|
||||
| 痛点 | Marqdo 的答案 |
|
||||
|------|----------------|
|
||||
| 文档过期、示例跑不通 | **一份源文件**:叙述、结构与执行结果同源 |
|
||||
| 知识散落在 Wiki / 注释 / 脚本里 | **`.mq.md` 即知识单元**,可浏览、可运行、可检索 |
|
||||
| 人写给人看,AI / 工具另起一套 | **人机同读同写同构**:标记语言对人类友好,对解释器确定 |
|
||||
| 大仓里「文档站」与「代码仓」脱节 | `view` 文档站 + `debug` 调试面 + `catalog` 清单,同一棵树长大 |
|
||||
|
||||
这不是「再做一个 Markdown 渲染器」,而是:**把文档升格为可解释的程序与可生长的知识库**,让协作在大型项目里依然站得住。
|
||||
|
||||
---
|
||||
|
||||
@@ -14,20 +27,29 @@ Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程
|
||||
|
||||
| 标记 | 含义 |
|
||||
|------|------|
|
||||
| 无标记行 | 注释 |
|
||||
| 无标记行 | 注释(空行分段) |
|
||||
| `*…*` | 程序语句 |
|
||||
| `**…**` | **返回值**(架构) |
|
||||
| `****` / `**` + 空白 + `**` | **空返回**(`None`),并结束本函数体 |
|
||||
| `> print …` 等 | 输出等副作用 = **普通函数**,非架构标记 |
|
||||
| `#` / `##` | 函数与作用域 |
|
||||
| `+` / `1.` | 分支(臂头单独 `*` = else) |
|
||||
| `-` | 循环(头下纯名则为形参) |
|
||||
| 表格 | 集合 |
|
||||
| `---` / `***` | 可选:框住分支/循环(不强制) |
|
||||
| 函数体内单独一行 `---` / `***` | **结束本函数体**(无返回值收束;见 mapping §11) |
|
||||
| 文件开头成对 `---` … `---` | Frontmatter(元信息 / 导入),与函数结束符消歧 |
|
||||
|
||||
```markdown
|
||||
# main
|
||||
|
||||
> print text=Hello World!
|
||||
> 问候 谁=World
|
||||
|
||||
## 问候
|
||||
- 谁
|
||||
|
||||
> print text=Hello `谁`!
|
||||
|
||||
---
|
||||
|
||||
## 加一
|
||||
- n
|
||||
@@ -35,37 +57,67 @@ Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程
|
||||
**`n` + 1**
|
||||
```
|
||||
|
||||
完整约定:[markdown-mapping.md](doc/design/markdown-mapping.md)。
|
||||
|
||||
---
|
||||
|
||||
## 理念
|
||||
|
||||
1. 叙述默认安全(无标记 = 注释)。
|
||||
2. 返回是架构;打印只是函数。
|
||||
3. 依赖清单由工具生成(OKF 风格),不是手填配置。
|
||||
4. **正经解释器(Rust)**:词法/行分类 → 递归下降语法 → 语义 → 树遍历 → 日后字节码;**不用 Flex/Bison**。见 [路线图](doc/roadmap/interpreter.md) 与 [依赖说明](doc/design/dependencies.md)。
|
||||
1. **叙述默认安全**(无标记 = 注释)。
|
||||
2. **返回是架构;打印只是函数。**
|
||||
3. **代码即文档即知识库**:文稿可执行,执行可回看结构,结构可导航与调试。
|
||||
4. **对齐 [OKF](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)(Open Knowledge Format)方向**:清单由工具从 `.mq.md` **自动生成**,不是手填配置——见下节与 [catalog-cli.md](doc/design/catalog-cli.md)。
|
||||
5. **正经解释器(Rust)**:词法/行分类 → 语法 → 语义 → 树遍历(及字节码);**不用 Flex/Bison**。见 [路线图](doc/roadmap/interpreter.md)。
|
||||
|
||||
---
|
||||
|
||||
## 现状
|
||||
## OKF 风格清单(自动生成)
|
||||
|
||||
- 映射 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)
|
||||
从源码派生 YAML / Markdown 知识包(勿手改生成物):
|
||||
|
||||
```bash
|
||||
marqdo catalog [PATH] -o OUT_DIR
|
||||
marqdo sync [PATH] -o OUT_DIR # catalog 的别名
|
||||
```
|
||||
|
||||
| 参数 | 默认 | 说明 |
|
||||
|------|------|------|
|
||||
| `PATH` | `.` | 工程根或含 `.mq.md` 的目录 |
|
||||
| `-o` / `--out` | `.marqdo` | 输出目录 |
|
||||
|
||||
产物示例:`catalog.yaml`、`index.md`、`modules/*.md`(`type: Marqdo Module` 等)。设计见 [generated-yaml-manifest.md](doc/design/generated-yaml-manifest.md) · 调研 [okf-and-marqdo.md](doc/research/okf-and-marqdo.md)。
|
||||
|
||||
```bash
|
||||
cargo run -- catalog public -o .marqdo
|
||||
# 或已安装二进制时:
|
||||
marqdo catalog public -o .marqdo
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 现状(v0.1.0)
|
||||
|
||||
- 映射与解释器:Phase I 树遍历 + 字节码后端可用;金样例在 `tests/`
|
||||
- **`marqdo view`**:文档浏览器(Structure + 函数大纲/搜索 + Execution + Source)
|
||||
- **`marqdo debug`**:独立调试页(断点 / 单步 / locals;默认端口 7430)
|
||||
- **`marqdo catalog` / `sync`**:OKF 风格 YAML + 模块概念页
|
||||
- 标准库:文本、文件、系统、时间、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 -- catalog public -o .marqdo
|
||||
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)。
|
||||
**发布包(GitHub Releases)**:单独 `.exe` **不含** `lib/`;请下载带 `lib/` 的 zip,或另下 `*-stdlib.zip` 解压到可执行文件旁(亦可设 `MARQDO_LIB`)。
|
||||
|
||||
文档:用户站 [public/](public/) · 设计 [doc/](doc/) · OKF / catalog [catalog-cli.md](doc/design/catalog-cli.md) · 调试 [view-debug.md](doc/design/view-debug.md)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@
|
||||
| [design/view.md](design/view.md) | **`marqdo view` / `view output` 黑白极简 + 静态文档** |
|
||||
| [design/user-site.md](design/user-site.md) | **用户站:`public/` → `gh-pages`** |
|
||||
| [design/catalog-cli.md](design/catalog-cli.md) | **`marqdo catalog` / `sync` OKF 清单命令** |
|
||||
| [design/view-debug.md](design/view-debug.md) | **`marqdo debug` 独立调试页** |
|
||||
| [design/vscode-extension.md](design/vscode-extension.md) | **VS Code 扩展:分支 `vscode-extension`(main 不跟踪源码)** |
|
||||
| [design/bytecode.md](design/bytecode.md) | **M5 字节码 / 双后端** |
|
||||
| [design/pipeline-debug.md](design/pipeline-debug.md) | **流水线 `--dump-*` 可视调试** |
|
||||
| [dev-setup.md](dev-setup.md) | 开发环境配置(Rust M0) |
|
||||
|
||||
@@ -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`。
|
||||
+8
-6
@@ -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 页面分离。
|
||||
@@ -0,0 +1,31 @@
|
||||
# VS Code 扩展(分支指针)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **已定分支模型** |
|
||||
| 日期 | 2026-08-05 |
|
||||
| 代码分支 | **`vscode-extension`**(同仓库) |
|
||||
| 目录 | 工作区 `vscode-extension/`(仅在该分支跟踪;**`main` 忽略**) |
|
||||
|
||||
---
|
||||
|
||||
## 分工(类比 `public` / `gh-pages`)
|
||||
|
||||
| 分支 | 内容 |
|
||||
|------|------|
|
||||
| `main` | Marqdo 语言 / CLI / `public/*.mq.md` 源;**不**存放扩展实现 |
|
||||
| `vscode-extension` | VS Code 扩展源码、开发规范、TextMate 语法 |
|
||||
| `gh-pages` | 用户站生成 HTML |
|
||||
|
||||
```bash
|
||||
git checkout vscode-extension
|
||||
cd vscode-extension && npm install
|
||||
```
|
||||
|
||||
规范入口(在该分支上阅读):
|
||||
|
||||
- `vscode-extension/README.md` — 目标与目录
|
||||
- `vscode-extension/DEVELOPMENT.md` — 日常流程
|
||||
- `vscode-extension/ARCHITECTURE.md` — 与 CLI 边界
|
||||
|
||||
扩展是 CLI 的薄宿主;语法真相仍是 [markdown-mapping.md](markdown-mapping.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` 顶层函数合并,无命名空间 | 短期可继续用 |
|
||||
|
||||
|
||||
+36
-15
@@ -51,34 +51,55 @@ 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, ver: str) -> list[Path]:
|
||||
names = [
|
||||
f"{stem}.exe",
|
||||
f"{stem}.zip",
|
||||
f"marqdo-{ver}-stdlib.zip",
|
||||
]
|
||||
assets: list[Path] = []
|
||||
for name in names:
|
||||
found = None
|
||||
for base in (Path("dist"), Path("target/dist")):
|
||||
p = base / name
|
||||
if p.exists():
|
||||
found = p
|
||||
break
|
||||
if not found:
|
||||
raise SystemExit(f"missing asset: {name} under dist/ or target/dist/")
|
||||
assets.append(found)
|
||||
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, ver)
|
||||
|
||||
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
|
||||
### Downloads
|
||||
|
||||
### Assets
|
||||
- `{stem}.exe` — Windows x64 binary
|
||||
- `{stem}.zip` — same binary zipped
|
||||
| Asset | Contents |
|
||||
|-------|----------|
|
||||
| `{stem}.exe` | **Executable only** — does **not** include the standard library |
|
||||
| `{stem}.zip` | **Recommended**: `marqdo.exe` + `lib/` (keep them together; `lib/` resolves next to the binary) |
|
||||
| `marqdo-{ver}-stdlib.zip` | Standard library only (`lib/*.mq.md`) — unpack next to an existing exe, or set `MARQDO_LIB` |
|
||||
|
||||
> **Important:** the standalone `.exe` does **not** ship `lib/`. Importing `lib/text.mq.md` etc. needs the bundle zip or the stdlib zip.
|
||||
|
||||
### Highlights
|
||||
- **Code as docs as knowledge**: `.mq.md` is narrative + program in one tree
|
||||
- **`marqdo debug`**: dedicated debugger; view stays docs-only
|
||||
- **View**: function outline + search
|
||||
- Roadmap: deeper **OKF**-aligned catalog for human–AI knowledge bases
|
||||
|
||||
```text
|
||||
marqdo --version
|
||||
marqdo run public/00-welcome.mq.md
|
||||
marqdo view public
|
||||
marqdo debug public
|
||||
```
|
||||
"""
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# Build Windows release assets (exe, bundle zip with lib/, stdlib zip) and upload
|
||||
# to an existing GitHub Release tag.
|
||||
# Usage (from repo root):
|
||||
# powershell -File ./scripts/release-windows.ps1
|
||||
# powershell -File ./scripts/release-windows.ps1 -Tag v0.1.0
|
||||
param(
|
||||
[string]$Tag = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
Set-Location (Split-Path $PSScriptRoot -Parent)
|
||||
|
||||
if (-not $Tag) {
|
||||
$Tag = (Select-String -Path Cargo.toml -Pattern '^version\s*=\s*"([^"]+)"').Matches.Groups[1].Value
|
||||
$Tag = "v$Tag"
|
||||
}
|
||||
$ver = $Tag.TrimStart("v")
|
||||
$target = "x86_64-pc-windows-msvc"
|
||||
$dist = Join-Path (Get-Location) "dist"
|
||||
$stage = Join-Path $dist "stage-bundle"
|
||||
$stageLib = Join-Path $dist "stage-stdlib"
|
||||
New-Item -ItemType Directory -Force -Path $dist | Out-Null
|
||||
|
||||
Write-Host "Building release binary for $Tag ..."
|
||||
cargo build --release -q
|
||||
|
||||
$exeName = "marqdo-$ver-$target.exe"
|
||||
$zipName = "marqdo-$ver-$target.zip"
|
||||
$stdlibName = "marqdo-$ver-stdlib.zip"
|
||||
$exePath = Join-Path $dist $exeName
|
||||
$zipPath = Join-Path $dist $zipName
|
||||
$stdlibPath = Join-Path $dist $stdlibName
|
||||
|
||||
Copy-Item ".\target\release\marqdo.exe" $exePath -Force
|
||||
|
||||
# Bundle: marqdo.exe + lib/ (stdlib resolves next to the binary)
|
||||
if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $stage | Out-Null
|
||||
Copy-Item ".\target\release\marqdo.exe" (Join-Path $stage "marqdo.exe") -Force
|
||||
Copy-Item ".\lib" (Join-Path $stage "lib") -Recurse -Force
|
||||
Get-ChildItem -Path (Join-Path $stage "lib") -Recurse -Filter "*.mq.md" | Out-Null
|
||||
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
|
||||
Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipPath -Force
|
||||
|
||||
# Stdlib-only zip (for users who already have the exe)
|
||||
if (Test-Path $stageLib) { Remove-Item $stageLib -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $stageLib | Out-Null
|
||||
Copy-Item ".\lib" (Join-Path $stageLib "lib") -Recurse -Force
|
||||
if (Test-Path $stdlibPath) { Remove-Item $stdlibPath -Force }
|
||||
Compress-Archive -Path (Join-Path $stageLib "*") -DestinationPath $stdlibPath -Force
|
||||
|
||||
Write-Host "Packaged:"
|
||||
Write-Host " $exePath (binary only — no stdlib)"
|
||||
Write-Host " $zipPath (marqdo.exe + lib/)"
|
||||
Write-Host " $stdlibPath (lib/ only)"
|
||||
|
||||
$raw = ("protocol=https`nhost=github.com`n`n" | git credential fill 2>$null) -join "`n"
|
||||
$user = ([regex]::Match($raw, '(?m)^username=(.+)$')).Groups[1].Value
|
||||
$token = ([regex]::Match($raw, '(?m)^password=(.+)$')).Groups[1].Value
|
||||
if (-not $token) { throw "No GitHub credentials from git credential fill; run gh auth login or configure git credentials." }
|
||||
$pair = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${user}:${token}"))
|
||||
$headers = @{
|
||||
Authorization = "Basic $pair"
|
||||
Accept = "application/vnd.github+json"
|
||||
"User-Agent" = "marqdo-release-windows"
|
||||
}
|
||||
|
||||
$rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/tags/$Tag" -Headers $headers
|
||||
Write-Host "Uploading to release $($rel.html_url)"
|
||||
|
||||
# Refresh release notes
|
||||
$notes = @"
|
||||
## Marqdo $Tag
|
||||
|
||||
### Downloads
|
||||
|
||||
| Asset | Contents |
|
||||
|-------|----------|
|
||||
| ``$exeName`` | **Executable only** — does **not** include the standard library |
|
||||
| ``$zipName`` | **Recommended**: ``marqdo.exe`` + ``lib/`` (place them together; ``lib/`` is resolved next to the binary) |
|
||||
| ``$stdlibName`` | Standard library only (``lib/*.mq.md``) — unpack next to an existing ``marqdo.exe``, or set ``MARQDO_LIB`` |
|
||||
|
||||
> **Important:** the standalone ``.exe`` does **not** ship ``lib/``. Importing ``lib/text.mq.md`` etc. needs the bundle zip or the stdlib zip beside the binary (or ``MARQDO_LIB``).
|
||||
|
||||
### Highlights
|
||||
- Code as docs as knowledge: ``.mq.md`` is narrative + program
|
||||
- ``marqdo debug``: breakpoints / step / locals; ``marqdo view`` stays docs-only
|
||||
- View: function outline + search; wider layout
|
||||
- Roadmap: deeper OKF-aligned catalog for human–AI knowledge bases
|
||||
|
||||
``````text
|
||||
marqdo --version
|
||||
marqdo run public/00-welcome.mq.md
|
||||
marqdo view public
|
||||
marqdo debug public
|
||||
``````
|
||||
"@
|
||||
|
||||
$body = @{
|
||||
tag_name = $Tag
|
||||
name = $Tag
|
||||
body = $notes
|
||||
draft = $false
|
||||
prerelease = $false
|
||||
} | ConvertTo-Json -Depth 5
|
||||
Invoke-RestMethod -Method Patch -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$($rel.id)" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([Text.Encoding]::UTF8.GetBytes($body)) | Out-Null
|
||||
|
||||
# Re-fetch assets list after patch
|
||||
$rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$($rel.id)" -Headers $headers
|
||||
|
||||
foreach ($file in @($exeName, $zipName, $stdlibName)) {
|
||||
$path = Join-Path $dist $file
|
||||
$existing = $rel.assets | Where-Object { $_.name -eq $file }
|
||||
if ($existing) {
|
||||
Invoke-RestMethod -Method Delete -Uri $existing.url -Headers $headers | Out-Null
|
||||
Write-Host " deleted old $file"
|
||||
}
|
||||
$uri = "https://uploads.github.com/repos/cflmy/marqdo/releases/$($rel.id)/assets?name=$([uri]::EscapeDataString($file))"
|
||||
$bytes = [System.IO.File]::ReadAllBytes($path)
|
||||
$ctype = if ($file.EndsWith(".zip")) { "application/zip" } else { "application/octet-stream" }
|
||||
$asset = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType $ctype -Body $bytes
|
||||
Write-Host " $($asset.browser_download_url)"
|
||||
}
|
||||
|
||||
Write-Host "OK"
|
||||
@@ -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<Option<DebugAction>>,
|
||||
cv: Condvar,
|
||||
}
|
||||
|
||||
/// Shared between the interpreter thread and HTTP/CLI control.
|
||||
pub struct DebugController {
|
||||
breakpoints: Mutex<HashSet<u32>>,
|
||||
/// 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<Option<u32>>,
|
||||
gate: Gate,
|
||||
snapshot: Mutex<DebugSnapshot>,
|
||||
/// Notifies waiters that snapshot changed.
|
||||
snap_cv: Condvar,
|
||||
}
|
||||
|
||||
impl DebugController {
|
||||
pub fn new(breakpoints: HashSet<u32>) -> Arc<Self> {
|
||||
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<u32>) {
|
||||
*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<u32> {
|
||||
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<String, Value>,
|
||||
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<String, serde_json::Value> = 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<DebugAction>, Receiver<DebugAction>) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -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;
|
||||
+27
-1
@@ -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<PathBuf>,
|
||||
@@ -25,6 +26,7 @@ pub struct Interpreter {
|
||||
current_span: Span,
|
||||
input: InputFeed,
|
||||
host: HostContext,
|
||||
debug: Option<Arc<DebugController>>,
|
||||
}
|
||||
|
||||
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<DebugController>) -> Self {
|
||||
self.debug = Some(debug);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn take_plots(&mut self) -> Vec<crate::host::PlotArtifact> {
|
||||
std::mem::take(&mut self.host.plots)
|
||||
}
|
||||
@@ -184,6 +193,12 @@ impl Interpreter {
|
||||
env: &mut Env,
|
||||
stmt: &Stmt,
|
||||
) -> Result<Option<Value>> {
|
||||
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,
|
||||
}
|
||||
}
|
||||
+31
-2
@@ -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<PathBuf>,
|
||||
|
||||
#[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<i32> {
|
||||
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(".")),
|
||||
|
||||
@@ -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<DebugController>,
|
||||
#[allow(dead_code)]
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
fn sessions() -> &'static Mutex<HashMap<String, Arc<Session>>> {
|
||||
static S: OnceLock<Mutex<HashMap<String, Arc<Session>>>> = 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<u32> {
|
||||
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<u32> = 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",
|
||||
}
|
||||
}
|
||||
@@ -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!(
|
||||
"<div class=\"err\">parse error: {}</div>",
|
||||
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#"<label class="dbg-stdin-label">stdin <textarea id="stdin" rows="2" spellcheck="false">{stdin}</textarea></label>"#,
|
||||
stdin = escape(&vm.stdin_preset),
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let outline = if vm.outline_html.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(r#"<div class="dbg-outline">{}</div>"#, vm.outline_html)
|
||||
};
|
||||
|
||||
let body = format!(
|
||||
r#"
|
||||
<script>
|
||||
window.MARQDO_FILE_PATH = {path_js};
|
||||
</script>
|
||||
<header class="dbg-toolbar">
|
||||
<div class="dbg-brand">
|
||||
<span class="dbg-mark">marqdo</span>
|
||||
<span class="dbg-mode">debug</span>
|
||||
</div>
|
||||
<div class="dbg-actions">
|
||||
<button type="button" class="dbg-btn primary" id="dbg-start" title="Start">Start</button>
|
||||
<button type="button" class="dbg-btn" id="dbg-continue" disabled title="Continue (F5)">Continue</button>
|
||||
<button type="button" class="dbg-btn" id="dbg-step" disabled title="Step Over (F10)">Step</button>
|
||||
<button type="button" class="dbg-btn danger" id="dbg-stop" disabled title="Stop">Stop</button>
|
||||
</div>
|
||||
<div class="dbg-status" id="dbg-status">Idle — set breakpoints, then Start · drag edges to resize panes</div>
|
||||
</header>
|
||||
<div class="dbg-work">
|
||||
<div class="dbg-shell">
|
||||
<aside class="dbg-nav" id="dbg-nav">
|
||||
<h2>Files</h2>
|
||||
{nav}
|
||||
</aside>
|
||||
<div class="dbg-split-v" id="split-nav" title="Drag to resize"></div>
|
||||
<main class="dbg-main">
|
||||
<div class="dbg-main-head">
|
||||
<h1>{title}</h1>
|
||||
<p class="meta">{rel}</p>
|
||||
{stdin}
|
||||
</div>
|
||||
<div class="dbg-center">
|
||||
<section class="dbg-structure-pane">
|
||||
<h2>Structure <span class="hint">gutter = breakpoint</span></h2>
|
||||
<div class="structure debug-surface" id="structure">{structure}</div>
|
||||
</section>
|
||||
{outline}
|
||||
</div>
|
||||
</main>
|
||||
<div class="dbg-split-v" id="split-side" title="Drag to resize"></div>
|
||||
<aside class="dbg-side" id="dbg-side">
|
||||
<section class="dbg-panel">
|
||||
<h2>Variables</h2>
|
||||
<div id="dbg-locals" class="dbg-vars">(idle)</div>
|
||||
</section>
|
||||
<section class="dbg-panel">
|
||||
<h2>Breakpoints</h2>
|
||||
<ul id="dbg-bps" class="dbg-bps"><li class="muted">none</li></ul>
|
||||
</section>
|
||||
<section class="dbg-panel">
|
||||
<h2>Call stack</h2>
|
||||
<div id="dbg-frame" class="dbg-frame">(idle)</div>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
<div class="dbg-split-h" id="split-console" title="Drag to resize console"></div>
|
||||
<section class="dbg-console" id="dbg-console">
|
||||
<h2>Debug Console</h2>
|
||||
<pre id="dbg-stdout" class="dbg-out">(idle)</pre>
|
||||
</section>
|
||||
</div>
|
||||
"#,
|
||||
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##"<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>debug · {title} · marqdo</title>
|
||||
<style>{css}</style>
|
||||
</head>
|
||||
<body class="dbg-body">
|
||||
{main}
|
||||
<script>
|
||||
{js}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
"##,
|
||||
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 = '<li class="muted">none</li>';
|
||||
return;
|
||||
}
|
||||
var html = "";
|
||||
list.forEach(function (n) {
|
||||
html += '<li data-line="' + n + '">line ' + n + '</li>';
|
||||
});
|
||||
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; });
|
||||
});
|
||||
});
|
||||
})();
|
||||
"#
|
||||
}
|
||||
+164
-9
@@ -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);
|
||||
}}
|
||||
}});
|
||||
}});
|
||||
}}
|
||||
}})();
|
||||
</script>
|
||||
@@ -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#"<div class="structure" id="structure">{structure}</div>"#,
|
||||
structure = vm.structure_html
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
r#"<div class="struct-wrap">
|
||||
<div class="structure" id="structure">{structure}</div>
|
||||
{outline}
|
||||
</div>"#,
|
||||
structure = vm.structure_html,
|
||||
outline = outline_block,
|
||||
)
|
||||
};
|
||||
let main = format!(
|
||||
r#"
|
||||
<script>window.MARQDO_VIEW_LIVE = {live};</script>
|
||||
<script>
|
||||
window.MARQDO_VIEW_LIVE = {live};
|
||||
window.MARQDO_FILE_PATH = {path_js};
|
||||
</script>
|
||||
<h1 class="page">{title}<span class="status-pill {status}">{status_label}</span></h1>
|
||||
<p class="meta">{rel}</p>
|
||||
<section class="block">
|
||||
<h2>Structure</h2>
|
||||
<div class="structure">{structure}</div>
|
||||
{structure_block}
|
||||
</section>
|
||||
<section class="block">
|
||||
<h2>Execution</h2>
|
||||
@@ -953,11 +1089,12 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
|
||||
</section>
|
||||
"#,
|
||||
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
|
||||
}
|
||||
+129
-2
@@ -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<PathBuf>,
|
||||
@@ -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<ViewRoot> {
|
||||
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<FileViewModel> {
|
||||
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(
|
||||
"<div class=\"err\">parse/load error: {}</div>",
|
||||
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)?;
|
||||
|
||||
+148
-30
@@ -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#"<div class="outline-panel" id="fn-outline">
|
||||
<input type="search" id="fn-search" class="fn-search" placeholder="Search functions…" autocomplete="off" spellcheck="false"/>
|
||||
<ul class="outline-tree">"#,
|
||||
);
|
||||
for fun in &module.functions {
|
||||
out.push_str(&outline_fun(fun, ""));
|
||||
}
|
||||
out.push_str("</ul></div>");
|
||||
out
|
||||
}
|
||||
|
||||
fn outline_fun(fun: &Function, parent_path: &str) -> String {
|
||||
let fn_path = fn_path(parent_path, &fun.name);
|
||||
let mut s = format!(
|
||||
"<li class=\"outline-item\" data-fn=\"{}\" data-fn-path=\"{}\">\
|
||||
<a href=\"#fn-{}\">{}</a> <span class=\"ol-meta\">h{}</span>",
|
||||
escape(&fun.name),
|
||||
escape(&fn_path),
|
||||
fun.span.line,
|
||||
escape(&fun.name),
|
||||
fun.level,
|
||||
);
|
||||
if !fun.children.is_empty() {
|
||||
s.push_str("<ul>");
|
||||
for child in &fun.children {
|
||||
s.push_str(&outline_fun(child, &fn_path));
|
||||
}
|
||||
s.push_str("</ul>");
|
||||
}
|
||||
s.push_str("</li>");
|
||||
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<u32> {
|
||||
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!("<div class=\"card fun-card{nest}\">"));
|
||||
s.push_str(&format!(
|
||||
"<div class=\"card fun-card{nest}\" id=\"fn-{}\" data-fn=\"{}\" data-fn-path=\"{}\">",
|
||||
fun.span.line,
|
||||
escape(&fun.name),
|
||||
escape(&fn_path),
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"<div><span class=\"badge\">fn · h{}</span><strong>{}</strong></div>",
|
||||
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!("<div class=\"nested\">{html}</div>"));
|
||||
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("<div class=\"card branch-card\"><span class=\"badge\">branch</span>");
|
||||
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!(
|
||||
"<div class=\"arm\"><span class=\"badge\">arm</span><code class=\"expr\">{}</code>",
|
||||
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("<div class=\"nested\">");
|
||||
body.push_str("<div class=\"nested\">");
|
||||
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("</div></div>");
|
||||
body.push_str("</div></div>");
|
||||
}
|
||||
inner.push_str("</div>");
|
||||
inner
|
||||
body.push_str("</div>");
|
||||
body
|
||||
}
|
||||
Stmt::While {
|
||||
condition, body, ..
|
||||
} => {
|
||||
let mut inner = format!(
|
||||
let mut body_html = format!(
|
||||
"<div class=\"card loop-card\"><span class=\"badge\">while</span><code class=\"expr\">{}</code><div class=\"nested\">",
|
||||
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("</div></div>");
|
||||
inner
|
||||
body_html.push_str("</div></div>");
|
||||
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!(
|
||||
"<div class=\"card loop-card\"><span class=\"badge\">foreach</span><code class=\"expr\">[{}]({})</code><div class=\"nested\">",
|
||||
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("</div></div>");
|
||||
inner
|
||||
body_html.push_str("</div></div>");
|
||||
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#"<div class="stmt" data-line="{line}" id="stmt-{line}"><div class="stmt-body">{inner}</div></div>"#,
|
||||
line = line,
|
||||
inner = inner,
|
||||
),
|
||||
StructureMode::Debug => format!(
|
||||
r#"<div class="stmt" data-line="{line}" id="stmt-{line}"><button type="button" class="bp-gutter" title="Toggle breakpoint" aria-label="Breakpoint line {line}"></button><div class="stmt-body">{inner}</div></div>"#,
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
.vscode-test/**
|
||||
node_modules/**
|
||||
out/**
|
||||
*.vsix
|
||||
npm-debug.log*
|
||||
.DS_Store
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Run Extension",
|
||||
"type": "extensionHost",
|
||||
"request": "launch",
|
||||
"args": [
|
||||
"--extensionDevelopmentPath=${workspaceFolder}",
|
||||
"${workspaceFolder}/.."
|
||||
],
|
||||
"outFiles": [
|
||||
"${workspaceFolder}/out/**/*.js"
|
||||
],
|
||||
"preLaunchTask": "npm: watch"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "watch",
|
||||
"problemMatcher": "$tsc-watch",
|
||||
"isBackground": true,
|
||||
"presentation": {
|
||||
"reveal": "never"
|
||||
},
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "compile",
|
||||
"problemMatcher": "$tsc",
|
||||
"group": "build"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
.vscode/**
|
||||
.vscode-test/**
|
||||
src/**
|
||||
tsconfig.json
|
||||
node_modules/**
|
||||
.gitignore
|
||||
**/*.map
|
||||
**/*.ts
|
||||
!out/**/*.js
|
||||
media/logo-source.*
|
||||
@@ -0,0 +1,68 @@
|
||||
# 架构(规范)
|
||||
|
||||
## 进程边界
|
||||
|
||||
```
|
||||
┌─────────────────────────────┐
|
||||
│ VS Code Extension Host │
|
||||
│ · 语言配置 / TextMate │
|
||||
│ · 命令、任务、Problems │
|
||||
│ · (日后)LSP client │
|
||||
│ · (日后)DAP client │
|
||||
└─────────────┬───────────────┘
|
||||
│ spawn / stdio
|
||||
▼
|
||||
┌─────────────────────────────┐
|
||||
│ marqdo CLI(已安装) │
|
||||
│ · run / catalog / debug │
|
||||
│ · 诊断文案与行号真相 │
|
||||
└─────────────────────────────┘
|
||||
```
|
||||
|
||||
扩展 **不嵌入** Rust 解释器;分发上用户安装 CLI(或日后可选打包 sidecar,仍属后置决策)。
|
||||
|
||||
## 语言 id
|
||||
|
||||
- VS Code `languageId`: `marqdo`
|
||||
- 文件:`*.mq.md`(必须保留 `.md` 后缀以便通用预览;用 `filename` / `filenamePattern` 关联,避免抢全部 Markdown)
|
||||
|
||||
## 与 Markdown 扩展共存
|
||||
|
||||
`.mq.md` 同时是 Markdown。策略:
|
||||
|
||||
1. **默认**用 Marqdo 语言模式(执行语义优先)。
|
||||
2. 提供命令「以 Markdown 打开预览」调用内置 Markdown preview(不切换语言 id 也可预览时,优先不破坏高亮)。
|
||||
3. 不禁用用户其它 Markdown 扩展;冲突时文档说明如何 `files.associations`。
|
||||
|
||||
## 诊断契约
|
||||
|
||||
CLI 用户可见失败:
|
||||
|
||||
```text
|
||||
path:line:col: message
|
||||
```
|
||||
|
||||
扩展将相对路径解析到工作区 URI,`severity` 为 0-based。与语言仓 P0 诊断模型一致。
|
||||
|
||||
## CLI 安装(扩展侧)
|
||||
|
||||
- 启动时(`onStartupFinished`)检测:**CLI 是否存在**、**版本是否 ≥ `marqdo.minCliVersion`(默认 0.1.0)**、**stdlib (`lib/`) 是否可用**。
|
||||
- 任一不满足 → 提示用户,由其选择安装 / 打开 Releases / 不再询问。
|
||||
- 安装物落到扩展 `globalStorage/cli/`,并写入 `marqdo.cliPath` / `marqdo.libPath`(spawn 时带 `MARQDO_LIB`)。
|
||||
- 命令:`Marqdo: Install / Repair CLI`、`Marqdo: Check CLI Status`。
|
||||
- 预编译自动安装以 **Windows x64** Release zip 为主。
|
||||
|
||||
## 调试(P3 → 现有入口)
|
||||
- **已落地**:命令 `Marqdo: Open Debugger` 子进程启动 `marqdo debug --no-open`,再打开浏览器 / Simple Browser。
|
||||
- **中期**:DAP 适配器包装现有 debug session API(`src/view/debug_api.rs` 语义),避免第三套断点模型。
|
||||
|
||||
## OKF / catalog(P3)
|
||||
|
||||
- 命令触发 `marqdo catalog <workspace> -o .marqdo`。
|
||||
- 生成物已在语言仓 `.gitignore`(`.marqdo/`);扩展只负责调用与打开 `index.md` / `catalog.yaml`。
|
||||
|
||||
## 非目标(本阶段)
|
||||
|
||||
- 在扩展内实现完整树遍历 / 字节码
|
||||
- 替代 `marqdo view` 静态站
|
||||
- 强制用户登录或云服务
|
||||
@@ -0,0 +1,67 @@
|
||||
# 开发流程
|
||||
|
||||
## 环境
|
||||
|
||||
- Node.js 20+(LTS)
|
||||
- VS Code 1.85+(`engines.vscode` 在 `package.json` 收紧)
|
||||
- 本机已安装 **Marqdo CLI ≥ 0.1.0**(`marqdo --version`),用于 Run / catalog 集成
|
||||
|
||||
## 首次
|
||||
|
||||
```bash
|
||||
git checkout vscode-extension
|
||||
cd vscode-extension
|
||||
npm install
|
||||
```
|
||||
|
||||
**推荐**:用 VS Code / Cursor **打开 `vscode-extension/` 文件夹**(不要只开仓库根),再按 F5(「Run Extension」)。Extension Development Host 会带上上级语言仓,便于打开 `public/*.mq.md` 验收。
|
||||
|
||||
验证:Language Mode = Marqdo;命令面板搜 `Marqdo: Run File` / `Open Debugger`。
|
||||
|
||||
## 日常脚本(约定)
|
||||
|
||||
| npm script | 用途 |
|
||||
|------------|------|
|
||||
| `npm run compile` | `tsc -p .` → `out/` |
|
||||
| `npm run watch` | 监视编译 |
|
||||
| `npm run lint` | 日后 ESLint(先可空) |
|
||||
| `npm run package` | `vsce package` 打 `.vsix`(发布前) |
|
||||
|
||||
尚未加入的脚本:落地 `package.json` 时按上表补齐,勿引入与 Marqdo 语言仓抢戏的重型框架。
|
||||
|
||||
## 改语法 / 高亮
|
||||
|
||||
1. 对照语言仓 `doc/design/markdown-mapping.md`(以 `main` 为准)。
|
||||
2. 改 `syntaxes/*.tmLanguage.json`(或等价)。
|
||||
3. 用 `tests/` 与 `public/` 下真实 `.mq.md` 肉眼验收(Extension Host 打开语言仓 worktree)。
|
||||
|
||||
## 改 CLI 集成
|
||||
|
||||
- 子进程调用 `marqdo`,cwd = 工作区根或文件目录(与 `marqdo run` 导入/`lib/` 解析一致)。
|
||||
- 解析 stderr 的 `path:line:col: message` 写入 `DiagnosticCollection`。
|
||||
- **禁止**在扩展内重新实现解释器。
|
||||
|
||||
## 提交与推送
|
||||
|
||||
只在 **`vscode-extension` 分支** 提交本目录:
|
||||
|
||||
```bash
|
||||
git status # 确认在 vscode-extension
|
||||
git add vscode-extension
|
||||
git commit -m "…"
|
||||
git push -u origin vscode-extension
|
||||
```
|
||||
|
||||
不要把本目录合并进 `main`(`main` 的 `.gitignore` 会忽略它)。
|
||||
|
||||
## 验收清单(P0 / P1)
|
||||
|
||||
- [ ] `.mq.md` 打开后 Language Mode = Marqdo
|
||||
- [ ] `#` / `*` / `**` / `>` / 表格 / 注释行有可区分着色
|
||||
- [ ] 函数体内 `---` / `***`、空返回 `****` 不与普通 Markdown 粗体完全糊成一团(尽力)
|
||||
- [ ] F5 开发宿主可重复加载,无激活期未捕获异常
|
||||
- [ ] `Marqdo: Run File` 成功时 Output 有输出;失败时 Problems 出现 `path:line:col`
|
||||
- [ ] `Marqdo: Open Debugger` 拉起本地 debug 页(默认 `http://127.0.0.1:7430/`)
|
||||
- [ ] 无 CLI 时启动提示 Install;确认后下载 bundle(含 stdlib)并可 `Run File`
|
||||
|
||||
设置:`marqdo.cliPath`、`marqdo.libPath`、`marqdo.autoInstall.checkOnStartup`、`marqdo.debugOpen`。
|
||||
@@ -0,0 +1,109 @@
|
||||
# VS Code 扩展(分支工作区)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **三按钮 Run / View / Debug + CLI 检测**(扩展 v0.0.5;封面 logo;需 CLI ≥ **0.1.0**) |
|
||||
| 日期 | 2026-08-05 |
|
||||
| 语言仓 | [`cflmy/marqdo`](https://github.com/cflmy/marqdo) `main` |
|
||||
| 扩展仓形态 | **同仓库专用分支** `vscode-extension`(本目录);`main` **不跟踪**本目录 |
|
||||
|
||||
---
|
||||
|
||||
## 1. 与 `public` / `gh-pages` 的类比
|
||||
|
||||
| | `public/` 用户站 | `vscode-extension/` |
|
||||
|--|------------------|---------------------|
|
||||
| **main** | 跟踪可执行 `.mq.md` 源 | **忽略**本目录(不进 `main` 历史) |
|
||||
| **专用分支** | `gh-pages`:生成 HTML | **`vscode-extension`**:扩展源码与规范 |
|
||||
| **消费者** | 浏览器 / Pages | VS Code / Open VSX / Marketplace(日后) |
|
||||
|
||||
开发扩展时:
|
||||
|
||||
```bash
|
||||
git fetch origin
|
||||
git checkout vscode-extension
|
||||
cd vscode-extension
|
||||
npm install
|
||||
```
|
||||
|
||||
回到语言本体:
|
||||
|
||||
```bash
|
||||
git checkout main
|
||||
```
|
||||
|
||||
可选:`git worktree add ../marqdo-vscode vscode-extension`,语言与扩展并行目录开发。
|
||||
|
||||
---
|
||||
|
||||
## 2. 目标(对齐 v0.1.0 分发)
|
||||
|
||||
v0.1.0 已是「可解释 + view + debug CLI + catalog」的阶段性稳定小版本。扩展的第一阶段目标是 **编辑体验**,而不是一次做满 IDE:
|
||||
|
||||
| 优先级 | 能力 | 说明 |
|
||||
|--------|------|------|
|
||||
| **P0** | `.mq.md` 语言登记 + 基础语法高亮 | TextMate(已落地) |
|
||||
| **P0** | 语言配置 | 括号 / 自动成对(已落地) |
|
||||
| **P1** | 任务 / 命令 | `Marqdo: Run File` → `marqdo run`(已落地) |
|
||||
| **P1** | 问题面板 | CLI `path:line:col` → Problems(已落地) |
|
||||
| **P2** | 轻量语言特性 | 大纲(`#` 函数)、跳转到定义(同文件 / 导入) |
|
||||
| **P3** | DAP / 调试 | 现已:`Marqdo: Open Debugger` 拉起 CLI debug 页;日后 DAP |
|
||||
| **P3** | OKF / catalog | `Marqdo: Generate Catalog`(已落地轻量入口) |
|
||||
|
||||
原则:**扩展是 Marqdo CLI 的薄宿主**;语义以解释器与 [markdown-mapping.md](../doc/design/markdown-mapping.md) 为准,扩展不发明第二套语法。
|
||||
|
||||
---
|
||||
|
||||
## 3. 目录约定(本分支)
|
||||
|
||||
```
|
||||
vscode-extension/
|
||||
README.md # 本文件:分支模型与目标
|
||||
DEVELOPMENT.md # 日常开发流程、脚本、验收
|
||||
ARCHITECTURE.md # 进程边界、与 CLI 的契约
|
||||
package.json # 扩展清单(Marketplace id 待定)
|
||||
tsconfig.json
|
||||
.vscode/ # F5:Run Extension
|
||||
.vscodeignore
|
||||
src/
|
||||
extension.ts # activate:命令 / 诊断
|
||||
cli.ts # spawn marqdo
|
||||
diagnostics.ts # path:line:col → Problems
|
||||
syntaxes/ # TextMate 语法(P0)
|
||||
marqdo.tmLanguage.json
|
||||
language-configuration.json
|
||||
```
|
||||
|
||||
生成物(`out/`、`node_modules/`、`*.vsix`)不入库;见本目录 `.gitignore`。
|
||||
|
||||
---
|
||||
|
||||
## 4. 命名与发布(待拍板)
|
||||
|
||||
| 项 | 建议(可改) |
|
||||
|----|--------------|
|
||||
| 扩展显示名 | Marqdo |
|
||||
| `publisher` | `cflmy`(或组织账号) |
|
||||
| `name`(包名) | `marqdo` |
|
||||
| 语言 id | `marqdo` |
|
||||
| 文件关联 | `*.mq.md` |
|
||||
|
||||
发布渠道:先私有 / Open VSX,再 VS Marketplace。版本号与语言仓 **不必锁死同一 semver**,但发行说明应写明「需要 Marqdo CLI ≥ 0.1.0」。
|
||||
|
||||
---
|
||||
|
||||
## 5. 文档索引(语言仓 `main`)
|
||||
|
||||
在 `main` 上仅保留指针,避免扩展实现泄漏进语言历史:
|
||||
|
||||
- [doc/design/vscode-extension.md](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension.md)(`main` 上的分支说明)
|
||||
- 语法:[markdown-mapping.md](https://github.com/cflmy/marqdo/blob/main/doc/design/markdown-mapping.md)
|
||||
- 诊断:[pipeline-debug.md](https://github.com/cflmy/marqdo/blob/main/doc/design/pipeline-debug.md)
|
||||
- CLI debug:[view-debug.md](https://github.com/cflmy/marqdo/blob/main/doc/design/view-debug.md)
|
||||
- Catalog / OKF:[catalog-cli.md](https://github.com/cflmy/marqdo/blob/main/doc/design/catalog-cli.md)
|
||||
|
||||
---
|
||||
|
||||
## 6. 一句话
|
||||
|
||||
**语言在 `main`;编辑器宿主在 `vscode-extension` 分支。先高亮与 run/诊断,再 LSP/DAP;始终以 CLI 为真相源。**
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"comments": {
|
||||
"lineComment": null,
|
||||
"blockComment": null
|
||||
},
|
||||
"brackets": [
|
||||
["{", "}"],
|
||||
["[", "]"],
|
||||
["(", ")"]
|
||||
],
|
||||
"autoClosingPairs": [
|
||||
{ "open": "{", "close": "}" },
|
||||
{ "open": "[", "close": "]" },
|
||||
{ "open": "(", "close": ")" },
|
||||
{ "open": "`", "close": "`" },
|
||||
{ "open": "*", "close": "*" }
|
||||
],
|
||||
"surroundingPairs": [
|
||||
["{", "}"],
|
||||
["[", "]"],
|
||||
["(", ")"],
|
||||
["`", "`"],
|
||||
["*", "*"]
|
||||
],
|
||||
"onEnterRules": [
|
||||
{
|
||||
"beforeText": "^\\s*>\\s+\\S+.*$",
|
||||
"action": { "indent": "indent" }
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 262 B |
Generated
+3853
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,262 @@
|
||||
{
|
||||
"name": "marqdo",
|
||||
"displayName": "Marqdo",
|
||||
"description": "Language support for Marqdo (.mq.md) — code as documentation.",
|
||||
"version": "2.8.0",
|
||||
"publisher": "cflmy",
|
||||
"icon": "media/icon.png",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/cflmy/marqdo.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/cflmy/marqdo/issues"
|
||||
},
|
||||
"homepage": "https://github.com/cflmy/marqdo/tree/main/vscode-extension",
|
||||
"engines": {
|
||||
"vscode": "^1.85.0"
|
||||
},
|
||||
"categories": [
|
||||
"Programming Languages"
|
||||
],
|
||||
"keywords": [
|
||||
"marqdo",
|
||||
"markdown",
|
||||
"mq.md"
|
||||
],
|
||||
"activationEvents": [
|
||||
"onLanguage:marqdo",
|
||||
"onStartupFinished"
|
||||
],
|
||||
"main": "./out/extension.js",
|
||||
"contributes": {
|
||||
"languages": [
|
||||
{
|
||||
"id": "marqdo",
|
||||
"aliases": [
|
||||
"Marqdo",
|
||||
"marqdo"
|
||||
],
|
||||
"extensions": [
|
||||
".mq.md"
|
||||
],
|
||||
"filenamePatterns": [
|
||||
"*.mq.md"
|
||||
],
|
||||
"configuration": "./language-configuration.json"
|
||||
}
|
||||
],
|
||||
"grammars": [
|
||||
{
|
||||
"language": "marqdo",
|
||||
"scopeName": "source.marqdo",
|
||||
"path": "./syntaxes/marqdo.tmLanguage.json"
|
||||
}
|
||||
],
|
||||
"commands": [
|
||||
{
|
||||
"command": "marqdo.run",
|
||||
"title": "Run File",
|
||||
"shortTitle": "Run",
|
||||
"category": "Marqdo",
|
||||
"icon": "$(play)"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.view",
|
||||
"title": "Open View",
|
||||
"shortTitle": "View",
|
||||
"category": "Marqdo",
|
||||
"icon": "$(open-preview)"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.debug",
|
||||
"title": "Open Debugger",
|
||||
"shortTitle": "Debug",
|
||||
"category": "Marqdo",
|
||||
"icon": "$(debug-alt)"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.view.stop",
|
||||
"title": "Stop View",
|
||||
"category": "Marqdo",
|
||||
"icon": "$(close)"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.debug.stop",
|
||||
"title": "Stop Debugger",
|
||||
"shortTitle": "Stop Debug",
|
||||
"category": "Marqdo",
|
||||
"icon": "$(debug-stop)"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.catalog",
|
||||
"title": "Generate Catalog",
|
||||
"category": "Marqdo",
|
||||
"icon": "$(book)"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.showOutput",
|
||||
"title": "Show Output",
|
||||
"category": "Marqdo",
|
||||
"icon": "$(output)"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.installCli",
|
||||
"title": "Install / Repair CLI",
|
||||
"category": "Marqdo",
|
||||
"icon": "$(cloud-download)"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.checkCli",
|
||||
"title": "Check CLI Status",
|
||||
"category": "Marqdo",
|
||||
"icon": "$(info)"
|
||||
}
|
||||
],
|
||||
"menus": {
|
||||
"editor/title": [
|
||||
{
|
||||
"command": "marqdo.run",
|
||||
"when": "editorLangId == marqdo || resourceFilename =~ /\\.mq\\.md$/",
|
||||
"group": "navigation@90"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.view",
|
||||
"when": "editorLangId == marqdo || resourceFilename =~ /\\.mq\\.md$/",
|
||||
"group": "navigation@91"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.debug",
|
||||
"when": "editorLangId == marqdo || resourceFilename =~ /\\.mq\\.md$/",
|
||||
"group": "navigation@92"
|
||||
}
|
||||
],
|
||||
"commandPalette": [
|
||||
{
|
||||
"command": "marqdo.run",
|
||||
"when": "editorLangId == marqdo || resourceFilename =~ /\\.mq\\.md$/"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.view",
|
||||
"when": "editorLangId == marqdo || resourceFilename =~ /\\.mq\\.md$/"
|
||||
},
|
||||
{
|
||||
"command": "marqdo.debug",
|
||||
"when": "editorLangId == marqdo || resourceFilename =~ /\\.mq\\.md$/"
|
||||
}
|
||||
]
|
||||
},
|
||||
"keybindings": [
|
||||
{
|
||||
"command": "marqdo.run",
|
||||
"key": "ctrl+shift+r",
|
||||
"mac": "cmd+shift+r",
|
||||
"when": "editorTextFocus && editorLangId == marqdo"
|
||||
}
|
||||
],
|
||||
"configuration": {
|
||||
"title": "Marqdo",
|
||||
"properties": {
|
||||
"marqdo.cliPath": {
|
||||
"type": "string",
|
||||
"default": "marqdo",
|
||||
"description": "Path to the marqdo CLI executable (default: marqdo on PATH, or extension-managed install)."
|
||||
},
|
||||
"marqdo.managedCliPath": {
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"description": "Path written by Marqdo: Install / Repair CLI (managed binary)."
|
||||
},
|
||||
"marqdo.libPath": {
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"description": "Standard library root (sets MARQDO_LIB when spawning the CLI)."
|
||||
},
|
||||
"marqdo.autoInstall.checkOnStartup": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "On startup, detect missing/outdated CLI or missing stdlib and offer install from GitHub Releases."
|
||||
},
|
||||
"marqdo.minCliVersion": {
|
||||
"type": "string",
|
||||
"default": "0.1.2",
|
||||
"description": "Minimum required Marqdo CLI version (semver). Older installs trigger an upgrade prompt."
|
||||
},
|
||||
"marqdo.autoInstall.checkUpdates": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Periodically check GitHub Releases for newer CLI / extension versions."
|
||||
},
|
||||
"marqdo.diagnoseOnSave": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Run `marqdo run` on save to refresh Problems (may hang on interactive input)."
|
||||
},
|
||||
"marqdo.runTimeoutMs": {
|
||||
"type": "number",
|
||||
"default": 60000,
|
||||
"description": "Timeout for `marqdo run` / diagnose (milliseconds)."
|
||||
},
|
||||
"marqdo.viewHost": {
|
||||
"type": "string",
|
||||
"default": "127.0.0.1",
|
||||
"description": "Host for `marqdo view`."
|
||||
},
|
||||
"marqdo.viewPort": {
|
||||
"type": "number",
|
||||
"default": 7429,
|
||||
"description": "Port for `marqdo view`."
|
||||
},
|
||||
"marqdo.viewOpen": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"external",
|
||||
"simpleBrowser"
|
||||
],
|
||||
"default": "external",
|
||||
"description": "How to open the view UI after starting the server."
|
||||
},
|
||||
"marqdo.debugHost": {
|
||||
"type": "string",
|
||||
"default": "127.0.0.1",
|
||||
"description": "Host for `marqdo debug`."
|
||||
},
|
||||
"marqdo.debugPort": {
|
||||
"type": "number",
|
||||
"default": 7430,
|
||||
"description": "Port for `marqdo debug`."
|
||||
},
|
||||
"marqdo.debugOpen": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"external",
|
||||
"simpleBrowser"
|
||||
],
|
||||
"default": "external",
|
||||
"description": "How to open the debug UI after starting the server."
|
||||
},
|
||||
"marqdo.catalogOut": {
|
||||
"type": "string",
|
||||
"default": ".marqdo",
|
||||
"description": "Output directory for `marqdo catalog`."
|
||||
}
|
||||
}
|
||||
},
|
||||
"configurationDefaults": {
|
||||
"files.associations": {
|
||||
"*.mq.md": "marqdo"
|
||||
}
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"vscode:prepublish": "npm run compile",
|
||||
"compile": "tsc -p ./",
|
||||
"watch": "tsc -watch -p ./"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.0",
|
||||
"@types/vscode": "^1.85.0",
|
||||
"@vscode/vsce": "^3.9.2",
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import * as vscode from "vscode";
|
||||
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "child_process";
|
||||
import type { ExtensionContext } from "vscode";
|
||||
|
||||
export interface CliResult {
|
||||
code: number | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
|
||||
let resolveCli: (() => string) | undefined;
|
||||
let resolveLib: (() => string | undefined) | undefined;
|
||||
|
||||
/** Wire install-aware path resolution from extension activate. */
|
||||
export function configureCliResolution(
|
||||
_context: ExtensionContext,
|
||||
cli: () => string,
|
||||
lib: () => string | undefined
|
||||
): void {
|
||||
resolveCli = cli;
|
||||
resolveLib = lib;
|
||||
}
|
||||
|
||||
function configuredPath(): string {
|
||||
return (
|
||||
vscode.workspace.getConfiguration("marqdo").get<string>("cliPath")?.trim() ||
|
||||
"marqdo"
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveMarqdoCli(): string {
|
||||
if (resolveCli) {
|
||||
return resolveCli();
|
||||
}
|
||||
return configuredPath();
|
||||
}
|
||||
|
||||
function spawnEnv(): NodeJS.ProcessEnv {
|
||||
const env = { ...process.env };
|
||||
const lib = resolveLib?.();
|
||||
if (lib) {
|
||||
env.MARQDO_LIB = lib;
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
export function workspaceCwd(prefer?: vscode.Uri): string {
|
||||
if (prefer) {
|
||||
const folder = vscode.workspace.getWorkspaceFolder(prefer);
|
||||
if (folder) {
|
||||
return folder.uri.fsPath;
|
||||
}
|
||||
return vscode.Uri.joinPath(prefer, "..").fsPath;
|
||||
}
|
||||
return vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? process.cwd();
|
||||
}
|
||||
|
||||
export function runMarqdo(
|
||||
args: string[],
|
||||
options: { cwd: string; timeoutMs?: number }
|
||||
): Promise<CliResult> {
|
||||
const cli = resolveMarqdoCli();
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn(cli, args, {
|
||||
cwd: options.cwd,
|
||||
shell: process.platform === "win32",
|
||||
env: spawnEnv(),
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let settled = false;
|
||||
const finish = (code: number | null) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
resolve({ code, stdout, stderr });
|
||||
};
|
||||
const timer =
|
||||
options.timeoutMs && options.timeoutMs > 0
|
||||
? setTimeout(() => {
|
||||
child.kill();
|
||||
finish(null);
|
||||
}, options.timeoutMs)
|
||||
: undefined;
|
||||
child.stdout.on("data", (d: Buffer) => {
|
||||
stdout += d.toString();
|
||||
});
|
||||
child.stderr.on("data", (d: Buffer) => {
|
||||
stderr += d.toString();
|
||||
});
|
||||
child.on("error", (err) => {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
stderr += err.message;
|
||||
finish(1);
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
finish(code);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function probeMarqdo(
|
||||
cliOverride?: string
|
||||
): { ok: boolean; version?: string; detail: string } {
|
||||
const cli = cliOverride ?? resolveMarqdoCli();
|
||||
try {
|
||||
const r = spawnSync(cli, ["--version"], {
|
||||
encoding: "utf8",
|
||||
shell: process.platform === "win32",
|
||||
timeout: 8000,
|
||||
env: spawnEnv(),
|
||||
});
|
||||
const out = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
|
||||
if (r.error) {
|
||||
return { ok: false, detail: r.error.message };
|
||||
}
|
||||
if (r.status !== 0) {
|
||||
return { ok: false, detail: out || `exit ${r.status}` };
|
||||
}
|
||||
return { ok: true, version: out, detail: out };
|
||||
} catch (e) {
|
||||
return { ok: false, detail: e instanceof Error ? e.message : String(e) };
|
||||
}
|
||||
}
|
||||
|
||||
export class LiveServer {
|
||||
private proc: ChildProcessWithoutNullStreams | null = null;
|
||||
private output: vscode.OutputChannel;
|
||||
private label: string;
|
||||
|
||||
constructor(output: vscode.OutputChannel, label: string) {
|
||||
this.output = output;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
get running(): boolean {
|
||||
return this.proc !== null && this.proc.exitCode === null;
|
||||
}
|
||||
|
||||
async start(
|
||||
subcommand: "view" | "debug",
|
||||
targetPath: string,
|
||||
host: string,
|
||||
port: number
|
||||
): Promise<string> {
|
||||
if (this.running) {
|
||||
await this.stop();
|
||||
}
|
||||
const cli = resolveMarqdoCli();
|
||||
const cwd = workspaceCwd(vscode.Uri.file(targetPath));
|
||||
this.output.appendLine(
|
||||
`$ ${cli} ${subcommand} ${targetPath} --host ${host} --port ${port} --no-open`
|
||||
);
|
||||
this.proc = spawn(
|
||||
cli,
|
||||
[subcommand, targetPath, "--host", host, "--port", String(port), "--no-open"],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
env: spawnEnv(),
|
||||
}
|
||||
);
|
||||
const url = `http://${host}:${port}/`;
|
||||
this.proc.stdout.on("data", (d: Buffer) => this.output.append(d.toString()));
|
||||
this.proc.stderr.on("data", (d: Buffer) => this.output.append(d.toString()));
|
||||
this.proc.on("exit", (code) => {
|
||||
this.output.appendLine(`[${this.label}] exited (${code})`);
|
||||
this.proc = null;
|
||||
});
|
||||
this.proc.on("error", (err) => {
|
||||
this.output.appendLine(`[${this.label}] ${err.message}`);
|
||||
this.proc = null;
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
return url;
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (!this.proc) {
|
||||
return;
|
||||
}
|
||||
const p = this.proc;
|
||||
this.proc = null;
|
||||
p.kill();
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import * as vscode from "vscode";
|
||||
import * as path from "path";
|
||||
|
||||
export function parseDiagnostics(
|
||||
text: string,
|
||||
fallbackUri: vscode.Uri,
|
||||
cwd: string
|
||||
): vscode.Diagnostic[] {
|
||||
const out: vscode.Diagnostic[] = [];
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (!line) {
|
||||
continue;
|
||||
}
|
||||
const parsed = parseDiagLine(line);
|
||||
if (!parsed) {
|
||||
continue;
|
||||
}
|
||||
out.push(
|
||||
makeDiag(parsed.file, parsed.line, parsed.col, parsed.message, fallbackUri, cwd)
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseDiagLine(
|
||||
line: string
|
||||
): { file: string; line: number; col: number; message: string } | undefined {
|
||||
// Windows: E:\path\to\file.mq.md:7:1: message
|
||||
const win = /^([A-Za-z]:[\\/][^:]*):(\d+):(\d+):\s*(.+)$/.exec(line);
|
||||
if (win) {
|
||||
return {
|
||||
file: win[1],
|
||||
line: Number(win[2]),
|
||||
col: Number(win[3]),
|
||||
message: win[4],
|
||||
};
|
||||
}
|
||||
// Unix / relative: path/file.mq.md:7:1: message
|
||||
const normal = /^(.+):(\d+):(\d+):\s*(.+)$/.exec(line);
|
||||
if (normal) {
|
||||
return {
|
||||
file: normal[1],
|
||||
line: Number(normal[2]),
|
||||
col: Number(normal[3]),
|
||||
message: normal[4],
|
||||
};
|
||||
}
|
||||
const spanOnly = /^(\d+):(\d+):\s*(.+)$/.exec(line);
|
||||
if (spanOnly) {
|
||||
return {
|
||||
file: "",
|
||||
line: Number(spanOnly[1]),
|
||||
col: Number(spanOnly[2]),
|
||||
message: spanOnly[3],
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function makeDiag(
|
||||
filePath: string,
|
||||
line1: number,
|
||||
col1: number,
|
||||
message: string,
|
||||
fallbackUri: vscode.Uri,
|
||||
cwd: string
|
||||
): vscode.Diagnostic {
|
||||
const line = Math.max(0, line1 - 1);
|
||||
const col = Math.max(0, col1 - 1);
|
||||
const range = new vscode.Range(line, col, line, Math.max(col + 1, col));
|
||||
const diag = new vscode.Diagnostic(range, message, vscode.DiagnosticSeverity.Error);
|
||||
diag.source = "marqdo";
|
||||
(diag as vscode.Diagnostic & { targetPath?: string }).targetPath = resolvePath(
|
||||
filePath,
|
||||
fallbackUri,
|
||||
cwd
|
||||
);
|
||||
return diag;
|
||||
}
|
||||
|
||||
function resolvePath(filePath: string, fallbackUri: vscode.Uri, cwd: string): string {
|
||||
if (!filePath) {
|
||||
return fallbackUri.fsPath;
|
||||
}
|
||||
if (path.isAbsolute(filePath)) {
|
||||
return filePath;
|
||||
}
|
||||
return path.resolve(cwd, filePath);
|
||||
}
|
||||
|
||||
export class DiagnosticBag {
|
||||
private readonly collection: vscode.DiagnosticCollection;
|
||||
|
||||
constructor() {
|
||||
this.collection = vscode.languages.createDiagnosticCollection("marqdo");
|
||||
}
|
||||
|
||||
get disposable(): vscode.Disposable {
|
||||
return this.collection;
|
||||
}
|
||||
|
||||
clear(uri?: vscode.Uri): void {
|
||||
if (uri) {
|
||||
this.collection.delete(uri);
|
||||
} else {
|
||||
this.collection.clear();
|
||||
}
|
||||
}
|
||||
|
||||
setFromCli(text: string, fallbackUri: vscode.Uri, cwd: string): void {
|
||||
const parsed = parseDiagnostics(text, fallbackUri, cwd);
|
||||
const byFile = new Map<string, vscode.Diagnostic[]>();
|
||||
for (const d of parsed) {
|
||||
const target =
|
||||
(d as vscode.Diagnostic & { targetPath?: string }).targetPath ?? fallbackUri.fsPath;
|
||||
const list = byFile.get(target) ?? [];
|
||||
list.push(d);
|
||||
byFile.set(target, list);
|
||||
}
|
||||
if (byFile.size === 0) {
|
||||
const trimmed = text.trim();
|
||||
if (trimmed) {
|
||||
const range = new vscode.Range(0, 0, 0, 1);
|
||||
this.collection.set(fallbackUri, [
|
||||
new vscode.Diagnostic(
|
||||
range,
|
||||
trimmed.split(/\r?\n/)[0],
|
||||
vscode.DiagnosticSeverity.Error
|
||||
),
|
||||
]);
|
||||
} else {
|
||||
this.collection.delete(fallbackUri);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const [file, diags] of byFile) {
|
||||
this.collection.set(vscode.Uri.file(file), diags);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
import * as vscode from "vscode";
|
||||
import { LiveServer, configureCliResolution, runMarqdo, workspaceCwd } from "./cli";
|
||||
import { DiagnosticBag } from "./diagnostics";
|
||||
import {
|
||||
checkInstallStatus,
|
||||
installFromGitHub,
|
||||
promptIfNeeded,
|
||||
resetSkipPrompt,
|
||||
resolveCliPath,
|
||||
resolveLibEnv,
|
||||
} from "./install";
|
||||
import { checkForUpdates } from "./updateCheck";
|
||||
|
||||
let output: vscode.OutputChannel;
|
||||
let diagnostics: DiagnosticBag;
|
||||
let viewServer: LiveServer;
|
||||
let debugServer: LiveServer;
|
||||
let extContext: vscode.ExtensionContext;
|
||||
|
||||
export function activate(context: vscode.ExtensionContext): void {
|
||||
extContext = context;
|
||||
output = vscode.window.createOutputChannel("Marqdo");
|
||||
diagnostics = new DiagnosticBag();
|
||||
viewServer = new LiveServer(output, "view");
|
||||
debugServer = new LiveServer(output, "debug");
|
||||
|
||||
configureCliResolution(
|
||||
context,
|
||||
() => resolveCliPath(context),
|
||||
() => resolveLibEnv(context)
|
||||
);
|
||||
|
||||
context.subscriptions.push(
|
||||
output,
|
||||
diagnostics.disposable,
|
||||
vscode.commands.registerCommand("marqdo.run", () => runActiveFile()),
|
||||
vscode.commands.registerCommand("marqdo.view", () => startView()),
|
||||
vscode.commands.registerCommand("marqdo.debug", () => startDebug()),
|
||||
vscode.commands.registerCommand("marqdo.debug.stop", () => stopDebug()),
|
||||
vscode.commands.registerCommand("marqdo.view.stop", () => stopView()),
|
||||
vscode.commands.registerCommand("marqdo.catalog", () => runCatalog()),
|
||||
vscode.commands.registerCommand("marqdo.showOutput", () => output.show(true)),
|
||||
vscode.commands.registerCommand("marqdo.installCli", () => installCli()),
|
||||
vscode.commands.registerCommand("marqdo.checkCli", () => checkCli())
|
||||
);
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.workspace.onDidSaveTextDocument((doc) => {
|
||||
if (doc.languageId === "marqdo" && autoDiagnose()) {
|
||||
void diagnoseDocument(doc);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
void (async () => {
|
||||
await promptIfNeeded(context, output);
|
||||
const status = checkInstallStatus(context);
|
||||
await checkForUpdates(context, output, status.version);
|
||||
})();
|
||||
}
|
||||
|
||||
export function deactivate(): void {
|
||||
void viewServer?.stop();
|
||||
void debugServer?.stop();
|
||||
}
|
||||
|
||||
function autoDiagnose(): boolean {
|
||||
return vscode.workspace.getConfiguration("marqdo").get<boolean>("diagnoseOnSave") ?? false;
|
||||
}
|
||||
|
||||
async function installCli(): Promise<void> {
|
||||
await resetSkipPrompt(extContext);
|
||||
const status = checkInstallStatus(extContext);
|
||||
try {
|
||||
const mode = status.suggestedMode ?? "bundle";
|
||||
await installFromGitHub(extContext, output, mode);
|
||||
} catch (e) {
|
||||
const err = e instanceof Error ? e.message : String(e);
|
||||
output.appendLine(`[install] ${err}`);
|
||||
const open = await vscode.window.showErrorMessage(`Marqdo install failed: ${err}`, "Open Releases");
|
||||
if (open) {
|
||||
await vscode.env.openExternal(vscode.Uri.parse("https://github.com/cflmy/marqdo/releases"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function checkCli(): Promise<void> {
|
||||
const status = checkInstallStatus(extContext);
|
||||
output.appendLine(`[check] ${status.detail}`);
|
||||
if (status.cliOk && status.versionOk && status.libOk) {
|
||||
void vscode.window.showInformationMessage(
|
||||
`Marqdo ready: ${status.parsedVersion ?? status.version} (≥ ${status.requiredVersion}), stdlib OK`
|
||||
);
|
||||
return;
|
||||
}
|
||||
const choice = await vscode.window.showWarningMessage(
|
||||
status.detail,
|
||||
"Install / Repair",
|
||||
"Open Releases"
|
||||
);
|
||||
if (choice === "Install / Repair") {
|
||||
await installCli();
|
||||
} else if (choice === "Open Releases") {
|
||||
await vscode.env.openExternal(vscode.Uri.parse("https://github.com/cflmy/marqdo/releases"));
|
||||
}
|
||||
}
|
||||
|
||||
function activeMqDoc(): vscode.TextDocument | undefined {
|
||||
const doc = vscode.window.activeTextEditor?.document;
|
||||
if (!doc) {
|
||||
return undefined;
|
||||
}
|
||||
if (doc.languageId === "marqdo" || doc.fileName.endsWith(".mq.md")) {
|
||||
return doc;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function ensureCliOrOfferInstall(): Promise<boolean> {
|
||||
const status = checkInstallStatus(extContext);
|
||||
if (status.cliOk && status.versionOk && status.libOk) {
|
||||
return true;
|
||||
}
|
||||
if (status.cliOk && status.versionOk && !status.libOk) {
|
||||
const choice = await vscode.window.showWarningMessage(
|
||||
"Standard library (lib/) is missing. Continue anyway, or install stdlib?",
|
||||
"Install stdlib",
|
||||
"Continue",
|
||||
"Cancel"
|
||||
);
|
||||
if (choice === "Install stdlib") {
|
||||
await installCli();
|
||||
return true;
|
||||
}
|
||||
if (choice === "Continue") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const label = !status.cliOk
|
||||
? "Marqdo CLI not found. Install the official release (includes stdlib)?"
|
||||
: `Marqdo CLI is below ${status.requiredVersion}. Upgrade now?`;
|
||||
const choice = await vscode.window.showWarningMessage(label, "Install", "Cancel");
|
||||
if (choice === "Install") {
|
||||
await installCli();
|
||||
const again = checkInstallStatus(extContext);
|
||||
return again.cliOk && again.versionOk;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function resolveTargetPath(): string | undefined {
|
||||
const doc = activeMqDoc();
|
||||
const folder = vscode.workspace.workspaceFolders?.[0];
|
||||
return doc?.uri.fsPath ?? folder?.uri.fsPath;
|
||||
}
|
||||
|
||||
async function openUrl(url: string, settingKey: "viewOpen" | "debugOpen"): Promise<void> {
|
||||
const open =
|
||||
vscode.workspace.getConfiguration("marqdo").get<string>(settingKey) ?? "external";
|
||||
if (open === "simpleBrowser") {
|
||||
await vscode.commands.executeCommand("simpleBrowser.show", url);
|
||||
} else {
|
||||
await vscode.env.openExternal(vscode.Uri.parse(url));
|
||||
}
|
||||
}
|
||||
|
||||
async function runActiveFile(): Promise<void> {
|
||||
if (!(await ensureCliOrOfferInstall())) {
|
||||
return;
|
||||
}
|
||||
const doc = activeMqDoc();
|
||||
if (!doc) {
|
||||
void vscode.window.showWarningMessage("Open a .mq.md file to run.");
|
||||
return;
|
||||
}
|
||||
if (doc.isDirty) {
|
||||
await doc.save();
|
||||
}
|
||||
const cwd = workspaceCwd(doc.uri);
|
||||
output.show(true);
|
||||
output.appendLine(`$ marqdo run ${doc.uri.fsPath}`);
|
||||
const result = await runMarqdo(["run", doc.uri.fsPath], {
|
||||
cwd,
|
||||
timeoutMs: vscode.workspace.getConfiguration("marqdo").get<number>("runTimeoutMs") ?? 60000,
|
||||
});
|
||||
if (result.stdout.trim()) {
|
||||
output.appendLine(result.stdout.trimEnd());
|
||||
}
|
||||
if (result.stderr.trim()) {
|
||||
output.appendLine(result.stderr.trimEnd());
|
||||
}
|
||||
if (result.code === 0) {
|
||||
diagnostics.clear(doc.uri);
|
||||
void vscode.window.setStatusBarMessage("Marqdo: run ok", 3000);
|
||||
} else {
|
||||
diagnostics.setFromCli(result.stderr || result.stdout, doc.uri, cwd);
|
||||
void vscode.window.showErrorMessage("Marqdo: run failed (see Problems / Output)");
|
||||
}
|
||||
}
|
||||
|
||||
async function diagnoseDocument(doc: vscode.TextDocument): Promise<void> {
|
||||
const cwd = workspaceCwd(doc.uri);
|
||||
const result = await runMarqdo(["run", doc.uri.fsPath], {
|
||||
cwd,
|
||||
timeoutMs: vscode.workspace.getConfiguration("marqdo").get<number>("runTimeoutMs") ?? 60000,
|
||||
});
|
||||
if (result.code === 0) {
|
||||
diagnostics.clear(doc.uri);
|
||||
} else {
|
||||
diagnostics.setFromCli(result.stderr || result.stdout, doc.uri, cwd);
|
||||
}
|
||||
}
|
||||
|
||||
async function startView(): Promise<void> {
|
||||
if (!(await ensureCliOrOfferInstall())) {
|
||||
return;
|
||||
}
|
||||
const target = resolveTargetPath();
|
||||
if (!target) {
|
||||
void vscode.window.showWarningMessage("Open a folder or .mq.md file for view.");
|
||||
return;
|
||||
}
|
||||
const cfg = vscode.workspace.getConfiguration("marqdo");
|
||||
const host = cfg.get<string>("viewHost") ?? "127.0.0.1";
|
||||
const port = cfg.get<number>("viewPort") ?? 7429;
|
||||
output.show(true);
|
||||
try {
|
||||
const url = await viewServer.start("view", target, host, port);
|
||||
await openUrl(url, "viewOpen");
|
||||
void vscode.window.setStatusBarMessage(`Marqdo view: ${url}`, 5000);
|
||||
} catch (e) {
|
||||
void vscode.window.showErrorMessage(
|
||||
`Marqdo view failed: ${e instanceof Error ? e.message : String(e)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function startDebug(): Promise<void> {
|
||||
if (!(await ensureCliOrOfferInstall())) {
|
||||
return;
|
||||
}
|
||||
const target = resolveTargetPath();
|
||||
if (!target) {
|
||||
void vscode.window.showWarningMessage("Open a folder or .mq.md file to debug.");
|
||||
return;
|
||||
}
|
||||
const cfg = vscode.workspace.getConfiguration("marqdo");
|
||||
const host = cfg.get<string>("debugHost") ?? "127.0.0.1";
|
||||
const port = cfg.get<number>("debugPort") ?? 7430;
|
||||
output.show(true);
|
||||
try {
|
||||
const url = await debugServer.start("debug", target, host, port);
|
||||
await openUrl(url, "debugOpen");
|
||||
void vscode.window.setStatusBarMessage(`Marqdo debug: ${url}`, 5000);
|
||||
} catch (e) {
|
||||
void vscode.window.showErrorMessage(
|
||||
`Marqdo debug failed: ${e instanceof Error ? e.message : String(e)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function stopView(): Promise<void> {
|
||||
await viewServer.stop();
|
||||
void vscode.window.setStatusBarMessage("Marqdo view stopped", 3000);
|
||||
}
|
||||
|
||||
async function stopDebug(): Promise<void> {
|
||||
await debugServer.stop();
|
||||
void vscode.window.setStatusBarMessage("Marqdo debug stopped", 3000);
|
||||
}
|
||||
|
||||
async function runCatalog(): Promise<void> {
|
||||
if (!(await ensureCliOrOfferInstall())) {
|
||||
return;
|
||||
}
|
||||
const folder = vscode.workspace.workspaceFolders?.[0];
|
||||
if (!folder) {
|
||||
void vscode.window.showWarningMessage("Open a workspace folder for catalog.");
|
||||
return;
|
||||
}
|
||||
const outDir =
|
||||
vscode.workspace.getConfiguration("marqdo").get<string>("catalogOut") ?? ".marqdo";
|
||||
output.show(true);
|
||||
output.appendLine(`$ marqdo catalog ${folder.uri.fsPath} -o ${outDir}`);
|
||||
const result = await runMarqdo(["catalog", folder.uri.fsPath, "-o", outDir], {
|
||||
cwd: folder.uri.fsPath,
|
||||
timeoutMs: 120000,
|
||||
});
|
||||
if (result.stdout.trim()) {
|
||||
output.appendLine(result.stdout.trimEnd());
|
||||
}
|
||||
if (result.stderr.trim()) {
|
||||
output.appendLine(result.stderr.trimEnd());
|
||||
}
|
||||
if (result.code === 0) {
|
||||
const index = vscode.Uri.joinPath(folder.uri, outDir, "index.md");
|
||||
try {
|
||||
const doc = await vscode.workspace.openTextDocument(index);
|
||||
await vscode.window.showTextDocument(doc, { preview: true });
|
||||
} catch {
|
||||
void vscode.window.showInformationMessage(`Marqdo catalog written to ${outDir}`);
|
||||
}
|
||||
} else {
|
||||
void vscode.window.showErrorMessage("Marqdo catalog failed (see Output)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
import * as vscode from "vscode";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import * as os from "os";
|
||||
import { spawnSync } from "child_process";
|
||||
import { probeMarqdo } from "./cli";
|
||||
|
||||
const REPO = "cflmy/marqdo";
|
||||
const SKIP_KEY = "marqdo.skipInstallPrompt";
|
||||
const MANAGED_DIR = "cli";
|
||||
/** CLI builds from this version ship stdlib inside the binary. */
|
||||
export const EMBEDDED_STDLIB_SINCE = "0.1.2";
|
||||
|
||||
export type InstallStatus = {
|
||||
cliOk: boolean;
|
||||
libOk: boolean;
|
||||
versionOk: boolean;
|
||||
version?: string;
|
||||
parsedVersion?: string;
|
||||
requiredVersion: string;
|
||||
cliPath?: string;
|
||||
libRoot?: string;
|
||||
detail: string;
|
||||
/** Suggested install mode when not fully ready */
|
||||
suggestedMode?: "bundle" | "stdlib";
|
||||
};
|
||||
|
||||
/** Parse first semver-like token from `marqdo --version` output. */
|
||||
export function parseCliVersion(raw: string): string | undefined {
|
||||
const m = raw.match(/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/);
|
||||
return m?.[1];
|
||||
}
|
||||
|
||||
/** Compare a.b.c semver (pre-release suffix ignored for ordering). Returns <0 if a<b. */
|
||||
export function compareSemver(a: string, b: string): number {
|
||||
const pa = a.split("-")[0].split(".").map((x) => Number.parseInt(x, 10) || 0);
|
||||
const pb = b.split("-")[0].split(".").map((x) => Number.parseInt(x, 10) || 0);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
|
||||
if (d !== 0) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function requiredVersion(): string {
|
||||
return cfg().get<string>("minCliVersion")?.trim() || "0.1.0";
|
||||
}
|
||||
|
||||
type GhAsset = { name: string; browser_download_url: string };
|
||||
type GhRelease = {
|
||||
tag_name: string;
|
||||
html_url: string;
|
||||
assets: GhAsset[];
|
||||
};
|
||||
|
||||
function cfg() {
|
||||
return vscode.workspace.getConfiguration("marqdo");
|
||||
}
|
||||
|
||||
export function managedRoot(context: vscode.ExtensionContext): string {
|
||||
return path.join(context.globalStorageUri.fsPath, MANAGED_DIR);
|
||||
}
|
||||
|
||||
export function managedExePath(context: vscode.ExtensionContext): string {
|
||||
const name = process.platform === "win32" ? "marqdo.exe" : "marqdo";
|
||||
return path.join(managedRoot(context), name);
|
||||
}
|
||||
|
||||
export function managedLibRoot(context: vscode.ExtensionContext): string {
|
||||
// Release zip layout: marqdo.exe + lib/… → MARQDO_LIB can be the dir that contains lib/, or lib itself.
|
||||
// load.rs: root.join(remainder) and root.join("lib").join(remainder)
|
||||
return managedRoot(context);
|
||||
}
|
||||
|
||||
/** Prefer explicit setting, then managed install, then PATH. */
|
||||
export function resolveCliPath(context?: vscode.ExtensionContext): string {
|
||||
const setting = cfg().get<string>("cliPath")?.trim() || "marqdo";
|
||||
if (setting !== "marqdo") {
|
||||
return setting;
|
||||
}
|
||||
if (context) {
|
||||
const managed = managedExePath(context);
|
||||
if (fs.existsSync(managed)) {
|
||||
return managed;
|
||||
}
|
||||
}
|
||||
const stored = cfg().get<string>("managedCliPath")?.trim();
|
||||
if (stored && fs.existsSync(stored)) {
|
||||
return stored;
|
||||
}
|
||||
return "marqdo";
|
||||
}
|
||||
|
||||
export function resolveLibEnv(context?: vscode.ExtensionContext): string | undefined {
|
||||
const setting = cfg().get<string>("libPath")?.trim();
|
||||
if (setting) {
|
||||
return setting;
|
||||
}
|
||||
if (context) {
|
||||
const root = managedLibRoot(context);
|
||||
if (fs.existsSync(path.join(root, "lib")) || looksLikeLibRoot(root)) {
|
||||
return root;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function looksLikeLibRoot(root: string): boolean {
|
||||
return (
|
||||
fs.existsSync(path.join(root, "math.mq.md")) ||
|
||||
fs.existsSync(path.join(root, "text.mq.md")) ||
|
||||
fs.existsSync(path.join(root, "lib", "math.mq.md"))
|
||||
);
|
||||
}
|
||||
|
||||
function findExeDir(cliPath: string): string | undefined {
|
||||
if (cliPath.includes(path.sep) || cliPath.includes("/") || /\.exe$/i.test(cliPath)) {
|
||||
if (fs.existsSync(cliPath)) {
|
||||
return path.dirname(cliPath);
|
||||
}
|
||||
}
|
||||
// Resolve via where/which
|
||||
const cmd = process.platform === "win32" ? "where" : "which";
|
||||
const r = spawnSync(cmd, [cliPath === "marqdo" && process.platform === "win32" ? "marqdo.exe" : cliPath], {
|
||||
encoding: "utf8",
|
||||
shell: true,
|
||||
});
|
||||
const first = (r.stdout || "")
|
||||
.split(/\r?\n/)
|
||||
.map((s) => s.trim())
|
||||
.find((s) => s.length > 0);
|
||||
if (first && fs.existsSync(first)) {
|
||||
return path.dirname(first);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function stdlibPresent(cliPath: string, context?: vscode.ExtensionContext): { ok: boolean; root?: string } {
|
||||
const envLib = process.env.MARQDO_LIB;
|
||||
if (envLib && looksLikeLibRoot(envLib)) {
|
||||
return { ok: true, root: envLib };
|
||||
}
|
||||
const configured = resolveLibEnv(context);
|
||||
if (configured && looksLikeLibRoot(configured)) {
|
||||
return { ok: true, root: configured };
|
||||
}
|
||||
const dir = findExeDir(cliPath);
|
||||
if (dir) {
|
||||
if (looksLikeLibRoot(dir) || looksLikeLibRoot(path.join(dir, "lib"))) {
|
||||
return { ok: true, root: dir };
|
||||
}
|
||||
}
|
||||
// Workspace ./lib
|
||||
const ws = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
|
||||
if (ws && looksLikeLibRoot(path.join(ws, "lib"))) {
|
||||
return { ok: true, root: path.join(ws, "lib") };
|
||||
}
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
export function checkInstallStatus(context: vscode.ExtensionContext): InstallStatus {
|
||||
const need = requiredVersion();
|
||||
const cliPath = resolveCliPath(context);
|
||||
const probe = probeMarqdo(cliPath);
|
||||
if (!probe.ok) {
|
||||
return {
|
||||
cliOk: false,
|
||||
libOk: false,
|
||||
versionOk: false,
|
||||
requiredVersion: need,
|
||||
cliPath,
|
||||
detail: `Marqdo CLI not found (${probe.detail}). Need ≥ ${need} with stdlib.`,
|
||||
suggestedMode: "bundle",
|
||||
};
|
||||
}
|
||||
const parsed = parseCliVersion(probe.version ?? "");
|
||||
const versionOk = parsed !== undefined && compareSemver(parsed, need) >= 0;
|
||||
let lib = stdlibPresent(cliPath, context);
|
||||
if (
|
||||
parsed &&
|
||||
compareSemver(parsed, EMBEDDED_STDLIB_SINCE) >= 0 &&
|
||||
!lib.ok
|
||||
) {
|
||||
lib = { ok: true, root: "(embedded in binary)" };
|
||||
}
|
||||
|
||||
let suggestedMode: "bundle" | "stdlib" | undefined;
|
||||
if (!versionOk) {
|
||||
suggestedMode = "bundle";
|
||||
} else if (!lib.ok) {
|
||||
suggestedMode = "stdlib";
|
||||
}
|
||||
|
||||
const parts: string[] = [`CLI ${probe.version}`];
|
||||
if (!versionOk) {
|
||||
parts.push(`version too old (need ≥ ${need}${parsed ? `, found ${parsed}` : ""})`);
|
||||
}
|
||||
if (lib.ok) {
|
||||
parts.push(`stdlib at ${lib.root}`);
|
||||
} else {
|
||||
parts.push("stdlib missing (no lib/ next to binary / MARQDO_LIB)");
|
||||
}
|
||||
|
||||
return {
|
||||
cliOk: true,
|
||||
libOk: lib.ok,
|
||||
versionOk,
|
||||
version: probe.version,
|
||||
parsedVersion: parsed,
|
||||
requiredVersion: need,
|
||||
cliPath,
|
||||
libRoot: lib.root,
|
||||
detail: parts.join("; "),
|
||||
suggestedMode,
|
||||
};
|
||||
}
|
||||
|
||||
function rustTargetTriple(): string | undefined {
|
||||
const { platform, arch } = process;
|
||||
if (platform === "win32" && arch === "x64") {
|
||||
return "x86_64-pc-windows-msvc";
|
||||
}
|
||||
if (platform === "linux" && arch === "x64") {
|
||||
return "x86_64-unknown-linux-gnu";
|
||||
}
|
||||
if (platform === "darwin" && arch === "arm64") {
|
||||
return "aarch64-apple-darwin";
|
||||
}
|
||||
if (platform === "darwin" && arch === "x64") {
|
||||
return "x86_64-apple-darwin";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function fetchLatestRelease(): Promise<GhRelease> {
|
||||
const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, {
|
||||
headers: {
|
||||
Accept: "application/vnd.github+json",
|
||||
"User-Agent": "marqdo-vscode-extension",
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`GitHub releases/latest HTTP ${res.status}`);
|
||||
}
|
||||
return (await res.json()) as GhRelease;
|
||||
}
|
||||
|
||||
async function downloadToFile(url: string, dest: string, onProgress?: (msg: string) => void): Promise<void> {
|
||||
onProgress?.(`Downloading ${path.basename(dest)}…`);
|
||||
const res = await fetch(url, {
|
||||
headers: { "User-Agent": "marqdo-vscode-extension", Accept: "application/octet-stream" },
|
||||
redirect: "follow",
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Download failed HTTP ${res.status}: ${url}`);
|
||||
}
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
||||
fs.writeFileSync(dest, buf);
|
||||
}
|
||||
|
||||
function extractZip(zipPath: string, destDir: string): void {
|
||||
fs.mkdirSync(destDir, { recursive: true });
|
||||
if (process.platform === "win32") {
|
||||
const ps = `Expand-Archive -LiteralPath '${zipPath.replace(/'/g, "''")}' -DestinationPath '${destDir.replace(/'/g, "''")}' -Force`;
|
||||
const r = spawnSync("powershell", ["-NoProfile", "-Command", ps], { encoding: "utf8" });
|
||||
if (r.status !== 0) {
|
||||
throw new Error(r.stderr || r.stdout || `Expand-Archive exit ${r.status}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const r = spawnSync("unzip", ["-o", zipPath, "-d", destDir], { encoding: "utf8" });
|
||||
if (r.status !== 0) {
|
||||
throw new Error(r.stderr || r.stdout || `unzip exit ${r.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
function pickBundleAsset(release: GhRelease, triple: string): GhAsset | undefined {
|
||||
const zipName = `marqdo-${release.tag_name.replace(/^v/, "")}-${triple}.zip`;
|
||||
return (
|
||||
release.assets.find((a) => a.name === zipName) ||
|
||||
release.assets.find(
|
||||
(a) => a.name.endsWith(`-${triple}.zip`) && !a.name.includes("stdlib")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function pickStdlibAsset(release: GhRelease): GhAsset | undefined {
|
||||
return release.assets.find((a) => a.name.includes("stdlib") && a.name.endsWith(".zip"));
|
||||
}
|
||||
|
||||
async function applyManagedPaths(context: vscode.ExtensionContext, exe: string): Promise<void> {
|
||||
await cfg().update("cliPath", exe, vscode.ConfigurationTarget.Global);
|
||||
await cfg().update("managedCliPath", exe, vscode.ConfigurationTarget.Global);
|
||||
await cfg().update("libPath", managedLibRoot(context), vscode.ConfigurationTarget.Global);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download recommended release bundle (exe + lib/) into extension globalStorage.
|
||||
*/
|
||||
export async function installFromGitHub(
|
||||
context: vscode.ExtensionContext,
|
||||
output: vscode.OutputChannel,
|
||||
mode: "bundle" | "stdlib" = "bundle"
|
||||
): Promise<InstallStatus> {
|
||||
const triple = rustTargetTriple();
|
||||
output.show(true);
|
||||
|
||||
return vscode.window.withProgress(
|
||||
{
|
||||
location: vscode.ProgressLocation.Notification,
|
||||
title: "Marqdo",
|
||||
cancellable: false,
|
||||
},
|
||||
async (progress) => {
|
||||
progress.report({ message: "Fetching latest release…" });
|
||||
output.appendLine(`Fetching https://github.com/${REPO}/releases/latest`);
|
||||
const release = await fetchLatestRelease();
|
||||
output.appendLine(`Latest: ${release.tag_name}`);
|
||||
|
||||
const destRoot = managedRoot(context);
|
||||
fs.mkdirSync(destRoot, { recursive: true });
|
||||
const tmp = path.join(os.tmpdir(), `marqdo-ext-${Date.now()}`);
|
||||
fs.mkdirSync(tmp, { recursive: true });
|
||||
|
||||
try {
|
||||
if (mode === "bundle") {
|
||||
if (!triple) {
|
||||
throw new Error(
|
||||
`No prebuilt bundle for ${process.platform}/${process.arch}. Open ${release.html_url} or build from source.`
|
||||
);
|
||||
}
|
||||
const asset = pickBundleAsset(release, triple);
|
||||
if (!asset) {
|
||||
throw new Error(
|
||||
`No asset for ${triple} in ${release.tag_name}. Available: ${release.assets
|
||||
.map((a) => a.name)
|
||||
.join(", ") || "(none)"}. See ${release.html_url}`
|
||||
);
|
||||
}
|
||||
const zipPath = path.join(tmp, asset.name);
|
||||
progress.report({ message: `Downloading ${asset.name}…` });
|
||||
await downloadToFile(asset.browser_download_url, zipPath, (m) => output.appendLine(m));
|
||||
progress.report({ message: "Extracting (CLI + stdlib)…" });
|
||||
// Clear previous managed install
|
||||
fs.rmSync(destRoot, { recursive: true, force: true });
|
||||
fs.mkdirSync(destRoot, { recursive: true });
|
||||
extractZip(zipPath, destRoot);
|
||||
output.appendLine(`Extracted to ${destRoot}`);
|
||||
} else {
|
||||
const asset = pickStdlibAsset(release);
|
||||
if (!asset) {
|
||||
throw new Error(`No stdlib zip in ${release.tag_name}. See ${release.html_url}`);
|
||||
}
|
||||
const zipPath = path.join(tmp, asset.name);
|
||||
progress.report({ message: `Downloading ${asset.name}…` });
|
||||
await downloadToFile(asset.browser_download_url, zipPath, (m) => output.appendLine(m));
|
||||
progress.report({ message: "Extracting stdlib…" });
|
||||
extractZip(zipPath, destRoot);
|
||||
output.appendLine(`Stdlib extracted to ${destRoot}`);
|
||||
}
|
||||
|
||||
const exe = managedExePath(context);
|
||||
if (mode === "bundle" && !fs.existsSync(exe)) {
|
||||
// Some zips might nest a folder
|
||||
const nested = findFileRecursive(destRoot, process.platform === "win32" ? "marqdo.exe" : "marqdo");
|
||||
if (nested) {
|
||||
// Flatten: move exe+lib up if needed is complex; just point cliPath at nested
|
||||
await cfg().update("cliPath", nested, vscode.ConfigurationTarget.Global);
|
||||
await cfg().update("managedCliPath", nested, vscode.ConfigurationTarget.Global);
|
||||
const libCandidate = path.dirname(nested);
|
||||
await cfg().update("libPath", libCandidate, vscode.ConfigurationTarget.Global);
|
||||
} else {
|
||||
throw new Error(`Extracted archive but ${exe} not found`);
|
||||
}
|
||||
} else if (mode === "bundle") {
|
||||
await applyManagedPaths(context, exe);
|
||||
} else {
|
||||
await cfg().update("libPath", managedLibRoot(context), vscode.ConfigurationTarget.Global);
|
||||
}
|
||||
|
||||
// chmod +x on unix
|
||||
if (process.platform !== "win32" && fs.existsSync(exe)) {
|
||||
fs.chmodSync(exe, 0o755);
|
||||
}
|
||||
|
||||
const status = checkInstallStatus(context);
|
||||
output.appendLine(status.detail);
|
||||
if (status.cliOk && status.versionOk && status.libOk) {
|
||||
void vscode.window.showInformationMessage(
|
||||
`Marqdo ready (${status.parsedVersion ?? status.version}). Stdlib OK.`
|
||||
);
|
||||
} else if (status.cliOk && !status.versionOk) {
|
||||
void vscode.window.showWarningMessage(
|
||||
`Marqdo CLI still below ${status.requiredVersion}. ${status.detail}`
|
||||
);
|
||||
} else if (status.cliOk && !status.libOk) {
|
||||
void vscode.window.showWarningMessage(
|
||||
`Marqdo CLI ok but stdlib still missing. Try “Marqdo: Install / Repair CLI”.`
|
||||
);
|
||||
}
|
||||
return status;
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function findFileRecursive(root: string, name: string): string | undefined {
|
||||
const stack = [root];
|
||||
while (stack.length) {
|
||||
const dir = stack.pop()!;
|
||||
let entries: fs.Dirent[];
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const e of entries) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) {
|
||||
stack.push(p);
|
||||
} else if (e.name === name) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function promptIfNeeded(
|
||||
context: vscode.ExtensionContext,
|
||||
output: vscode.OutputChannel
|
||||
): Promise<void> {
|
||||
if (cfg().get<boolean>("autoInstall.checkOnStartup") === false) {
|
||||
return;
|
||||
}
|
||||
if (context.globalState.get<boolean>(SKIP_KEY)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const status = checkInstallStatus(context);
|
||||
output.appendLine(`[install] ${status.detail}`);
|
||||
|
||||
if (status.cliOk && status.versionOk && status.libOk) {
|
||||
output.appendLine(`[install] ready (CLI ≥ ${status.requiredVersion}, stdlib present)`);
|
||||
return;
|
||||
}
|
||||
|
||||
let message: string;
|
||||
let primary: string;
|
||||
const mode = status.suggestedMode ?? "bundle";
|
||||
|
||||
if (!status.cliOk) {
|
||||
message = `Marqdo CLI not detected. Install CLI ≥ ${status.requiredVersion} with the standard library?`;
|
||||
primary = "Install CLI + stdlib";
|
||||
} else if (!status.versionOk) {
|
||||
message = `Marqdo CLI version is too old (need ≥ ${status.requiredVersion}${
|
||||
status.parsedVersion ? `, found ${status.parsedVersion}` : `, raw: ${status.version}`
|
||||
}). Upgrade now (includes stdlib)?`;
|
||||
primary = "Upgrade CLI + stdlib";
|
||||
} else {
|
||||
message =
|
||||
"Marqdo CLI is OK, but the standard library (lib/) is missing. Download stdlib into the extension?";
|
||||
primary = "Install stdlib";
|
||||
}
|
||||
|
||||
const choice = await vscode.window.showWarningMessage(
|
||||
message,
|
||||
{ modal: false },
|
||||
primary,
|
||||
"Open Releases",
|
||||
"Don't ask again"
|
||||
);
|
||||
|
||||
if (choice === primary) {
|
||||
try {
|
||||
await installFromGitHub(context, output, mode);
|
||||
} catch (e) {
|
||||
const err = e instanceof Error ? e.message : String(e);
|
||||
output.appendLine(`[install] ${err}`);
|
||||
const open = await vscode.window.showErrorMessage(`Marqdo install failed: ${err}`, "Open Releases");
|
||||
if (open) {
|
||||
await vscode.env.openExternal(vscode.Uri.parse(`https://github.com/${REPO}/releases`));
|
||||
}
|
||||
}
|
||||
} else if (choice === "Open Releases") {
|
||||
await vscode.env.openExternal(vscode.Uri.parse(`https://github.com/${REPO}/releases`));
|
||||
} else if (choice === "Don't ask again") {
|
||||
await context.globalState.update(SKIP_KEY, true);
|
||||
}
|
||||
}
|
||||
|
||||
export async function resetSkipPrompt(context: vscode.ExtensionContext): Promise<void> {
|
||||
await context.globalState.update(SKIP_KEY, undefined);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import * as vscode from "vscode";
|
||||
import { compareSemver, parseCliVersion } from "./install";
|
||||
|
||||
const REPO = "cflmy/marqdo";
|
||||
const LAST_CHECK_KEY = "marqdo.lastUpdateCheck";
|
||||
const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
type GhRelease = {
|
||||
tag_name: string;
|
||||
html_url: string;
|
||||
assets: { name: string }[];
|
||||
};
|
||||
|
||||
async function fetchLatestRelease(): Promise<GhRelease> {
|
||||
const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, {
|
||||
headers: {
|
||||
Accept: "application/vnd.github+json",
|
||||
"User-Agent": "marqdo-vscode-extension",
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`GitHub releases/latest HTTP ${res.status}`);
|
||||
}
|
||||
return (await res.json()) as GhRelease;
|
||||
}
|
||||
|
||||
function extensionVersion(): string {
|
||||
return vscode.extensions.getExtension("cflmy.marqdo")?.packageJSON?.version ?? "0.0.0";
|
||||
}
|
||||
|
||||
function pickVsixAsset(release: GhRelease): string | undefined {
|
||||
const mine = extensionVersion();
|
||||
const exact = release.assets.find((a) => a.name === `marqdo-${mine}.vsix`);
|
||||
if (exact) {
|
||||
return undefined;
|
||||
}
|
||||
return release.assets.find((a) => a.name.endsWith(".vsix"))?.name;
|
||||
}
|
||||
|
||||
/** Notify when a newer CLI or extension release exists on GitHub. */
|
||||
export async function checkForUpdates(
|
||||
context: vscode.ExtensionContext,
|
||||
output: vscode.OutputChannel,
|
||||
installedCliVersion?: string
|
||||
): Promise<void> {
|
||||
if (vscode.workspace.getConfiguration("marqdo").get<boolean>("autoInstall.checkUpdates") === false) {
|
||||
return;
|
||||
}
|
||||
const last = context.globalState.get<number>(LAST_CHECK_KEY) ?? 0;
|
||||
if (Date.now() - last < CHECK_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
await context.globalState.update(LAST_CHECK_KEY, Date.now());
|
||||
|
||||
try {
|
||||
const release = await fetchLatestRelease();
|
||||
const latestTag = release.tag_name.replace(/^v/, "");
|
||||
const extVer = extensionVersion();
|
||||
const messages: string[] = [];
|
||||
|
||||
if (compareSemver(latestTag, extVer) > 0 || pickVsixAsset(release)) {
|
||||
messages.push(`extension ${extVer} → ${release.tag_name}`);
|
||||
}
|
||||
const parsedCli = installedCliVersion ? parseCliVersion(installedCliVersion) : undefined;
|
||||
if (parsedCli && compareSemver(latestTag, parsedCli) > 0) {
|
||||
messages.push(`CLI ${parsedCli} → ${release.tag_name}`);
|
||||
}
|
||||
if (messages.length === 0) {
|
||||
output.appendLine(`[update] up to date (${release.tag_name})`);
|
||||
return;
|
||||
}
|
||||
output.appendLine(`[update] newer release: ${messages.join("; ")}`);
|
||||
const choice = await vscode.window.showInformationMessage(
|
||||
`Marqdo ${release.tag_name} is available (${messages.join(", ")}).`,
|
||||
"Open Releases",
|
||||
"Later"
|
||||
);
|
||||
if (choice === "Open Releases") {
|
||||
await vscode.env.openExternal(vscode.Uri.parse(release.html_url));
|
||||
}
|
||||
} catch (e) {
|
||||
output.appendLine(
|
||||
`[update] check skipped: ${e instanceof Error ? e.message : String(e)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
|
||||
"name": "Marqdo",
|
||||
"scopeName": "source.marqdo",
|
||||
"patterns": [
|
||||
{ "include": "#frontmatter" },
|
||||
{ "include": "#code-fence" },
|
||||
{ "include": "#formula" },
|
||||
{ "include": "#heading" },
|
||||
{ "include": "#empty-return" },
|
||||
{ "include": "#hr-end" },
|
||||
{ "include": "#call" },
|
||||
{ "include": "#else-arm" },
|
||||
{ "include": "#return-line" },
|
||||
{ "include": "#statement-line" },
|
||||
{ "include": "#param-line" },
|
||||
{ "include": "#loop-line" },
|
||||
{ "include": "#branch" },
|
||||
{ "include": "#table" },
|
||||
{ "include": "#inline-code" },
|
||||
{ "include": "#comment" }
|
||||
],
|
||||
"repository": {
|
||||
"frontmatter": {
|
||||
"name": "meta.embedded.block.frontmatter.marqdo",
|
||||
"begin": "\\A---\\s*$",
|
||||
"end": "^---\\s*$",
|
||||
"beginCaptures": {
|
||||
"0": { "name": "punctuation.definition.frontmatter.begin.marqdo" }
|
||||
},
|
||||
"endCaptures": {
|
||||
"0": { "name": "punctuation.definition.frontmatter.end.marqdo" }
|
||||
},
|
||||
"patterns": [
|
||||
{
|
||||
"name": "meta.import.marqdo",
|
||||
"match": "^(\\s*)(>)(\\s+)(\\S.*)$",
|
||||
"captures": {
|
||||
"2": { "name": "keyword.control.import.marqdo" },
|
||||
"4": { "name": "string.unquoted.import.path.marqdo" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "meta.frontmatter.field.marqdo",
|
||||
"match": "^([A-Za-z0-9_-]+)\\s*:\\s*(.*)$",
|
||||
"captures": {
|
||||
"1": { "name": "entity.name.tag.frontmatter.marqdo" },
|
||||
"2": { "name": "string.unquoted.frontmatter.marqdo" }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"heading": {
|
||||
"name": "markup.heading.marqdo",
|
||||
"match": "^(#{1,6})(\\s+)(.+)$",
|
||||
"captures": {
|
||||
"1": { "name": "punctuation.definition.heading.marqdo" },
|
||||
"3": { "name": "entity.name.function.marqdo" }
|
||||
}
|
||||
},
|
||||
"empty-return": {
|
||||
"name": "keyword.control.return.empty.marqdo",
|
||||
"match": "^\\s*(\\*{4}|\\*\\*\\s+\\*\\*)\\s*$"
|
||||
},
|
||||
"hr-end": {
|
||||
"name": "keyword.control.function.end.marqdo",
|
||||
"match": "^\\s*(---+|\\*{3})\\s*$"
|
||||
},
|
||||
"call": {
|
||||
"name": "meta.call.marqdo",
|
||||
"match": "^(\\s*)(>)(\\s+)(\\S+)(.*)$",
|
||||
"captures": {
|
||||
"2": { "name": "keyword.operator.call.marqdo" },
|
||||
"4": { "name": "entity.name.function.call.marqdo" },
|
||||
"5": { "name": "meta.call.args.marqdo" }
|
||||
}
|
||||
},
|
||||
"else-arm": {
|
||||
"name": "keyword.control.conditional.else.marqdo",
|
||||
"match": "^(\\s*)(\\*)(\\s*)$"
|
||||
},
|
||||
"return-line": {
|
||||
"name": "meta.return.marqdo",
|
||||
"begin": "^(\\s*)(\\*\\*)(?!\\*)",
|
||||
"beginCaptures": {
|
||||
"2": { "name": "punctuation.definition.return.begin.marqdo" }
|
||||
},
|
||||
"end": "(\\*\\*)",
|
||||
"endCaptures": {
|
||||
"1": { "name": "punctuation.definition.return.end.marqdo" }
|
||||
},
|
||||
"contentName": "markup.bold.return.marqdo",
|
||||
"patterns": [
|
||||
{ "include": "#inline-code" },
|
||||
{ "include": "#call-inline" }
|
||||
]
|
||||
},
|
||||
"statement-line": {
|
||||
"name": "meta.statement.marqdo",
|
||||
"begin": "^(\\s*)(\\*)(?!\\*)",
|
||||
"beginCaptures": {
|
||||
"2": { "name": "punctuation.definition.statement.begin.marqdo" }
|
||||
},
|
||||
"end": "(?<!\\*)(\\*)(?!\\*)\\s*$",
|
||||
"endCaptures": {
|
||||
"1": { "name": "punctuation.definition.statement.end.marqdo" }
|
||||
},
|
||||
"contentName": "markup.italic.statement.marqdo",
|
||||
"patterns": [
|
||||
{ "include": "#inline-code" },
|
||||
{ "include": "#call-inline" }
|
||||
]
|
||||
},
|
||||
"call-inline": {
|
||||
"name": "meta.call.inline.marqdo",
|
||||
"match": "(>)(\\s*)(\\S+)",
|
||||
"captures": {
|
||||
"1": { "name": "keyword.operator.call.marqdo" },
|
||||
"3": { "name": "entity.name.function.call.marqdo" }
|
||||
}
|
||||
},
|
||||
"param-line": {
|
||||
"name": "meta.param.marqdo",
|
||||
"match": "^(\\s*)(\\+)(\\s+)(.+)$",
|
||||
"captures": {
|
||||
"2": { "name": "keyword.other.param.marqdo" },
|
||||
"4": { "name": "variable.parameter.marqdo" }
|
||||
}
|
||||
},
|
||||
"loop-line": {
|
||||
"name": "meta.loop.marqdo",
|
||||
"match": "^(\\s*)(-)(\\s+)(.+)$",
|
||||
"captures": {
|
||||
"2": { "name": "keyword.control.loop.marqdo" },
|
||||
"4": { "name": "meta.loop.body.marqdo" }
|
||||
}
|
||||
},
|
||||
"branch": {
|
||||
"name": "meta.branch.marqdo",
|
||||
"match": "^(\\s*)(\\d+\\.)(\\s+)(.*)$",
|
||||
"captures": {
|
||||
"2": { "name": "keyword.control.conditional.marqdo" },
|
||||
"4": { "name": "meta.branch.condition.marqdo" }
|
||||
}
|
||||
},
|
||||
"table": {
|
||||
"name": "markup.table.marqdo",
|
||||
"match": "^\\s*\\|.*\\|\\s*$"
|
||||
},
|
||||
"formula": {
|
||||
"name": "meta.embedded.math.marqdo",
|
||||
"begin": "^\\s*\\$\\$\\s*$",
|
||||
"end": "^\\s*\\$\\$\\s*$",
|
||||
"contentName": "string.other.math.marqdo"
|
||||
},
|
||||
"code-fence": {
|
||||
"name": "markup.fenced_code.block.marqdo",
|
||||
"begin": "^(\\s*)(```)([\\w+-]*)\\s*$",
|
||||
"beginCaptures": {
|
||||
"2": { "name": "punctuation.definition.raw.begin.marqdo" },
|
||||
"3": { "name": "entity.name.tag.lang.marqdo" }
|
||||
},
|
||||
"end": "^(\\s*)(```)\\s*$",
|
||||
"endCaptures": {
|
||||
"2": { "name": "punctuation.definition.raw.end.marqdo" }
|
||||
},
|
||||
"contentName": "markup.raw.block.marqdo"
|
||||
},
|
||||
"inline-code": {
|
||||
"name": "string.interpolated.marqdo",
|
||||
"match": "`([^`]+)`",
|
||||
"captures": {
|
||||
"0": { "name": "markup.inline.raw.marqdo" },
|
||||
"1": { "name": "variable.other.marqdo" }
|
||||
}
|
||||
},
|
||||
"comment": {
|
||||
"name": "comment.line.marqdo",
|
||||
"match": "^.+$"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"target": "ES2020",
|
||||
"outDir": "out",
|
||||
"rootDir": "src",
|
||||
"lib": ["ES2020"],
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"exclude": ["node_modules", ".vscode-test"]
|
||||
}
|
||||
Reference in new issue
Block a user