From 96a7c6ce76409f0d3588ed5f11d2c3b07ac56a0b Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 4 Aug 2026 14:49:44 +0800 Subject: [PATCH] Consolidate layout: tests fixtures, public user docs, and view site. Move gold samples under tests/, put executable user docs in public/, restyle view, and add catalog plus gh-pages publish workflow. Co-authored-by: Cursor --- .github/workflows/pages.yml | 50 ++ .gitignore | 5 + Cargo.lock | 2 +- README.md | 19 +- doc/README.md | 8 +- doc/adr/0001-implementation-language.md | 2 +- doc/design/bytecode.md | 2 +- doc/design/call-arguments.md | 2 +- doc/design/catalog-cli.md | 128 ++++ doc/design/dependencies.md | 10 +- doc/design/examples-and-tests.md | 44 +- doc/design/generated-yaml-manifest.md | 10 +- doc/design/keywords.md | 2 +- doc/design/markdown-mapping.md | 4 +- doc/design/pipeline-debug.md | 4 +- doc/design/tech-stack.md | 8 +- doc/design/user-site.md | 57 ++ doc/design/view.md | 152 ++--- doc/dev-setup.md | 5 +- doc/roadmap/interpreter.md | 20 +- examples/README.md | 15 - public/00-welcome.mq.md | 16 + public/README.md | 26 + public/features/01-phase-i-treewalk.mq.md | 14 + public/features/02-bytecode.mq.md | 18 + public/features/03-view-and-docs.mq.md | 16 + public/keywords/bool-logic.mq.md | 23 + public/keywords/print.mq.md | 12 + public/structure/01-hello.mq.md | 12 + public/structure/02-function.mq.md | 17 + public/structure/03-positional-call.mq.md | 19 + public/structure/04-branch.mq.md | 17 + public/structure/05-loop.mq.md | 28 + public/structure/06-collection.mq.md | 19 + public/structure/import/main.mq.md | 17 + public/structure/import/utils.mq.md | 14 + scripts/build-public.ps1 | 6 + scripts/build-public.sh | 7 + src/catalog.rs | 312 +++++++++ src/diagnostics.rs | 52 +- src/lex/mod.rs | 2 +- src/lib.rs | 1 + src/main.rs | 86 ++- src/parse/mod.rs | 6 +- src/view/html.rs | 632 ++++++++++++------ src/view/mod.rs | 66 +- src/view/output.rs | 73 ++ src/view/render.rs | 2 +- tests/README.md | 19 + {examples => tests}/errors/.gitkeep | 0 {examples => tests}/errors/bad-arity.mq.md | 0 .../errors/syntax-bad-line.mq.md | 0 .../errors/undefined-var.mq.md | 0 {examples => tests}/errors/unknown-fn.mq.md | 0 tests/gold.rs | 121 +++- {examples => tests}/keywords/bool-logic.mq.md | 0 {examples => tests}/keywords/print.mq.md | 0 {examples => tests}/structure/branch.mq.md | 0 .../structure/collection.mq.md | 0 {examples => tests}/structure/hello.mq.md | 0 .../structure/import/main.mq.md | 0 .../structure/import/utils.mq.md | 0 {examples => tests}/structure/loop.mq.md | 0 .../structure/nested-call.mq.md | 0 .../structure/positional-call.mq.md | 0 65 files changed, 1770 insertions(+), 432 deletions(-) create mode 100644 .github/workflows/pages.yml create mode 100644 doc/design/catalog-cli.md create mode 100644 doc/design/user-site.md delete mode 100644 examples/README.md create mode 100644 public/00-welcome.mq.md create mode 100644 public/README.md create mode 100644 public/features/01-phase-i-treewalk.mq.md create mode 100644 public/features/02-bytecode.mq.md create mode 100644 public/features/03-view-and-docs.mq.md create mode 100644 public/keywords/bool-logic.mq.md create mode 100644 public/keywords/print.mq.md create mode 100644 public/structure/01-hello.mq.md create mode 100644 public/structure/02-function.mq.md create mode 100644 public/structure/03-positional-call.mq.md create mode 100644 public/structure/04-branch.mq.md create mode 100644 public/structure/05-loop.mq.md create mode 100644 public/structure/06-collection.mq.md create mode 100644 public/structure/import/main.mq.md create mode 100644 public/structure/import/utils.mq.md create mode 100644 scripts/build-public.ps1 create mode 100644 scripts/build-public.sh create mode 100644 src/catalog.rs create mode 100644 src/view/output.rs create mode 100644 tests/README.md rename {examples => tests}/errors/.gitkeep (100%) rename {examples => tests}/errors/bad-arity.mq.md (100%) rename {examples => tests}/errors/syntax-bad-line.mq.md (100%) rename {examples => tests}/errors/undefined-var.mq.md (100%) rename {examples => tests}/errors/unknown-fn.mq.md (100%) rename {examples => tests}/keywords/bool-logic.mq.md (100%) rename {examples => tests}/keywords/print.mq.md (100%) rename {examples => tests}/structure/branch.mq.md (100%) rename {examples => tests}/structure/collection.mq.md (100%) rename {examples => tests}/structure/hello.mq.md (100%) rename {examples => tests}/structure/import/main.mq.md (100%) rename {examples => tests}/structure/import/utils.mq.md (100%) rename {examples => tests}/structure/loop.mq.md (100%) rename {examples => tests}/structure/nested-call.mq.md (100%) rename {examples => tests}/structure/positional-call.mq.md (100%) diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..f1f3cc3 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,50 @@ +# Build public/ with marqdo and publish to the gh-pages branch. +name: User docs site + +on: + push: + branches: [main, master] + paths: + - "public/**" + - "src/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/pages.yml" + - "scripts/build-public.*" + workflow_dispatch: + +permissions: + contents: write + +jobs: + build-and-deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install Rust + uses: dtolnay/rust-toolchain@stable + + - name: Build & export site + run: | + cargo build --release + find public -name '*.mq.md' ! -name 'utils.mq.md' -print0 \ + | xargs -0 -n1 ./target/release/marqdo run + ./target/release/marqdo view output public -o public + + - name: Verify site shape + run: | + if grep -R "tests/errors" public --include='*.html' ; then + echo "user site must not include tests/errors fixtures" >&2 + exit 1 + fi + test -f public/index.html + test -f public/00-welcome.mq.md + + - name: Deploy to gh-pages + uses: peaceiris/actions-gh-pages@v4 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./public + publish_branch: gh-pages + force_orphan: true diff --git a/.gitignore b/.gitignore index 429b41f..10391ee 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,11 @@ .vscode/ *.pdb .DS_Store +.marqdo/ + +# Generated HTML beside tracked public/*.mq.md (sources stay in git) +/public/index.html +/public/pages/ # Python spike venv (local) spike/.venv/ diff --git a/Cargo.lock b/Cargo.lock index 035cd97..99af386 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -210,7 +210,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" [[package]] name = "marqdo" -version = "0.1.0" +version = "0.0.1" dependencies = [ "anyhow", "assert_cmd", diff --git a/README.md b/README.md index 2e9d3fd..eae411d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程序。 -语法宪法:[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) · 浏览:[view.md](doc/design/view.md) · 示例:[examples/](examples/) +语法宪法:[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/) --- @@ -48,19 +48,22 @@ Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程 - 映射 v0.1:[markdown-mapping.md](doc/design/markdown-mapping.md) - 解释器路线图:[interpreter.md](doc/roadmap/interpreter.md) -- **Phase I(树遍历)已通**:`examples/structure/` 与 `examples/keywords/` 金样例均可 `marqdo run` -- **view**:`marqdo view examples` 按 AST 浏览结构与输出 +- **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) ```bash -cargo run -- run examples/structure/hello.mq.md -cargo run -- run examples/structure/hello.mq.md --backend bytecode -cargo run -- view examples --no-open +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 -- view output public -o public +powershell -File ./scripts/build-public.ps1 +cargo run -- catalog tests -o .marqdo ``` -当前发布:**v0.0.1**(Phase I 树遍历 + `view` + M5 字节码原型)。M5 见 [bytecode.md](doc/design/bytecode.md);errors 见 `examples/errors/`。 - +文档:用户站见 [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)。 --- diff --git a/doc/README.md b/doc/README.md index 75c90ce..b7149ad 100644 --- a/doc/README.md +++ b/doc/README.md @@ -24,15 +24,17 @@ | [design/dependencies.md](design/dependencies.md) | 依赖详单(无 Flex/Bison) | | [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置 `print` `input`** | | [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** | -| [design/examples-and-tests.md](design/examples-and-tests.md) | **示例即金样例目录布局** | -| [design/view.md](design/view.md) | **`marqdo view` 源结构浏览器** | +| [design/examples-and-tests.md](design/examples-and-tests.md) | **tests/ 金样例目录布局** | +| [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/bytecode.md](design/bytecode.md) | **M5 字节码 / 双后端** | | [design/pipeline-debug.md](design/pipeline-debug.md) | **流水线 `--dump-*` 可视调试** | | [dev-setup.md](dev-setup.md) | 开发环境配置(Rust M0) | | [roadmap/interpreter.md](roadmap/interpreter.md) | 正经解释器路线图 | | [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 | -示例与验收集:[`examples/`](../examples/)。Spike 存档:[`spike/`](../spike/)。 +金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。 ## 写作原则 diff --git a/doc/adr/0001-implementation-language.md b/doc/adr/0001-implementation-language.md index 72c851a..9c3949e 100644 --- a/doc/adr/0001-implementation-language.md +++ b/doc/adr/0001-implementation-language.md @@ -39,7 +39,7 @@ ## 后果 - 正式代码以 Cargo 工程生长;不把 Flex/Bison/LLVM 列入 v1 依赖。 -- 金样例仍为 `examples/`;行为与宪法一致。 +- 金样例仍为 `tests/`;行为与宪法一致。 - 此前「Python 作参考实现」的倾向由本修订取代;Spike 结论(行扫描等)仍然有效并迁入 Rust。 --- diff --git a/doc/design/bytecode.md b/doc/design/bytecode.md index c78825a..249500f 100644 --- a/doc/design/bytecode.md +++ b/doc/design/bytecode.md @@ -68,7 +68,7 @@ | `structure/nested-call` | ✅ | ✅ | | `structure/positional-call` | ✅ | ✅ | | `structure/import/*` | ✅ | ✅(load 合并 AST 后编译) | -| `examples/errors/*` | ✅(非零退出) | 同 tree 语义(编译期/运行期诊断) | +| `tests/errors/*` | ✅(非零退出) | 同 tree 语义(编译期/运行期诊断) | 核心金样例双后端已对齐;后续可扩展 Op、优化与更好的调试信息。 diff --git a/doc/design/call-arguments.md b/doc/design/call-arguments.md index a9e01c7..ad45142 100644 --- a/doc/design/call-arguments.md +++ b/doc/design/call-arguments.md @@ -47,4 +47,4 @@ positional ::= value_token ## 4. 金样例 -见 `examples/structure/positional-call.mq.md` 与更新后的 `examples/structure/import/`。 +见 `tests/structure/positional-call.mq.md` 与更新后的 `tests/structure/import/`。 diff --git a/doc/design/catalog-cli.md b/doc/design/catalog-cli.md new file mode 100644 index 0000000..e9312e1 --- /dev/null +++ b/doc/design/catalog-cli.md @@ -0,0 +1,128 @@ +# OKF 兼容清单:`marqdo catalog` + +| | | +|---|---| +| 状态 | 已定(v0 命令落地) | +| 日期 | 2026-08-04 | +| 取代 | [generated-yaml-manifest.md](generated-yaml-manifest.md) 中「待决:sync/doc 命令」的命令名部分 | +| 相关 | [generated-yaml-manifest.md](generated-yaml-manifest.md) · [view.md](view.md) · [okf-and-marqdo.md](../research/okf-and-marqdo.md) | + +--- + +## 1. 决策(重申) + +YAML / OKF 风格清单是**从 `.mq.md` 派生的生成物**,不是手写配置。详见 [generated-yaml-manifest.md](generated-yaml-manifest.md)。 + +本文件规定 **CLI 与 v0 落盘格式**。 + +--- + +## 2. CLI + +```bash +marqdo catalog [PATH] -o OUT_DIR +# 别名(与早期草案一致) +marqdo sync [PATH] -o OUT_DIR +``` + +| 参数 | 默认 | 说明 | +|------|------|------| +| `PATH` | `.` | 工程根或含 `.mq.md` 的目录(递归扫描) | +| `-o` / `--out` | `.marqdo` | 生成目录(写入前创建;**覆盖**同名生成文件) | + +退出码:成功 0;无可扫描文件或 IO/解析失败非 0(单文件解析失败时写入 `diagnostics` 并继续其余文件,最终若有失败则非 0)。 + +--- + +## 3. 生成物(v0) + +``` +OUT_DIR/ + catalog.yaml # 机器向总清单(OKF 风格字段) + index.md # 人/Agent 可读总览(含 YAML frontmatter) + modules/ + .md # 每个 .mq.md 一个概念页(frontmatter + 摘要) +``` + +路径中的目录层级拍扁为文件名时用 `__` 连接,例如: + +`structure/import/main.mq.md` → `modules/structure__import__main.md` + +### 3.1 `catalog.yaml`(示意) + +```yaml +# GENERATED by marqdo — do not edit by hand +type: Marqdo Catalog +title: marqdo-project +generated: + by: marqdo/0.0.1 + # at: 可选 ISO8601;CI 比对时可忽略 +modules: + - id: structure/hello + resource: structure/hello.mq.md + title: Hello World # 来自源 frontmatter title,缺省用文件名 + imports: [] + exports: + - name: Hello World + kind: fn + - id: structure/import/main + resource: structure/import/main.mq.md + imports: + - utils.mq.md + exports: + - name: main + kind: fn +``` + +字段约定(v0 最小集): + +| 字段 | 含义 | +|------|------| +| `type` | 固定 `Marqdo Catalog`(OKF:未知 type 可降级) | +| `modules[].resource` | 相对 `PATH` 的源路径 | +| `modules[].imports` | 源 frontmatter 中的 `> *.mq.md` | +| `modules[].exports` | 顶层 `#` 函数名(`kind: fn`);嵌套 `##` 列入 `children`(可选,v0 可扁平只列顶层) | +| `generated.by` | `marqdo/` | + +不在 v0:版本锁定哈希、跨仓 URL、完整符号类型。 + +### 3.2 模块概念页 frontmatter + +```yaml +--- +type: Marqdo Module +title: … +resource: structure/hello.mq.md +depends: [] # imports 列表 +exports: [Hello World] +generated: + by: marqdo/0.0.1 +--- +``` + +正文含「请勿手改」提示、依赖列表、导出列表;可链到同包其它模块页。 + +--- + +## 4. 与 `view output` 的分工 + +| 命令 | 产物 | 受众 | +|------|------|------| +| `marqdo view output` | 静态 HTML(结构 + 运行结果) | 人类读程序文档站 | +| `marqdo catalog` | OKF 风格 YAML + Markdown 索引 | 工具 / Agent / 依赖总览 | + +二者都从同一源树生成,互不替代。发布用户文档时可同时: + +```bash +marqdo view output public -o public +marqdo catalog tests -o .marqdo +``` + +--- + +## 5. 验收 + +1. `marqdo catalog tests -o /tmp/mq-cat` 写出 `catalog.yaml` 与 `modules/`。 +2. `catalog.yaml` 含 `structure/hello` 与 import 模块的 `imports: [utils.mq.md]`。 +3. 文件头或 `generated` 标明 GENERATED;文档声明勿手改。 +4. `marqdo sync` 与 `catalog` 行为一致。 diff --git a/doc/design/dependencies.md b/doc/design/dependencies.md index eec8374..7e2cf61 100644 --- a/doc/design/dependencies.md +++ b/doc/design/dependencies.md @@ -1,4 +1,4 @@ -# Marqdo 实现依赖说明(Rust 参考解释器) +# Marqdo 实现依赖说明(Rust 参考解释器) | | | |---|---| @@ -94,7 +94,7 @@ Marqdo 换 **Rust 或 C++** 都不改变「主前端不该是 Flex/Bison」这 | Crate | 角色 | |-------|------| | **rust 自带** `#[test]` | 单元测试 | -| **insta** 或手写金文件 | examples 期望 stdout 快照(可选) | +| **insta** 或手写金文件 | tests 期望 stdout 快照(可选) | | **assert_cmd** / **predicates** | CLI 集成测试(可选) | #### Phase II(字节码 VM,后加) @@ -142,8 +142,8 @@ crates/marqdo/ # 或根包 marqdo interp/ # Phase I bytecode/ # Phase II runtime/ - tests/ -examples/ # 金样例(已有) + tests/ # gold.rs + structure|keywords|errors +public/ # 用户可执行文档 spike/ # Python 风险探测存档(可保留,非运行时依赖) ``` @@ -152,7 +152,7 @@ spike/ # Python 风险探测存档(可保留,非运行 ```bash cargo build cargo test -cargo run -- run examples/structure/nested-call.mq.md +cargo run -- run tests/structure/nested-call.mq.md ``` --- diff --git a/doc/design/examples-and-tests.md b/doc/design/examples-and-tests.md index 7ee4b59..9503639 100644 --- a/doc/design/examples-and-tests.md +++ b/doc/design/examples-and-tests.md @@ -4,33 +4,37 @@ |---|---| | 状态 | 已定 | | 日期 | 2026-08-04 | -| 原则 | **示例即金样例**:`examples/**/*.mq.md` 由 `cargo test` / CI 跑通;`marqdo view` 也可直接浏览 | +| 原则 | **夹具即金样例**:`tests/{structure,keywords,errors}/**/*.mq.md` 由 `cargo test` / CI 跑通;`marqdo view tests` 也可浏览 | --- ## 1. 目录 +只保留 **`tests/`**,用子目录区分类别(不再另设 `examples/`): + ``` -examples/ - README.md # 本树说明 +tests/ + README.md + gold.rs # 集成测试入口 structure/ # 代码基础结构(Markup 架构) hello.mq.md - nested-call.mq.md # 原 index:嵌套函数 + 调用 - positional-call.mq.md # 位置实参 + nested-call.mq.md + positional-call.mq.md branch.mq.md loop.mq.md collection.mq.md import/ - main.mq.md # 原 with-import + main.mq.md utils.mq.md keywords/ # 关键字与内置名 print.mq.md - bool-logic.mq.md # True/False/None、and/or/not + bool-logic.mq.md errors/ # 期望失败(诊断文案稳定后再加金样例) - .gitkeep + … ``` -Rust 集成测试:`tests/gold.rs` 扫描约定路径,比对 stdout。 +面向访客的可执行介绍在 [`public/`](../../public/)(无 `errors/`),见 [user-site.md](user-site.md)。 +开发设计文稿在 [`doc/`](../)(单数)。 --- @@ -42,7 +46,7 @@ Rust 集成测试:`tests/gold.rs` 扫描约定路径,比对 stdout。 | **keywords** | `True`/`False`/`None`、`and`/`or`/`not`、`print`/`input` 约定 | 复杂控制流(可极简) | | **errors** | 未定义名、实参错误、语法错误的诊断 | 成功路径 | -未单独建夹、但应覆盖的其它测试(放 `tests/` 单测或日后 `examples/runtime/`): +未单独建夹、但应覆盖的其它测试(`src/**` 单测或日后 `tests/runtime/`): - **流水线调试**:`--dump-lines` / `--dump-ast` / `--trace-eval` - **CLI**:默认 `index.mq.md`、退出码 @@ -53,24 +57,12 @@ Rust 集成测试:`tests/gold.rs` 扫描约定路径,比对 stdout。 ## 3. 金样例约定 -每个可执行 `.mq.md` 在 `tests/gold.rs`(或旁路 `.out` 文件)登记期望 stdout。 +每个可执行 `.mq.md` 在 `tests/gold.rs` 登记期望 stdout。 `errors/` 内文件登记期望 stderr 子串与非零退出码。 -Frontmatter 可写: - -```yaml ---- -title: … -expect_stdout: | - line1 - line2 ---- -``` - -(可选;v0 先以测试代码内嵌期望为主。) - --- -## 4. 与 `view` 的关系 +## 4. 与 `view` / `public` 的关系 -`marqdo view examples` 按上述文件夹生成侧栏索引;`structure` / `keywords` 为一级分组。 +- `marqdo view tests`:开发者浏览金样例(含 errors)。 +- `marqdo view public`:用户文档站源;**不要**把 `tests/errors` 编进 `public/`。 diff --git a/doc/design/generated-yaml-manifest.md b/doc/design/generated-yaml-manifest.md index 462b01b..86abae4 100644 --- a/doc/design/generated-yaml-manifest.md +++ b/doc/design/generated-yaml-manifest.md @@ -149,11 +149,11 @@ Marqdo 有两层「文档」,不要混为一谈: ## 待决问题(后续 ADR) -- [ ] 生成物落盘路径(例如 `.marqdo/` vs `docs/catalog/`)及是否提交进 git -- [ ] 单文件是否仍写入「生成型 frontmatter」,还是全部集中在工程级 OKF 包 -- [ ] 与 `Cargo.toml` 式「可手写包身份(name/version)」的边界:是否允许极少量非生成的包清单,与全自动 OKF 目录如何分工 -- [ ] `marqdo sync` / `marqdo doc` 命令的具体行为 -- [ ] 是否沿用 OKF v0.2 的 `generated` / `sources` 字段描述溯源 +- [x] 生成物默认路径:`.marqdo/`(`-o` 可改)— 见 [catalog-cli.md](catalog-cli.md) +- [x] `marqdo catalog` / `sync`;静态用户文档:`marqdo view output` — 见 [view.md](view.md) +- [ ] 是否提交生成物进 git(项目自定;CI 可校验干净生成) +- [ ] 与「可手写包身份 name/version」的边界 +- [ ] 是否沿用 OKF v0.2 的 `sources` 等溯源字段 --- diff --git a/doc/design/keywords.md b/doc/design/keywords.md index b771d13..d2a124b 100644 --- a/doc/design/keywords.md +++ b/doc/design/keywords.md @@ -14,7 +14,7 @@ 1. **标记承担架构**:函数=`#`,分支=`+`,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。 2. **英文标识**:内置与字面量用英文,便于工具高亮与国际协作。 3. **学 Python 的边界**:Python 3 里 [`print` / `input` 是内置函数,不是关键字](https://realpython.com/python-keywords/);布尔与空值是字面量关键字。Marqdo 同样区分 **关键字** vs **内置函数名**。 -4. **宁少勿多**:前期只列执行 examples 所需;要加再进 ADR。 +4. **宁少勿多**:前期只列执行金样例所需;要加再进 ADR。 --- diff --git a/doc/design/markdown-mapping.md b/doc/design/markdown-mapping.md index 228e6ff..af364e7 100644 --- a/doc/design/markdown-mapping.md +++ b/doc/design/markdown-mapping.md @@ -1,4 +1,4 @@ -# Marqdo 语法映射 v0.1(Markup-as-Syntax) +# Marqdo 语法映射 v0.1(Markup-as-Syntax) | | | |---|---| @@ -208,4 +208,4 @@ v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致 ## 13. 示例索引 -见 [`examples/`](../../examples/)。 +见 [`tests/`](../../tests/)。 diff --git a/doc/design/pipeline-debug.md b/doc/design/pipeline-debug.md index cc1c78f..1405fdc 100644 --- a/doc/design/pipeline-debug.md +++ b/doc/design/pipeline-debug.md @@ -1,4 +1,4 @@ -# 解释器流水线可视调试 +# 解释器流水线可视调试 | | | |---|---| @@ -43,7 +43,7 @@ marqdo dump FILE --stage lines|tokens|ast|sema|all ## 3. 横幅示例 ``` -=== marqdo: lines (examples/hello.mq.md) === +=== marqdo: lines (tests/structure/hello.mq.md) === 1 Blank 2 Comment | # Hello World 3 Blank diff --git a/doc/design/tech-stack.md b/doc/design/tech-stack.md index 616a536..354dcd5 100644 --- a/doc/design/tech-stack.md +++ b/doc/design/tech-stack.md @@ -1,4 +1,4 @@ -# 参考实现:技术选型分析(尚未拍板) +# 参考实现:技术选型分析(尚未拍板) | | | |---|---| @@ -18,7 +18,7 @@ 2. **对齐 GFM** 的结构:标题、列表(`-`/`+`/`1.`)、强调、表格、围栏、链接 3. **Lower**:行首判别、标题树作用域、列表符语义、注释剥离 4. **两遍**:收集定义 + 导入 → 求值 -5. **CLI** + **金样例测试**(`examples/`) +5. **CLI** + **金样例测试**(`tests/`) 可选后期:字节码/编译、LSP、格式化。首版目标是**验证语法宪法**,不是上生产编译器。 @@ -51,7 +51,7 @@ → Marqdo AST → 语义:导入图、提升、作用域 → 后端:解释器(v0)/日后编译 - → 测试:examples → 期望 stdout + → 测试:tests 金样例 → 期望 stdout ``` **前端可复用成熟 GFM 库,也可自研**;Middle/后端必须自研(这是语言本体)。 @@ -130,7 +130,7 @@ - 候选 A:TS + remark-gfm — 能否区分 `-`/`+` bullet、解析单列表格、读 strong/emphasis。 - 候选 B:Rust + comrak/pulldown — 同上。 - (可选)C 或 D 若团队有偏好再做。 -2. **对照验收用例**(固定):`examples/hello.mq.md`、`branch.mq.md`(`+`)、`collection.mq.md`(表)、含 `> x.mq.md` 的 frontmatter 行。 +2. **对照验收用例**(固定):`tests/structure/hello.mq.md`、`branch.mq.md`(`+`)、`collection.mq.md`(表)、含 `> x.mq.md` 的 frontmatter 行。 3. **出 ADR**:选定「验证期实现」与(可选)「生产目标实现」是否同一语言。 4. **再**建仓库脚手架与测试——禁止在 ADR 前默认生成 `package.json` / `Cargo.toml` 当既成事实。 diff --git a/doc/design/user-site.md b/doc/design/user-site.md new file mode 100644 index 0000000..f879ab6 --- /dev/null +++ b/doc/design/user-site.md @@ -0,0 +1,57 @@ +# 用户静态文档站(public / gh-pages) + +| | | +|---|---| +| 状态 | 已定 | +| 日期 | 2026-08-04 | +| 相关 | [view.md](view.md) · 源目录 [`public/`](../../public/) | + +--- + +## 1. 分工 + +| 路径 | 是否入库 | 职责 | +|------|----------|------| +| `doc/` | 是 | 开发者设计 / ADR / 路线图(单数 `doc`,勿再造 `docs/`) | +| `public/**/*.mq.md` | 是 | 用户可读、可执行、可下载的介绍(结构 / 关键字 / 特性迭代) | +| `public/index.html`、`public/pages/` | **否**(ignore) | `marqdo view output` 生成的 HTML | +| `tests/{structure,keywords,errors}/` | 是 | 金样例与失败夹具(含 errors) | +| 远程分支 `gh-pages` | 发布产物 | 发布整个 `public/`(源文件 + 生成 HTML) | + +**禁止**把 `tests/errors/` 编进用户站。 + +--- + +## 2. 生成 + +```bash +cargo run --release -- view output public -o public +# 或 +./scripts/build-public.sh +powershell -File ./scripts/build-public.ps1 +``` + +产物写在源旁: + +``` +public/ + *.mq.md / structure/ / … # 入库源 + index.html # 生成(ignore) + pages/… # 生成(ignore) +``` + +--- + +## 3. 发布分支 + +将构建后的 `public/` 推到 **`gh-pages`**。CI:`.github/workflows/pages.yml`。 + +仓库 Settings → Pages → Source = Deploy from branch → `gh-pages` / root。 + +--- + +## 4. 验收 + +1. `public/` 下每个 `.mq.md`(除纯工具模块外)`marqdo run` 退出码 0。 +2. `view output public -o public` 后首页为欢迎页,侧栏无 errors。 +3. 主分支跟踪 `public/**/*.mq.md`;不提交 `public/index.html` / `public/pages/`。 diff --git a/doc/design/view.md b/doc/design/view.md index 6ab5acd..0f4ef2e 100644 --- a/doc/design/view.md +++ b/doc/design/view.md @@ -1,24 +1,44 @@ -# `marqdo view` — 源结构浏览器 +# `marqdo view` — 源结构浏览器与静态文档导出 | | | |---|---| -| 状态 | 已定(实现中) | +| 状态 | 已定(v0.0.2 方向) | | 日期 | 2026-08-04 | -| 相关 | [examples-and-tests.md](examples-and-tests.md) · [pipeline-debug.md](pipeline-debug.md) · AST(`src/ast.rs`) | +| 相关 | [examples-and-tests.md](examples-and-tests.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) | --- ## 1. 动机 -`.mq.md` 既是文档也是程序。需要一种**可读渲染**,而不仅是纯文本或 `run` 的 stdout: +`.mq.md` 既是文档也是程序。需要: -- 按语法树展示函数、分支、循环、调用、返回; -- 同页展示**执行结果**; -- 支持打开**单个文件**或**文件夹**(扫描全部 `.mq.md` + 结构索引)。 +1. **本地浏览**:按 AST 展示结构 + 执行结果; +2. **静态导出**:同一套渲染写成 HTML,作为**用户文档站点**(勿手写第二套站点); +3. **启动快**:样式极简,无外链字体/厚主题,避免 view 冷启动慢。 --- -## 2. CLI +## 2. 视觉(Apple HIG / Docs 极简) + +对齐 [Apple HIG](https://developer.apple.com/design/human-interface-guidelines) 的 **clarity / deference / white space**,并参考常见 docs 布局(sticky 侧栏 + 居中主栏,见 Nextra / Docusaurus 类站点):**系统灰底、白内容面、浅分隔线、系统字体**。作者站 [id.cflmy.cn](https://id.cflmy.cn) 仍作克制感参考,但不强行纯黑描边。 + +| 规则 | 要求 | +|------|------| +| 色板 | 页底 `#f5f5f7`;内容面 `#ffffff`;正文 `#1d1d1f`;次要字 `#6e6e73`;分隔 `#d2d2d7`;选中侧栏项反白 | +| 布局 | 壳层 `max-width ≈ 1400px` 居中;侧栏 ≈280px sticky;主内容 `max-width ≈ 58rem`(宽屏可读、不过窄);**≤800px 侧栏收起**,顶栏汉堡(checkbox,无 JS) | +| 默认页 | 打开目录时 **直接展示排序后的第一个 `.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` 方案。 + +--- + +## 3. CLI + +### 3.1 实时浏览 ```bash marqdo view [PATH] [--port PORT] [--host HOST] [--no-open] @@ -26,94 +46,68 @@ marqdo view [PATH] [--port PORT] [--host HOST] [--no-open] | 参数 | 默认 | 说明 | |------|------|------| -| `PATH` | `.` | `.mq.md` 文件,或目录(递归扫描 `*.mq.md`) | -| `--port` | `7429` | HTTP 端口 | -| `--host` | `127.0.0.1` | 仅本地 | -| `--no-open` | 关 | 不尝试打开系统浏览器 | +| `PATH` | `.` | `.mq.md` 或目录 | +| `--port` | `7429` | | +| `--host` | `127.0.0.1` | | +| `--no-open` | 关 | 不打开浏览器 | + +### 3.2 静态导出(文档生成) + +```bash +marqdo view output [PATH] -o OUT_DIR [--no-exec] +``` + +| 参数 | 默认 | 说明 | +|------|------|------| +| `PATH` | `.` | 与 `view` 相同扫描范围 | +| `-o` / `--out` | (必填) | 输出目录(不存在则创建) | +| `--no-exec` | 关 | 不跑程序,执行区显示「skipped」 | + +**产物布局:** + +``` +OUT_DIR/ + index.html # 默认 = 排序后第一个 .mq.md 的完整页(侧栏高亮该项) + pages/ + <相对路径>.html # 每个 .mq.md 一页;路径中的 `/` 保留为子目录 + # 例:structure/hello.mq.md → pages/structure/hello.mq.md.html +``` + +- 页内链接一律**相对路径**,可用任意静态服务器或 `file://`(同目录结构下)打开。 +- 用户文档推荐流程:`marqdo view output public -o public`,将生成物发布到 `gh-pages`(见 [user-site.md](user-site.md))。 +- 金样例浏览仍可用:`marqdo view output tests -o /tmp/mq-tests`(含 errors,勿当对外用户站)。 +- 渲染逻辑与实时 `view` **共用**同一套 HTML 构件(结构 / 执行 / 源码),禁止两套皮肤分叉。 示例: ```bash -marqdo view examples/structure/hello.mq.md -marqdo view examples -marqdo view examples/keywords --port 8080 +marqdo view output public -o public +marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc ``` -启动后打印 `http://127.0.0.1:7429/`,阻塞直至 Ctrl+C。 - --- -## 3. 信息架构 +## 4. 信息架构(不变) -### 3.1 目录模式 - -``` -┌─────────────┬──────────────────────────────────┐ -│ 索引 │ 选中文件 / 欢迎页 │ -│ structure/ │ │ -│ hello │ [源码结构] [执行结果] [原始文本] │ -│ branch │ │ -│ keywords/ │ │ -└─────────────┴──────────────────────────────────┘ -``` - -- 侧栏:相对 `PATH` 的目录树;只列出 `.mq.md`。 -- 点击文件:主区切换为该文件的三栏/三节视图。 - -### 3.2 单文件模式 - -无侧栏列表(或仅当前文件);主区同「选中文件」视图。仍提供「执行」结果。 +侧栏索引 + 主区三节:结构(AST+注释插回)· 执行 · 源码。表达式为表面语法,非 Debug。 --- -## 4. 主区三节 - -### 4.1 源码结构(AST 渲染) - -不依赖浏览器 Markdown 猜测语义,而用服务端已解析的 AST: - -| AST 节点 | 视觉 | -|----------|------| -| `Function` | 卡片:标题层级、形参芯片、子函数嵌套;**中间的注释行仍展示**(来自源行分类,不在 AST 内) | -| `Stmt::*` | 绑定 / 返回 / 调用 / 分支 / 循环;表达式用**表面语法**(如 `` `x` > 0 ``),不用 Debug | - -样式:清晰分区,避免「通用仪表盘」堆砌;结构层级一眼可读。 - -### 4.2 执行结果 - -服务端对该文件跑与 `marqdo run` 相同的管线,**捕获 stdout/stderr** 与退出状态,展示在「输出」区。 -含 `input` 的程序:view 中标注「需交互,未在 view 执行」或提供只读说明(v0:跳过/失败信息)。 - -### 4.3 原始文本 - -等宽展示源文件;可选行分类着色(Code / Comment / Blank),与 `--dump-lines` 一致。 - ---- - -## 5. HTTP API(实现细节) +## 5. HTTP(实时模式) | 方法 | 路径 | 含义 | |------|------|------| -| `GET` | `/` | 索引 HTML | -| `GET` | `/file?path=…` | 单文件页(path 相对根,防 `..` 逃逸) | -| `GET` | `/api/tree` | JSON 文件树 | -| `GET` | `/api/file?path=…` | JSON:`{ source, ast_html 或 ast_json, stdout, stderr, ok }` | +| `GET` | `/` | 默认打开第一个 `.mq.md`(无文件时为空提示) | +| `GET` | `/file?path=…` | 单文件页 | +| `GET` | `/api/tree` | JSON 树(可选) | -v0 可全部服务端渲染 HTML,API 可选。 - -安全:根目录锁死为 CLI 给定的 `PATH`(若为文件则其父目录为根、仅一文件);拒绝根外路径。 +根目录锁死;拒绝 `..` 逃逸。 --- -## 6. 依赖 +## 6. 验收 -本地同步 HTTP 即可(如 `tiny_http`),无强制前端构建;HTML/CSS/少量 JS 内嵌于 Rust。 - ---- - -## 7. 验收 - -1. `marqdo view examples/structure/hello.mq.md` 显示结构 + `Hello World!` 输出。 -2. `marqdo view examples` 侧栏含 `structure/` 与 `keywords/` 分组。 -3. 分支/循环样例在结构区可区分臂与循环体。 -4. 路径逃逸被拒绝。 +1. 实时 `view`:HIG 风极简、无外链字体、结构与执行正确;打开目录即见首个文件。 +2. `view output public -o public`(或临时目录)生成可点的 `index.html`(首文件)与各 `pages/…`。 +3. 静态页中执行区与 `marqdo run` 一致(未加 `--no-exec` 时);失败诊断路径无 `\\?\`。 +4. 冷启动无明显外网依赖。 diff --git a/doc/dev-setup.md b/doc/dev-setup.md index f747d3e..49dc77b 100644 --- a/doc/dev-setup.md +++ b/doc/dev-setup.md @@ -33,7 +33,7 @@ cd marqdo cargo build cargo test -cargo run -- run examples/structure/hello.mq.md +cargo run -- run tests/structure/hello.mq.md ``` 当前 M0:`run` 会读入文件并明确报错「evaluation not implemented」(脚手架,非静默假成功)。 @@ -75,7 +75,8 @@ proxy = "http://127.0.0.1:7897" | `src/lex` | 行分类 / 词法(自研) | | `src/parse` | 递归下降语法 | | `src/diagnostics` | 诊断 | -| `examples/` | 金样例(宪法) | +| `tests/` | 金样例 + 集成测试(`structure` / `keywords` / `errors`) | +| `public/` | 用户可执行文档(无 errors) | | `spike/` | 旧 Python 风险探测,非运行时依赖 | | `doc/` | 设计与路线图 | diff --git a/doc/roadmap/interpreter.md b/doc/roadmap/interpreter.md index b2ad5f8..384c9df 100644 --- a/doc/roadmap/interpreter.md +++ b/doc/roadmap/interpreter.md @@ -1,4 +1,4 @@ -# Marqdo 参考实现:正经解释器路线图 +# Marqdo 参考实现:正经解释器路线图 | | | |---|---| @@ -67,7 +67,7 @@ index.mq.md (+ 导入的 .mq.md) └─────────┬─────────┘ ▼ ┌───────────────────┐ -│ 4a. 树遍历解释器 │ ← Phase I(必须先完成,跑通全部 examples) +│ 4a. 树遍历解释器 │ ← Phase I(必须先完成,跑通全部 tests 金样例) │ 或 │ │ 4b. 字节码编译+VM │ ← Phase II(性能与「更像真语言实现」) └─────────┬─────────┘ @@ -86,7 +86,7 @@ Phase I 对齐 Crafting Interpreters 的 **jlox(树遍历)**;Phase II 对 - 包名:`marqdo`(`src/marqdo/` 或 `marqdo/`) - CLI:`marqdo run `,默认找目录下 `index.mq.md` - 诊断:带文件名、行号、列号 -- 测试:每个 `examples/*.mq.md` 有期望 stdout(金样例);CI 可跑 +- 测试:每个 `tests/{structure,keywords}/*.mq.md` 有期望 stdout(金样例);CI 可跑 ### Phase I — 可运行的语言核心(树遍历) @@ -96,7 +96,7 @@ Phase I 对齐 Crafting Interpreters 的 **jlox(树遍历)**;Phase II 对 2. **语法 → AST**:函数、形参、`*` 语句、`**` 返回、`>` 调用、`+` 分支、`-` 循环、表格集合、绑定与 `==`。 3. **语义**:提升、嵌套作用域、`##` 私有、frontmatter 导入公有顶层。 4. **运行时**:环境、调用栈、值(文/数/表/记录)、内置 `print`。 -5. **验收**:`examples/structure/*` 与 `examples/keywords/*` 全部 `marqdo run` 通过。 +5. **验收**:`tests/structure/*` 与 `tests/keywords/*` 全部 `marqdo run` 通过。 ### Phase II — 字节码 VM(正经化) @@ -140,11 +140,11 @@ Phase I 对齐 Crafting Interpreters 的 **jlox(树遍历)**;Phase II 对 ``` Cargo.toml -crates/marqdo/ # 或根包 src/lex/ parse/ ast/ sema/ interp/ bytecode/ runtime/ -tests/ -examples/ -spike/ # Python 存档,非运行时依赖 +tests/ # gold.rs + structure|keywords|errors 夹具 +public/ # 用户可执行文档 +doc/ # 设计文稿 +spike/ # Python 存档,非运行时依赖 ``` --- @@ -170,9 +170,9 @@ spike/ # Python 存档,非运行时依赖 在仓库根或任意含 `index.mq.md` 的目录: ```bash -marqdo run examples/structure/nested-call.mq.md +marqdo run tests/structure/nested-call.mq.md # 或 -marqdo run examples/structure/import/main.mq.md +marqdo run tests/structure/import/main.mq.md ``` 输出与金样例一致;错误带位置;新增语法必须加金样例与单测。这才是「一门解释型语言」的最低合格线。 diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index 2b53165..0000000 --- a/examples/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# Marqdo examples(金样例) - -本目录即测试夹具,见 [doc/design/examples-and-tests.md](../doc/design/examples-and-tests.md)。 - -| 目录 | 内容 | -|------|------| -| [`structure/`](structure/) | 函数、调用、分支、循环、表、导入、位置实参 | -| [`keywords/`](keywords/) | `print`、布尔与 `and`/`or`/`not` | -| [`errors/`](errors/) | 期望失败(未定义名 / 未知函数 / 实参 / 语法) | - -```bash -cargo test -marqdo run examples/structure/hello.mq.md -marqdo view examples -``` diff --git a/public/00-welcome.mq.md b/public/00-welcome.mq.md new file mode 100644 index 0000000..111a68b --- /dev/null +++ b/public/00-welcome.mq.md @@ -0,0 +1,16 @@ +--- +title: 欢迎使用 Marqdo +description: 用户文档首页 — 代码即文档 +--- + +# main + +产品名 Marqdo = Marq(Markdown)+ do(执行)。 + +打开这份 .mq.md,你看到的是说明;用解释器运行它,同一份文件就是程序。 + +无标记的段落是注释,不会执行。下面这一行才是真正的调用: + +> print text=欢迎来到 Marqdo:代码即文档,文档即代码。 + +侧栏可浏览 structure(结构)、keywords(关键字)、features(特性迭代)。三者均可执行。 diff --git a/public/README.md b/public/README.md new file mode 100644 index 0000000..b5721f2 --- /dev/null +++ b/public/README.md @@ -0,0 +1,26 @@ +# 用户文档(可执行 · 可下载) + +本目录即面向访客的 Marqdo 介绍:每个 `.mq.md` 既是文稿也能 `marqdo run`,并随仓库 / 静态站一起下载。 + +| 路径 | 内容 | +|------|------| +| [`00-welcome.mq.md`](00-welcome.mq.md) | 首页 | +| [`structure/`](structure/) | 基本结构 | +| [`keywords/`](keywords/) | 关键字与内置 `print` | +| [`features/`](features/) | 特性迭代说明 | + +**不放** `errors/`:失败样例只在 `tests/errors/`,避免用户站出现红色执行失败。 + +开发文档(语言设计等)在 [`doc/`](../doc/),与本目录分离。 + +## 浏览与生成 HTML + +```bash +cargo run -- view public +cargo run -- view output public -o public +# 或 +./scripts/build-public.sh +powershell -File ./scripts/build-public.ps1 +``` + +生成的 `index.html` 与 `pages/` 默认被 ignore;CI 构建后推到 `gh-pages`。详见 [user-site.md](../doc/design/user-site.md)。 diff --git a/public/features/01-phase-i-treewalk.mq.md b/public/features/01-phase-i-treewalk.mq.md new file mode 100644 index 0000000..be80a61 --- /dev/null +++ b/public/features/01-phase-i-treewalk.mq.md @@ -0,0 +1,14 @@ +--- +title: Phase I — 树遍历解释器 +description: 词法 · 语法 · 语义 · 树遍历已贯通 +--- + +# main + +里程碑:Phase I(树遍历)。 + +流水线:加载 → 行分类 → 递归下降语法 → 语义检查 → 树遍历执行。实现不用 Flex/Bison。 + +本页本身即可运行,证明「文档即程序」在解释器里已落地: + +> print text=Phase I:tree-walk interpreter is live. diff --git a/public/features/02-bytecode.mq.md b/public/features/02-bytecode.mq.md new file mode 100644 index 0000000..b6d178d --- /dev/null +++ b/public/features/02-bytecode.mq.md @@ -0,0 +1,18 @@ +--- +title: 字节码后端 +description: --backend bytecode 与树遍历共用语义 +--- + +# main + +里程碑:字节码原型。 + +同一套 .mq.md 可用树遍历或字节码 VM 执行。命令示例: + + marqdo run FILE --backend tree + + marqdo run FILE --backend bytecode + +下面这段在两种后端下输出一致: + +> print text=Bytecode backend:same program, alternate engine. diff --git a/public/features/03-view-and-docs.mq.md b/public/features/03-view-and-docs.mq.md new file mode 100644 index 0000000..6fa24d7 --- /dev/null +++ b/public/features/03-view-and-docs.mq.md @@ -0,0 +1,16 @@ +--- +title: view 与用户文档站 +description: 本地浏览与静态导出由解释器生成 +--- + +# main + +里程碑:marqdo view 与 view output。 + +本地浏览:marqdo view public + +静态导出:marqdo view output public -o public + +用户可执行文档就在 public/;生成的 HTML(index.html / pages/)供静态托管,CI 发布到 gh-pages。 + +> print text=Docs site:generated by the Marqdo interpreter, not hand-written HTML. diff --git a/public/keywords/bool-logic.mq.md b/public/keywords/bool-logic.mq.md new file mode 100644 index 0000000..a6b21a8 --- /dev/null +++ b/public/keywords/bool-logic.mq.md @@ -0,0 +1,23 @@ +--- +title: 布尔与逻辑 +description: True / False / None 与 and / or / not +--- + +# main + +关键字:`True`、`False`、`None`,以及 `and` / `or` / `not`。 + +*`a` = True* +*`b` = False* + ++ `a` and not `b` + > print text=ok ++ * + > print text=fail + +*`probe` = 1* + ++ None + > print text=none-truthy ++ * + > print text=none-falsy diff --git a/public/keywords/print.mq.md b/public/keywords/print.mq.md new file mode 100644 index 0000000..0e4f48f --- /dev/null +++ b/public/keywords/print.mq.md @@ -0,0 +1,12 @@ +--- +title: 内置 print +description: 具名与位置两种写法 +--- + +# main + +内置 print 接受具名或位置实参: + +> print text=named form + +> print positional diff --git a/public/structure/01-hello.mq.md b/public/structure/01-hello.mq.md new file mode 100644 index 0000000..0cbd2ce --- /dev/null +++ b/public/structure/01-hello.mq.md @@ -0,0 +1,12 @@ +--- +title: Hello World +description: 最简单的可执行文档 +--- + +# main + +普通段落是注释。print 是内置函数,不是语法架构。 + +注释里的粗体与斜体标记若出现在行首会被当成代码,所以叙述行请用普通文字开头。 + +> print text=Hello World! diff --git a/public/structure/02-function.mq.md b/public/structure/02-function.mq.md new file mode 100644 index 0000000..f65e905 --- /dev/null +++ b/public/structure/02-function.mq.md @@ -0,0 +1,17 @@ +--- +title: 函数与具名调用 +description: `#` 定义函数,`>` 调用;`-` 下列纯名为形参 +--- + +# main + +用 `#` / `##` 定义函数。形参写在函数头下方的 `-` 纯名行。 + +调用用 `>`:具名实参写作 `形参=值`。 + +> 问候 谁=World + +## 问候 + - 谁 + +> print text=Hello `谁`! diff --git a/public/structure/03-positional-call.mq.md b/public/structure/03-positional-call.mq.md new file mode 100644 index 0000000..fcac923 --- /dev/null +++ b/public/structure/03-positional-call.mq.md @@ -0,0 +1,19 @@ +--- +title: 位置实参 +description: 按形参顺序传参;也可继续用具名 +--- + +# main + +位置实参:按形参声明顺序绑定,不必写 `谁=`。 + +> 问候 Marqdo + +具名形式仍然可用: + +> 问候 谁=World + +## 问候 + - 谁 + +> print text=Hello `谁`! diff --git a/public/structure/04-branch.mq.md b/public/structure/04-branch.mq.md new file mode 100644 index 0000000..4f590cb --- /dev/null +++ b/public/structure/04-branch.mq.md @@ -0,0 +1,17 @@ +--- +title: 分支 +description: `+` 臂;整行 `*` 为 else +--- + +# main + +斜体行是程序语句。分支用 `+`;臂头单独一行 `*` 表示 else。 + +*`x` = 0* + ++ `x` > 0 + > print text=正数 ++ `x` < 0 + > print text=负数 ++ * + > print text=零 diff --git a/public/structure/05-loop.mq.md b/public/structure/05-loop.mq.md new file mode 100644 index 0000000..461b5ba --- /dev/null +++ b/public/structure/05-loop.mq.md @@ -0,0 +1,28 @@ +--- +title: 循环 +description: 条件循环与表格遍历 +--- + +# main + +函数体内的 `-` 是循环(不是形参)。 + +倒数: + +*`n` = 3* + +- `n` > 0 + > print text=`n` + *`n` = `n` - 1* + +遍历篮子(表格是集合): + +`篮子` = + +| 果 | +|----| +| 苹果 | +| 梨 | + +- [果](篮子) + > print text=今天吃`果` diff --git a/public/structure/06-collection.mq.md b/public/structure/06-collection.mq.md new file mode 100644 index 0000000..9ac93be --- /dev/null +++ b/public/structure/06-collection.mq.md @@ -0,0 +1,19 @@ +--- +title: 集合(表格) +description: GFM 表格即集合 +--- + +# main + +Markdown 表格在 Marqdo 里就是集合,可用循环逐行取出。 + +`篮子` = + +| 果 | +|----| +| 苹果 | +| 梨 | +| 桃 | + +- [果](篮子) + > print text=`果` diff --git a/public/structure/import/main.mq.md b/public/structure/import/main.mq.md new file mode 100644 index 0000000..19a0051 --- /dev/null +++ b/public/structure/import/main.mq.md @@ -0,0 +1,17 @@ +--- +title: 跨文件导入 +description: frontmatter 中 `> 文件.mq.md` 导入模块 +> utils.mq.md +--- + +# main + +文件头 YAML 里写 `> utils.mq.md` 即可导入同目录模块。 + +导入后:用返回值绑定,再输出;并直接调用问候。 + +*`y` = > 加一 n=41* + +> print text=`y` + +> 问候 谁=Marqdo diff --git a/public/structure/import/utils.mq.md b/public/structure/import/utils.mq.md new file mode 100644 index 0000000..6fdedd0 --- /dev/null +++ b/public/structure/import/utils.mq.md @@ -0,0 +1,14 @@ +--- +title: 工具模块 +description: 被 main 导入;粗体是返回值 +--- + +# 加一 + - n + +**`n` + 1** + +# 问候 + - 谁 + +> print text=你好,`谁`! diff --git a/scripts/build-public.ps1 b/scripts/build-public.ps1 new file mode 100644 index 0000000..e74c31a --- /dev/null +++ b/scripts/build-public.ps1 @@ -0,0 +1,6 @@ +# Generate HTML next to public/*.mq.md via the Marqdo interpreter. +$ErrorActionPreference = "Stop" +Set-Location (Split-Path $PSScriptRoot -Parent) +cargo build --release -q +& .\target\release\marqdo.exe view output public -o public +Write-Host "OK → public/index.html + public/pages/ (sources: public/**/*.mq.md)" diff --git a/scripts/build-public.sh b/scripts/build-public.sh new file mode 100644 index 0000000..572d012 --- /dev/null +++ b/scripts/build-public.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Generate HTML next to public/*.mq.md via the Marqdo interpreter. +set -euo pipefail +cd "$(dirname "$0")/.." +cargo build --release -q +./target/release/marqdo view output public -o public +echo "OK → public/index.html + public/pages/ (sources: public/**/*.mq.md)" diff --git a/src/catalog.rs b/src/catalog.rs new file mode 100644 index 0000000..2c62b02 --- /dev/null +++ b/src/catalog.rs @@ -0,0 +1,312 @@ +//! OKF-compatible catalog generation: `marqdo catalog` / `sync`. + +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; + +use crate::lex::{classify_source, LineKind}; +use crate::parse::parse_source; + +pub struct CatalogOptions { + pub path: PathBuf, + pub out_dir: PathBuf, +} + +struct ModuleInfo { + id: String, + resource: String, + title: String, + imports: Vec, + exports: Vec, +} + +pub fn write_catalog(opts: CatalogOptions) -> Result<()> { + let root = if opts.path.is_file() { + opts.path + .parent() + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| PathBuf::from(".")) + } else { + opts.path.clone() + }; + let root = root.canonicalize().unwrap_or(root); + + let mut files = Vec::new(); + if opts.path.is_file() { + files.push(opts.path.canonicalize().unwrap_or(opts.path.clone())); + } else { + collect_mq_md(&root, &root, &mut files)?; + files.sort(); + } + + fs::create_dir_all(opts.out_dir.join("modules")) + .with_context(|| format!("create {}", opts.out_dir.display()))?; + + let version = env!("CARGO_PKG_VERSION"); + let mut modules = Vec::new(); + let mut had_err = false; + + for abs in &files { + let rel = abs + .strip_prefix(&root) + .unwrap_or(abs) + .to_string_lossy() + .replace('\\', "/"); + match inspect_file(abs, &rel) { + Ok(info) => modules.push(info), + Err(e) => { + eprintln!("catalog: skip {rel}: {e:#}"); + had_err = true; + } + } + } + + let catalog_yaml = render_catalog_yaml(&modules, version); + fs::write(opts.out_dir.join("catalog.yaml"), catalog_yaml)?; + + let index_md = render_index_md(&modules, version); + fs::write(opts.out_dir.join("index.md"), index_md)?; + + for m in &modules { + let stem = m.resource.replace('/', "__").replace('\\', "__"); + let stem = stem.trim_end_matches(".mq.md"); + let path = opts.out_dir.join("modules").join(format!("{stem}.md")); + fs::write(&path, render_module_md(m, version))?; + } + + eprintln!( + "marqdo catalog: {} module(s) → {}", + modules.len(), + opts.out_dir.display() + ); + if had_err { + anyhow::bail!("catalog completed with errors"); + } + Ok(()) +} + +fn collect_mq_md(root: &Path, dir: &Path, out: &mut Vec) -> Result<()> { + for entry in fs::read_dir(dir)? { + let entry = entry?; + let p = entry.path(); + if p.is_dir() { + collect_mq_md(root, &p, out)?; + } else if p + .file_name() + .and_then(|s| s.to_str()) + .map(|s| s.ends_with(".mq.md")) + .unwrap_or(false) + { + out.push(p); + } + } + Ok(()) +} + +fn inspect_file(abs: &Path, rel: &str) -> Result { + let source = fs::read_to_string(abs)?; + let imports = extract_frontmatter_imports(&source); + let title = extract_frontmatter_title(&source) + .unwrap_or_else(|| rel.trim_end_matches(".mq.md").to_string()); + + let mut exports = Vec::new(); + // Prefer parse for accurate top-level fn names + match parse_source(&source) { + Ok(module) => { + for f in &module.functions { + exports.push(f.name.clone()); + } + } + Err(_) => { + for line in classify_source(&source) { + if line.kind != LineKind::Code { + continue; + } + let t = line.text.trim(); + if let Some(rest) = t.strip_prefix("# ") { + if !rest.starts_with('#') { + exports.push(rest.to_string()); + } + } + } + } + } + + let id = rel.trim_end_matches(".mq.md").to_string(); + Ok(ModuleInfo { + id, + resource: rel.to_string(), + title, + imports, + exports, + }) +} + +fn extract_frontmatter_imports(source: &str) -> Vec { + let source = source.strip_prefix('\u{feff}').unwrap_or(source); + let mut imports = Vec::new(); + let lines: Vec<&str> = source.lines().collect(); + if lines.first().map(|l| l.trim()) != Some("---") { + return imports; + } + for line in lines.iter().skip(1) { + let t = line.trim(); + if t == "---" { + break; + } + if let Some(rest) = t.strip_prefix('>') { + let path = rest.trim(); + if path.ends_with(".mq.md") { + imports.push(path.to_string()); + } + } + } + imports +} + +fn extract_frontmatter_title(source: &str) -> Option { + let source = source.strip_prefix('\u{feff}').unwrap_or(source); + let lines: Vec<&str> = source.lines().collect(); + if lines.first().map(|l| l.trim()) != Some("---") { + return None; + } + for line in lines.iter().skip(1) { + let t = line.trim(); + if t == "---" { + break; + } + if let Some(v) = t.strip_prefix("title:") { + return Some(v.trim().trim_matches('"').to_string()); + } + } + None +} + +fn yaml_escape(s: &str) -> String { + if s.is_empty() + || s.contains(':') + || s.contains('#') + || s.contains('"') + || s.contains('\'') + || s.contains('\n') + || s.starts_with(' ') + { + format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) + } else { + s.to_string() + } +} + +fn render_catalog_yaml(modules: &[ModuleInfo], version: &str) -> String { + let mut out = String::new(); + out.push_str("# GENERATED by marqdo — do not edit by hand\n"); + out.push_str("type: Marqdo Catalog\n"); + out.push_str("title: marqdo-project\n"); + out.push_str("generated:\n"); + out.push_str(&format!(" by: marqdo/{version}\n")); + out.push_str("modules:\n"); + for m in modules { + out.push_str(&format!(" - id: {}\n", yaml_escape(&m.id))); + out.push_str(&format!(" resource: {}\n", yaml_escape(&m.resource))); + out.push_str(&format!(" title: {}\n", yaml_escape(&m.title))); + if m.imports.is_empty() { + out.push_str(" imports: []\n"); + } else { + out.push_str(" imports:\n"); + for i in &m.imports { + out.push_str(&format!(" - {}\n", yaml_escape(i))); + } + } + if m.exports.is_empty() { + out.push_str(" exports: []\n"); + } else { + out.push_str(" exports:\n"); + for e in &m.exports { + out.push_str(&format!(" - name: {}\n", yaml_escape(e))); + out.push_str(" kind: fn\n"); + } + } + } + out +} + +fn render_index_md(modules: &[ModuleInfo], version: &str) -> String { + let mut out = String::new(); + out.push_str("---\n"); + out.push_str("type: Marqdo Catalog\n"); + out.push_str("title: marqdo catalog\n"); + out.push_str("generated:\n"); + out.push_str(&format!(" by: marqdo/{version}\n")); + out.push_str("---\n\n"); + out.push_str("# Catalog\n\n"); + out.push_str("> Generated by Marqdo. Do not edit by hand.\n\n"); + out.push_str("| Module | Resource | Imports |\n"); + out.push_str("|--------|----------|--------|\n"); + for m in modules { + let stem = m.resource.replace('/', "__"); + let stem = stem.trim_end_matches(".mq.md"); + out.push_str(&format!( + "| [{}](modules/{stem}.md) | `{}` | {} |\n", + m.title, + m.resource, + if m.imports.is_empty() { + "—".into() + } else { + m.imports.join(", ") + } + )); + } + out +} + +fn render_module_md(m: &ModuleInfo, version: &str) -> String { + let mut out = String::new(); + out.push_str("---\n"); + out.push_str("type: Marqdo Module\n"); + out.push_str(&format!("title: {}\n", m.title)); + out.push_str(&format!("resource: {}\n", m.resource)); + if m.imports.is_empty() { + out.push_str("depends: []\n"); + } else { + out.push_str("depends:\n"); + for i in &m.imports { + out.push_str(&format!(" - {i}\n")); + } + } + if m.exports.is_empty() { + out.push_str("exports: []\n"); + } else { + out.push_str("exports:\n"); + for e in &m.exports { + out.push_str(&format!(" - {e}\n")); + } + } + out.push_str("generated:\n"); + out.push_str(&format!(" by: marqdo/{version}\n")); + out.push_str("---\n\n"); + out.push_str(&format!("# {}\n\n", m.title)); + out.push_str(&format!( + "> Auto-generated from [`{}`](../../{}). Do not edit by hand.\n\n", + m.resource, m.resource + )); + out.push_str("## Dependencies\n\n"); + if m.imports.is_empty() { + out.push_str("_None_\n\n"); + } else { + for i in &m.imports { + out.push_str(&format!("- `{i}`\n")); + } + out.push('\n'); + } + out.push_str("## Exports\n\n"); + if m.exports.is_empty() { + out.push_str("_None_\n"); + } else { + out.push_str("| Symbol | Kind |\n|--------|------|\n"); + for e in &m.exports { + out.push_str(&format!("| `{e}` | fn |\n")); + } + } + out +} diff --git a/src/diagnostics.rs b/src/diagnostics.rs index 31ed45d..a6051af 100644 --- a/src/diagnostics.rs +++ b/src/diagnostics.rs @@ -23,6 +23,24 @@ impl fmt::Display for Span { } } +/// Format a path for user-facing diagnostics. +/// +/// Strips the Windows extended-length prefix (`\\?\` / `\\?\UNC\`) that +/// `canonicalize` often adds, so messages stay readable. +pub fn display_path(path: &Path) -> String { + let raw = path.display().to_string(); + if let Some(rest) = raw.strip_prefix(r"\\?\UNC\") { + format!(r"\\{rest}") + } else if let Some(rest) = raw.strip_prefix(r"\\?\") { + rest.to_string() + } else if let Some(rest) = raw.strip_prefix("//?/") { + // Some tools emit forward-slash forms + rest.to_string() + } else { + raw + } +} + /// Unified diagnostic: `path:line:col: message` (path omitted if unknown). #[derive(Debug, Error, Clone)] #[error("{}", self.format_message())] @@ -47,7 +65,7 @@ impl Diagnostic { pub fn format_message(&self) -> String { match &self.path { - Some(p) => format!("{}:{}: {}", p.display(), self.span, self.message), + Some(p) => format!("{}:{}: {}", display_path(p), self.span, self.message), None => format!("{}: {}", self.span, self.message), } } @@ -57,3 +75,35 @@ impl Diagnostic { pub fn bail_at(path: Option<&Path>, span: Span, message: impl Into) -> anyhow::Error { anyhow::Error::new(Diagnostic::new(path, span, message)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strips_windows_extended_prefix() { + let p = PathBuf::from(r"\\?\E:\marqdo\examples\errors\bad-arity.mq.md"); + assert_eq!( + display_path(&p), + r"E:\marqdo\examples\errors\bad-arity.mq.md" + ); + } + + #[test] + fn strips_unc_extended_prefix() { + let p = PathBuf::from(r"\\?\UNC\server\share\file.mq.md"); + assert_eq!(display_path(&p), r"\\server\share\file.mq.md"); + } + + #[test] + fn diagnostic_message_uses_clean_path() { + let d = Diagnostic::at( + Path::new(r"\\?\E:\marqdo\x.mq.md"), + Span::new(7, 1), + "missing argument for parameter `x`", + ); + let msg = d.format_message(); + assert!(!msg.contains(r"\\?\")); + assert!(msg.contains(r"E:\marqdo\x.mq.md:7:1:")); + } +} diff --git a/src/lex/mod.rs b/src/lex/mod.rs index a937812..1f0ccff 100644 --- a/src/lex/mod.rs +++ b/src/lex/mod.rs @@ -122,7 +122,7 @@ mod tests { #[test] fn classify_hello_fixture() { - let src = include_str!("../../examples/structure/hello.mq.md"); + let src = include_str!("../../tests/structure/hello.mq.md"); let lines = classify_source(src); assert!(lines.iter().any(|l| l.kind == LineKind::Code && l.text.contains("print"))); assert!(lines.iter().any(|l| l.kind == LineKind::Comment)); diff --git a/src/lib.rs b/src/lib.rs index bfbc477..3466a71 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ pub mod ast; pub mod bytecode; pub mod capture; +pub mod catalog; pub mod debug; pub mod diagnostics; pub mod interp; diff --git a/src/main.rs b/src/main.rs index 5425a7d..f0990d4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,11 +4,12 @@ use std::process::ExitCode; use anyhow::Result; use clap::{Parser, Subcommand, ValueEnum}; -use marqdo::view::{serve, ViewOptions}; +use marqdo::catalog::{write_catalog, CatalogOptions}; +use marqdo::view::{serve, write_static, OutputOptions, ViewOptions}; use marqdo::{Backend, RunOptions}; #[derive(Parser, Debug)] -#[command(name = "marqdo", version, about = "Marqdo interpreter — run and view .mq.md programs")] +#[command(name = "marqdo", version, about = "Marqdo interpreter — run, view, and catalog .mq.md")] struct Cli { #[command(subcommand)] command: Commands, @@ -54,19 +55,54 @@ enum Commands { #[arg(long)] dump_all: bool, }, - /// Browse `.mq.md` structure + execution in a local webpage + /// Browse `.mq.md` structure + execution (live server or static output) View { + #[command(subcommand)] + action: Option, + + /// Path when running the live server (default: `.`) + #[arg(value_name = "PATH", global = true)] + path: Option, + + #[arg(long, default_value = "127.0.0.1", global = true)] + host: String, + + #[arg(long, default_value_t = 7429, global = true)] + port: u16, + + #[arg(long, global = true)] + no_open: bool, + }, + /// Generate OKF-compatible catalog YAML + module pages + Catalog { #[arg(value_name = "PATH")] path: Option, - #[arg(long, default_value = "127.0.0.1")] - host: String, + #[arg(short = 'o', long = "out", default_value = ".marqdo")] + out: PathBuf, + }, + /// Alias for `catalog` + Sync { + #[arg(value_name = "PATH")] + path: Option, - #[arg(long, default_value_t = 7429)] - port: u16, + #[arg(short = 'o', long = "out", default_value = ".marqdo")] + out: PathBuf, + }, +} + +#[derive(Subcommand, Debug)] +enum ViewAction { + /// Write static HTML documentation site + Output { + #[arg(value_name = "PATH")] + path: Option, + + #[arg(short = 'o', long = "out", required = true)] + out: PathBuf, #[arg(long)] - no_open: bool, + no_exec: bool, }, } @@ -115,16 +151,40 @@ fn try_main() -> Result { Ok(0) } Commands::View { + action, path, host, port, no_open, - } => { - serve(ViewOptions { + } => match action { + Some(ViewAction::Output { + path: out_path, + out, + no_exec, + }) => { + write_static(OutputOptions { + path: out_path + .or(path) + .unwrap_or_else(|| PathBuf::from(".")), + out_dir: out, + no_exec, + })?; + Ok(0) + } + None => { + serve(ViewOptions { + 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(".")), - host, - port, - open_browser: !no_open, + out_dir: out, })?; Ok(0) } diff --git a/src/parse/mod.rs b/src/parse/mod.rs index 8751a61..b047ff3 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -525,7 +525,7 @@ mod tests { #[test] fn parse_hello() { - let src = include_str!("../../examples/structure/hello.mq.md"); + let src = include_str!("../../tests/structure/hello.mq.md"); let m = parse_source(src).unwrap(); assert_eq!(m.functions.len(), 1); assert_eq!(m.functions[0].name, "Hello World"); @@ -535,7 +535,7 @@ mod tests { #[test] fn parse_index() { - let src = include_str!("../../examples/structure/nested-call.mq.md"); + let src = include_str!("../../tests/structure/nested-call.mq.md"); let m = parse_source(src).unwrap(); assert!(m.imports.is_empty()); let main = m.functions.iter().find(|f| f.name == "main").unwrap(); @@ -546,7 +546,7 @@ mod tests { #[test] fn parse_branch() { - let src = include_str!("../../examples/structure/branch.mq.md"); + let src = include_str!("../../tests/structure/branch.mq.md"); let m = parse_source(src).unwrap(); let main = &m.functions[0]; assert!(main.body.iter().any(|s| matches!(s, Stmt::Branch { .. }))); diff --git a/src/view/html.rs b/src/view/html.rs index ac5267f..e7dddc8 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -1,6 +1,6 @@ -//! HTML shell for `marqdo view`. +//! HTML shell for `marqdo view` — Apple-inspired monochrome, system fonts only. -use std::path::Path; +use std::path::{Component, Path, PathBuf}; use crate::view::render::FileViewModel; @@ -17,6 +17,333 @@ pub fn escape(s: &str) -> String { .collect() } +/// How navigation hrefs are built. +#[derive(Debug, Clone)] +pub enum LinkMode { + /// Live server: `/file?path=…` + Live, + /// Static export: relative links under `pages/`. + /// `from` is the source rel path of the current page (`None` = index.html). + Static { from: Option }, +} + +fn stylesheet() -> &'static str { + // Inspired by Apple HIG clarity + docs-site layouts (sticky sidebar, readable + // center column, system grays). Monochrome only; no remote fonts. + r#" +:root { + --bg: #f5f5f7; + --surface: #ffffff; + --ink: #1d1d1f; + --muted: #6e6e73; + --line: #d2d2d7; + --line-strong: #1d1d1f; + --fill: #f5f5f7; + --hover: #e8e8ed; + --focus: #0071e3; + --fail-bg: #fff5f5; + --ok-bg: #f5f5f7; + --radius: 12px; + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; +} +* { box-sizing: border-box; } +html { scroll-behavior: smooth; } +body { + margin: 0; + min-height: 100vh; + font-family: var(--sans); + color: var(--ink); + background: var(--bg); + line-height: 1.47; + font-size: 17px; + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; +} +a { color: var(--ink); text-decoration: none; } +a:hover { opacity: 0.72; } +a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +#nav-toggle { position: absolute; opacity: 0; pointer-events: none; } +.topbar { + display: none; + align-items: center; + gap: 0.75rem; + padding: 0.7rem 1rem; + border-bottom: 1px solid var(--line); + background: rgba(255,255,255,0.86); + backdrop-filter: saturate(180%) blur(16px); + -webkit-backdrop-filter: saturate(180%) blur(16px); + position: sticky; + top: 0; + z-index: 20; +} +.topbar .brand { margin: 0; font-size: 1.05rem; font-weight: 600; letter-spacing: -0.022em; } +.nav-btn { + appearance: none; + border: 1px solid var(--line); + background: var(--surface); + color: var(--ink); + border-radius: 10px; + width: 2.35rem; + height: 2.35rem; + font-size: 1.05rem; + line-height: 1; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + transition: background 0.15s ease, border-color 0.15s ease; +} +.nav-btn:hover { background: var(--hover); } +.shell { + display: grid; + grid-template-columns: 280px minmax(0, 1fr); + min-height: 100vh; + max-width: 1400px; + margin: 0 auto; +} +.nav { + border-right: 1px solid var(--line); + padding: 1.75rem 1rem 2.5rem 1.15rem; + overflow: auto; + background: var(--bg); + position: sticky; + top: 0; + align-self: start; + height: 100vh; +} +.nav-brand { display: block; padding: 0 0.35rem; } +.brand { + font-size: 1.35rem; + font-weight: 700; + letter-spacing: -0.03em; + margin: 0 0 0.1rem; +} +.tagline { + color: var(--muted); + font-size: 0.78rem; + margin: 0 0 1.5rem; + font-weight: 500; +} +.nav h2 { + font-size: 0.68rem; + text-transform: uppercase; + letter-spacing: 0.09em; + color: var(--muted); + font-weight: 600; + margin: 1.15rem 0.35rem 0.45rem; +} +.nav ul { list-style: none; padding: 0; margin: 0; } +.nav li { margin: 0.08rem 0; } +.nav a.file { + display: block; + padding: 0.42rem 0.65rem; + border-radius: 8px; + border-bottom: none; + color: var(--ink); + font-family: var(--mono); + font-size: 0.78rem; + transition: background 0.12s ease, color 0.12s ease; +} +.nav a.file:hover { background: var(--hover); opacity: 1; } +.nav a.file.active { + background: var(--ink); + color: #fff; + opacity: 1; + font-weight: 500; +} +.folder { + color: var(--muted); + font-size: 0.72rem; + margin: 1rem 0.35rem 0.35rem; + font-weight: 600; + letter-spacing: 0.01em; +} +.panel-wrap { + min-width: 0; + overflow: auto; + background: var(--bg); +} +main.panel { + padding: 2.25rem 2.5rem 4rem; + margin: 0 auto; + width: 100%; + max-width: 58rem; +} +h1.page { + font-size: clamp(1.75rem, 2.4vw, 2.35rem); + font-weight: 700; + letter-spacing: -0.035em; + margin: 0 0 0.3rem; + line-height: 1.15; +} +.meta { + color: var(--muted); + font-size: 0.88rem; + margin: 0 0 1.75rem; + font-family: var(--mono); +} +.status-pill { + display: inline-block; + font-size: 0.68rem; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; + padding: 0.18rem 0.5rem; + border-radius: 999px; + border: 1px solid var(--line); + margin-left: 0.5rem; + vertical-align: middle; +} +.status-pill.ok { background: var(--surface); color: var(--muted); } +.status-pill.fail { background: var(--ink); color: #fff; border-color: var(--ink); } +section.block { margin: 2rem 0; } +section.block > h2 { + font-size: 0.72rem; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--muted); + font-weight: 600; + margin: 0 0 0.85rem; +} +.structure { + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 0.35rem 0.15rem; + box-shadow: 0 1px 0 rgba(0,0,0,0.02); +} +.card { + border: none; + border-bottom: 1px solid var(--line); + border-radius: 0; + padding: 0.85rem 1.1rem; + margin: 0; + background: transparent; +} +.card:last-child { border-bottom: none; } +.fun-card, .call-card, .branch-card, .loop-card, .ret-card { + border-left: 2px solid var(--line-strong); + padding-left: calc(1.1rem - 2px); +} +.comment-card { + border-left: 2px solid var(--line); + background: transparent; + padding-left: calc(1.1rem - 2px); +} +.badge { + display: inline-block; + font-family: var(--mono); + font-size: 0.66rem; + padding: 0.14rem 0.4rem; + border-radius: 6px; + border: 1px solid var(--line); + background: var(--fill); + color: var(--ink); + margin-right: 0.4rem; + font-weight: 600; + letter-spacing: 0.02em; +} +.params { margin: 0.35rem 0 0; } +.chip { + display: inline-block; + font-family: var(--mono); + font-size: 0.72rem; + padding: 0.14rem 0.45rem; + margin: 0.15rem 0.15rem 0 0; + border-radius: 6px; + background: var(--fill); + border: 1px solid transparent; + color: var(--ink); +} +.nested { + margin: 0.45rem 0 0.15rem 0.15rem; + padding-left: 0.85rem; + border-left: 1px solid var(--line); +} +.arm { + margin: 0.4rem 0; + padding: 0.55rem 0.7rem; + background: var(--fill); + border-radius: 10px; + border: 1px solid transparent; +} +.out, .source { + font-family: var(--mono); + font-size: 0.82rem; + white-space: pre-wrap; + background: var(--surface); + border-radius: var(--radius); + padding: 1rem 1.15rem; + border: 1px solid var(--line); + line-height: 1.55; + box-shadow: 0 1px 0 rgba(0,0,0,0.02); +} +.out.ok { background: var(--ok-bg); } +.out.fail { + background: var(--fail-bg); + border-color: #e4c1c1; + color: var(--ink); + font-weight: 500; +} +.comment-text { color: var(--muted); font-size: 0.92rem; } +code.expr { + font-family: var(--mono); + font-size: 0.84rem; + color: var(--ink); +} +.err { color: var(--ink); font-weight: 600; padding: 0.75rem 1rem; } +.welcome { + max-width: 40rem; + margin: 4rem auto; + text-align: center; +} +.welcome p { color: var(--muted); font-size: 1.05rem; } +.backdrop { + display: none; + position: fixed; + inset: 0; + background: rgba(0,0,0,0.28); + z-index: 25; + animation: fade-in 0.18s ease; +} +@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; } +} +@media (max-width: 800px) { + .topbar { display: flex; } + .nav-brand { display: none; } + .shell { + grid-template-columns: 1fr; + max-width: none; + min-height: calc(100vh - 3.25rem); + } + .nav { + position: fixed; + top: 0; + left: 0; + bottom: 0; + width: min(82vw, 300px); + height: 100vh; + z-index: 30; + transform: translateX(-105%); + transition: transform 0.22s cubic-bezier(0.2, 0.8, 0.2, 1); + border-right: 1px solid var(--line); + background: var(--surface); + box-shadow: 8px 0 32px rgba(0,0,0,0.08); + } + #nav-toggle:checked ~ .shell .nav { transform: translateX(0); } + #nav-toggle:checked ~ .backdrop { display: block; } + main.panel { + max-width: none; + padding: 1.4rem 1.15rem 3rem; + } +} +"# +} + pub fn layout(title: &str, nav: &str, main: &str) -> String { format!( r##" @@ -24,209 +351,41 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { -{title} · marqdo view - - - +{title} · marqdo + + + +
+ +

marqdo

+
+
{main}
+
"##, title = escape(title), + css = stylesheet(), nav = nav, main = main ) } -pub fn nav_html(files: &[std::path::PathBuf], active: Option<&str>) -> String { +pub fn nav_html(files: &[PathBuf], active: Option<&str>, links: &LinkMode) -> String { let mut out = String::from("

Files

    "); let mut last_folder = String::new(); for f in files { @@ -253,16 +412,68 @@ pub fn nav_html(files: &[std::path::PathBuf], active: Option<&str>) -> String { } else { "" }; - let href = format!("/file?path={}", urlencoding_encode(&rel)); + let href = href_file(links, &rel); out.push_str(&format!( - "
  • {}
  • ", + "
  • {}
  • ", + escape(&href), escape(name) )); } out.push_str("
"); + // index link for static pages + if matches!(links, LinkMode::Static { from: Some(_) }) { + let home = href_index(links); + out.insert_str( + 0, + &format!( + "

Index

", + escape(&home) + ), + ); + } out } +fn href_file(links: &LinkMode, target_rel: &str) -> String { + match links { + LinkMode::Live => format!("/file?path={}", urlencoding_encode(target_rel)), + LinkMode::Static { from: None } => format!("pages/{}.html", target_rel), + LinkMode::Static { + from: Some(from_rel), + } => relative_page_href(from_rel, target_rel), + } +} + +fn href_index(links: &LinkMode) -> String { + match links { + LinkMode::Live => "/".into(), + LinkMode::Static { from: None } => "index.html".into(), + LinkMode::Static { + from: Some(from_rel), + } => { + let depth = Path::new(from_rel) + .parent() + .map(|p| p.components().filter(|c| matches!(c, Component::Normal(_))).count()) + .unwrap_or(0); + // pages//file.html → up (depth+1) to OUT_DIR + format!("{}index.html", "../".repeat(depth + 1)) + } + } +} + +/// From `pages/.html` to `pages/.html`. +fn relative_page_href(from_rel: &str, to_rel: &str) -> String { + let from_parent = Path::new(from_rel).parent().unwrap_or_else(|| Path::new("")); + let to_path = PathBuf::from(format!("{to_rel}.html")); + let mut ups = 0usize; + for c in from_parent.components() { + if matches!(c, Component::Normal(_)) { + ups += 1; + } + } + format!("{}{}", "../".repeat(ups), to_path.to_string_lossy().replace('\\', "/")) +} + fn urlencoding_encode(s: &str) -> String { let mut out = String::new(); for b in s.bytes() { @@ -276,43 +487,56 @@ fn urlencoding_encode(s: &str) -> String { out } -pub fn page_index(files: &[std::path::PathBuf], only: Option<&Path>) -> String { - let nav = nav_html(files, None); +pub fn page_index(files: &[PathBuf], only: Option<&Path>, links: &LinkMode) -> String { + let nav = nav_html(files, None, links); let main = if let Some(p) = only { let rel = p.to_string_lossy().replace('\\', "/"); format!( - "

Single file

Open {}

", - urlencoding_encode(&rel), + "

marqdo

Open {}

", + escape(&href_file(links, &rel)), escape(&rel) ) + } else if files.is_empty() { + "

marqdo

No .mq.md files found in this path.

".into() } else { + // Prefer callers to render the first file at `/` / index.html; this is a fallback. + let first = files[0].to_string_lossy().replace('\\', "/"); format!( - "

Browse

Select a .mq.md file in the index. Structure is rendered from the AST; output comes from the same pipeline as marqdo run.

{} file(s)

", - files.len() + "

marqdo

Opening {}…

", + escape(&href_file(links, &first)), + escape(&first) ) }; layout("index", &nav, &main) } -pub fn page_file(files: &[std::path::PathBuf], rel: &str, vm: &FileViewModel) -> String { - let nav = nav_html(files, Some(rel)); +pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkMode) -> String { + let nav = nav_html(files, Some(rel), links); let status = if vm.ok { "ok" } else { "fail" }; + let status_label = if vm.ok { "ok" } else { "fail" }; let out_text = if vm.ok { if vm.stdout.is_empty() { - "(no stdout)".to_string() + "(no stdout)".into() } else { escape(&vm.stdout) } + } else if vm.stderr.is_empty() { + "(skipped)".into() } else { escape(&vm.stderr) }; + let title = Path::new(rel) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or(rel) + .trim_end_matches(".mq.md"); let main = format!( r#" -

{title}

+

{title}{status_label}

{rel}

Structure

- {structure} +
{structure}

Execution

@@ -323,15 +547,11 @@ pub fn page_file(files: &[std::path::PathBuf], rel: &str, vm: &FileViewModel) ->
{source}
"#, - title = escape( - Path::new(rel) - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or(rel) - ), + title = escape(title), + status = status, + status_label = status_label, rel = escape(rel), structure = vm.structure_html, - status = status, out = out_text, source = escape(&vm.source), ); diff --git a/src/view/mod.rs b/src/view/mod.rs index 871de0d..48a6d42 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -1,8 +1,11 @@ //! `marqdo view` — local HTML browser for `.mq.md` structure + output. mod html; +mod output; mod render; +pub use output::{write_static, OutputOptions}; + use std::fs; use std::net::SocketAddr; use std::path::{Path, PathBuf}; @@ -11,7 +14,7 @@ use std::process::Command; use anyhow::{bail, Context, Result}; use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; -use crate::view::html::{escape, page_file, page_index}; +use crate::view::html::{escape, page_file, page_index, LinkMode}; use crate::view::render::{render_module_structure, FileViewModel}; use crate::{run_file_capture, RunOptions}; @@ -22,12 +25,10 @@ pub struct ViewOptions { pub open_browser: bool, } -struct ViewRoot { - /// Directory that paths are resolved against. - root: PathBuf, - /// If Some, only this relative file is in scope (single-file mode). - only_file: Option, - files: Vec, +pub(crate) struct ViewRoot { + pub root: PathBuf, + pub only_file: Option, + pub files: Vec, } /// Block serving until Ctrl+C (process kill). @@ -54,7 +55,7 @@ pub fn serve(opts: ViewOptions) -> Result<()> { Ok(()) } -fn build_root(path: &Path) -> Result { +pub(crate) fn build_root(path: &Path) -> Result { let path = if path.exists() { path.canonicalize().unwrap_or_else(|_| path.to_path_buf()) } else { @@ -124,14 +125,23 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> { let (path_part, query) = split_url(&url); match path_part { "/" | "/index.html" => { - let body = page_index(&root.files, root.only_file.as_deref()); - respond_html(request, body) + // 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)?; + let vm = build_file_view(&resolved, &rel)?; + let body = page_file(&root.files, &rel, &vm, &LinkMode::Live); + 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 vm = build_file_view(&resolved, &rel)?; - let body = page_file(&root.files, &rel, &vm); + let body = page_file(&root.files, &rel, &vm, &LinkMode::Live); respond_html(request, body) } "/api/tree" => { @@ -146,18 +156,22 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> { } } -fn build_file_view(abs: &Path, rel: &str) -> Result { +pub(crate) fn build_file_view(abs: &Path, rel: &str) -> Result { let source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?; let structure = match crate::load::load_module(abs) { Ok(module) => render_module_structure(&module, &source), Err(e) => format!( "
parse/load error: {}
", - escape(&format!("{e:#}")) + escape(&tidy_user_error(&format!("{e:#}"), abs, rel)) ), }; let (stdout, stderr, ok) = match run_file_capture(abs, &RunOptions::default()) { Ok(cap) => (cap.stdout, String::new(), true), - Err(e) => (String::new(), format!("{e:#}"), false), + Err(e) => ( + String::new(), + tidy_user_error(&format!("{e:#}"), abs, rel), + false, + ), }; Ok(FileViewModel { rel_path: rel.to_string(), @@ -169,6 +183,30 @@ fn build_file_view(abs: &Path, rel: &str) -> Result { }) } +/// Prefer view-relative paths and strip Windows `\\?\` noise in error text. +fn tidy_user_error(msg: &str, abs: &Path, rel: &str) -> String { + use crate::diagnostics::display_path; + let mut s = msg.to_string(); + let abs_disp = abs.display().to_string(); + let abs_clean = display_path(abs); + for candidate in [ + abs_disp.as_str(), + abs_clean.as_str(), + &abs_disp.replace('/', "\\"), + &abs_clean.replace('/', "\\"), + &abs_disp.replace('\\', "/"), + &abs_clean.replace('\\', "/"), + ] { + if !candidate.is_empty() { + s = s.replace(candidate, rel); + } + } + // Leftover extended prefixes anywhere in the message + s = s.replace(r"\\?\", ""); + s = s.replace("//?/", ""); + s +} + fn resolve_rel(root: &ViewRoot, rel: &str) -> Result { if rel.is_empty() { bail!("missing path"); diff --git a/src/view/output.rs b/src/view/output.rs new file mode 100644 index 0000000..56d1b78 --- /dev/null +++ b/src/view/output.rs @@ -0,0 +1,73 @@ +//! Static HTML export: `marqdo view output`. + +use std::fs; +use std::path::PathBuf; + +use anyhow::{Context, Result}; + +use crate::view::html::{page_file, page_index, LinkMode}; +use crate::view::{build_file_view, build_root, ViewRoot}; + +pub struct OutputOptions { + pub path: PathBuf, + pub out_dir: PathBuf, + pub no_exec: bool, +} + +pub fn write_static(opts: OutputOptions) -> Result<()> { + let root = build_root(&opts.path)?; + fs::create_dir_all(&opts.out_dir) + .with_context(|| format!("create {}", opts.out_dir.display()))?; + + let pages_root = opts.out_dir.join("pages"); + let mut first_page_html: Option = None; + + for rel_pb in &root.files { + let rel = rel_pb.to_string_lossy().replace('\\', "/"); + let abs = resolve_abs(&root, &rel)?; + let mut vm = build_file_view(&abs, &rel)?; + if opts.no_exec { + vm.stdout.clear(); + vm.stderr = "execution skipped (--no-exec)".into(); + vm.ok = true; + } + let links = LinkMode::Static { + from: Some(rel.clone()), + }; + let html = page_file(&root.files, &rel, &vm, &links); + let out_file = pages_root.join(format!("{rel}.html")); + if let Some(parent) = out_file.parent() { + fs::create_dir_all(parent)?; + } + fs::write(&out_file, html).with_context(|| format!("write {}", out_file.display()))?; + + if first_page_html.is_none() { + // index.html = first file (same content, links rooted at OUT_DIR) + first_page_html = Some(page_file( + &root.files, + &rel, + &vm, + &LinkMode::Static { from: None }, + )); + } + } + + let index_html = first_page_html.unwrap_or_else(|| { + page_index(&root.files, root.only_file.as_deref(), &LinkMode::Static { from: None }) + }); + let index_path = opts.out_dir.join("index.html"); + fs::write(&index_path, index_html) + .with_context(|| format!("write {}", index_path.display()))?; + + eprintln!( + "marqdo view output: {} page(s) → {}", + root.files.len(), + opts.out_dir.display() + ); + Ok(()) +} + +fn resolve_abs(root: &ViewRoot, rel: &str) -> Result { + let abs = root.root.join(rel); + Ok(abs.canonicalize().unwrap_or(abs)) +} diff --git a/src/view/render.rs b/src/view/render.rs index b34085b..ab97936 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -413,7 +413,7 @@ mod tests { #[test] fn structure_keeps_comments_and_surface_expr() { - let src = include_str!("../../examples/structure/nested-call.mq.md"); + let src = include_str!("../../tests/structure/nested-call.mq.md"); let module = crate::parse::parse_source(src).unwrap(); let html = render_module_structure(&module, src); assert!(html.contains("comment-card")); diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..f629c04 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,19 @@ +# 测试夹具(金样例) + +金样例与集成测试同处 `tests/`,用子目录区分类别。设计见 [examples-and-tests.md](../doc/design/examples-and-tests.md)。 + +| 路径 | 内容 | +|------|------| +| [`structure/`](structure/) | 函数、调用、分支、循环、表、导入、位置实参 | +| [`keywords/`](keywords/) | `print`、布尔与 `and`/`or`/`not` | +| [`errors/`](errors/) | 期望失败(诊断文案) | +| [`gold.rs`](gold.rs) | 集成测试:跑上述夹具并比对 stdout / stderr | + +```bash +cargo test +marqdo run tests/structure/hello.mq.md +marqdo view tests +marqdo catalog tests -o .marqdo +``` + +面向访客的可执行介绍在 [`public/`](../public/)(不含 `errors/`),见 [user-site.md](../doc/design/user-site.md)。 diff --git a/examples/errors/.gitkeep b/tests/errors/.gitkeep similarity index 100% rename from examples/errors/.gitkeep rename to tests/errors/.gitkeep diff --git a/examples/errors/bad-arity.mq.md b/tests/errors/bad-arity.mq.md similarity index 100% rename from examples/errors/bad-arity.mq.md rename to tests/errors/bad-arity.mq.md diff --git a/examples/errors/syntax-bad-line.mq.md b/tests/errors/syntax-bad-line.mq.md similarity index 100% rename from examples/errors/syntax-bad-line.mq.md rename to tests/errors/syntax-bad-line.mq.md diff --git a/examples/errors/undefined-var.mq.md b/tests/errors/undefined-var.mq.md similarity index 100% rename from examples/errors/undefined-var.mq.md rename to tests/errors/undefined-var.mq.md diff --git a/examples/errors/unknown-fn.mq.md b/tests/errors/unknown-fn.mq.md similarity index 100% rename from examples/errors/unknown-fn.mq.md rename to tests/errors/unknown-fn.mq.md diff --git a/tests/gold.rs b/tests/gold.rs index 7a09212..5d1f990 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -28,52 +28,59 @@ fn assert_err(path: &str, substr: &str) { #[test] fn structure_hello() { - assert_out("examples/structure/hello.mq.md", "Hello World!"); + assert_out("tests/structure/hello.mq.md", "Hello World!"); } #[test] fn structure_nested_call() { - assert_out("examples/structure/nested-call.mq.md", "Hello World!"); + assert_out("tests/structure/nested-call.mq.md", "Hello World!"); } #[test] fn structure_positional_call() { assert_out( - "examples/structure/positional-call.mq.md", + "tests/structure/positional-call.mq.md", "Hello Marqdo!\nHello World!", ); } #[test] fn structure_branch() { - assert_out("examples/structure/branch.mq.md", "零"); + assert_out("tests/structure/branch.mq.md", "零"); } #[test] fn structure_loop() { assert_out( - "examples/structure/loop.mq.md", - "3\n2\n1\n今天吃苹果\n今天吃梨", + "tests/structure/loop.mq.md", + "3 +2 +1 +今天吃苹果 +今天吃梨", ); } #[test] fn structure_collection() { - assert_out("examples/structure/collection.mq.md", "苹果\n梨\n桃"); + assert_out("tests/structure/collection.mq.md", "苹果 +梨 +桃"); } #[test] fn structure_import() { assert_out( - "examples/structure/import/main.mq.md", - "42\n你好,Marqdo!", + "tests/structure/import/main.mq.md", + "42 +你好,Marqdo!", ); } #[test] fn keywords_print() { assert_out( - "examples/keywords/print.mq.md", + "tests/keywords/print.mq.md", "named form\npositional", ); } @@ -81,7 +88,7 @@ fn keywords_print() { #[test] fn keywords_bool_logic() { assert_out( - "examples/keywords/bool-logic.mq.md", + "tests/keywords/bool-logic.mq.md", "ok\nnone-falsy", ); } @@ -89,7 +96,7 @@ fn keywords_bool_logic() { #[test] fn error_undefined_var() { assert_err( - "examples/errors/undefined-var.mq.md", + "tests/errors/undefined-var.mq.md", "undefined variable `missing`", ); } @@ -97,7 +104,7 @@ fn error_undefined_var() { #[test] fn error_unknown_fn() { assert_err( - "examples/errors/unknown-fn.mq.md", + "tests/errors/unknown-fn.mq.md", "unknown function `no_such_fn`", ); } @@ -105,7 +112,7 @@ fn error_unknown_fn() { #[test] fn error_bad_arity() { assert_err( - "examples/errors/bad-arity.mq.md", + "tests/errors/bad-arity.mq.md", "missing argument for parameter `x`", ); } @@ -113,7 +120,7 @@ fn error_bad_arity() { #[test] fn error_syntax_bad_line() { assert_err( - "examples/errors/syntax-bad-line.mq.md", + "tests/errors/syntax-bad-line.mq.md", "unrecognized statement", ); } @@ -131,7 +138,7 @@ fn assert_out_backend(path: &str, backend: &str, expect: &str) { #[test] fn bytecode_hello() { assert_out_backend( - "examples/structure/hello.mq.md", + "tests/structure/hello.mq.md", "bytecode", "Hello World!", ); @@ -139,31 +146,37 @@ fn bytecode_hello() { #[test] fn bytecode_branch() { - assert_out_backend("examples/structure/branch.mq.md", "bytecode", "零"); + assert_out_backend("tests/structure/branch.mq.md", "bytecode", "零"); } #[test] fn bytecode_loop() { assert_out_backend( - "examples/structure/loop.mq.md", + "tests/structure/loop.mq.md", "bytecode", - "3\n2\n1\n今天吃苹果\n今天吃梨", + "3 +2 +1 +今天吃苹果 +今天吃梨", ); } #[test] fn bytecode_collection() { assert_out_backend( - "examples/structure/collection.mq.md", + "tests/structure/collection.mq.md", "bytecode", - "苹果\n梨\n桃", + "苹果 +梨 +桃", ); } #[test] fn bytecode_print_keyword() { assert_out_backend( - "examples/keywords/print.mq.md", + "tests/keywords/print.mq.md", "bytecode", "named form\npositional", ); @@ -172,7 +185,7 @@ fn bytecode_print_keyword() { #[test] fn bytecode_bool_logic() { assert_out_backend( - "examples/keywords/bool-logic.mq.md", + "tests/keywords/bool-logic.mq.md", "bytecode", "ok\nnone-falsy", ); @@ -181,7 +194,7 @@ fn bytecode_bool_logic() { #[test] fn bytecode_nested_call() { assert_out_backend( - "examples/structure/nested-call.mq.md", + "tests/structure/nested-call.mq.md", "bytecode", "Hello World!", ); @@ -190,7 +203,7 @@ fn bytecode_nested_call() { #[test] fn bytecode_positional_call() { assert_out_backend( - "examples/structure/positional-call.mq.md", + "tests/structure/positional-call.mq.md", "bytecode", "Hello Marqdo!\nHello World!", ); @@ -199,8 +212,62 @@ fn bytecode_positional_call() { #[test] fn bytecode_import() { assert_out_backend( - "examples/structure/import/main.mq.md", + "tests/structure/import/main.mq.md", "bytecode", - "42\n你好,Marqdo!", + "42 +你好,Marqdo!", ); } + +#[test] +fn catalog_writes_yaml() { + let dir = tempfile_dir("mq-cat"); + let (code, _, stderr) = run(&[ + "catalog", + "tests", + "-o", + dir.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{stderr}"); + let yaml = std::fs::read_to_string(dir.join("catalog.yaml")).unwrap(); + assert!(yaml.contains("type: Marqdo Catalog")); + assert!(yaml.contains("structure/hello")); + assert!(yaml.contains("utils.mq.md"), "{yaml}"); + assert!( + yaml.contains("跨文件导入示例") || yaml.contains("imports:\n - utils.mq.md"), + "{yaml}" + ); +} + +#[test] +fn view_output_writes_html() { + let dir = tempfile_dir("mq-site"); + let (code, _, stderr) = run(&[ + "view", + "output", + "tests/structure/hello.mq.md", + "-o", + dir.to_str().unwrap(), + "--no-exec", + ]); + assert_eq!(code, 0, "{stderr}"); + let index = std::fs::read_to_string(dir.join("index.html")).unwrap(); + assert!(index.contains("marqdo")); + assert!(!index.contains("fonts.googleapis.com")); + assert!(index.contains("#ffffff") || index.contains("--surface: #ffffff")); + assert!(index.contains("nav-toggle")); + assert!(dir.join("pages").join("hello.mq.md.html").exists()); +} + +fn tempfile_dir(prefix: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "{prefix}-{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} diff --git a/examples/keywords/bool-logic.mq.md b/tests/keywords/bool-logic.mq.md similarity index 100% rename from examples/keywords/bool-logic.mq.md rename to tests/keywords/bool-logic.mq.md diff --git a/examples/keywords/print.mq.md b/tests/keywords/print.mq.md similarity index 100% rename from examples/keywords/print.mq.md rename to tests/keywords/print.mq.md diff --git a/examples/structure/branch.mq.md b/tests/structure/branch.mq.md similarity index 100% rename from examples/structure/branch.mq.md rename to tests/structure/branch.mq.md diff --git a/examples/structure/collection.mq.md b/tests/structure/collection.mq.md similarity index 100% rename from examples/structure/collection.mq.md rename to tests/structure/collection.mq.md diff --git a/examples/structure/hello.mq.md b/tests/structure/hello.mq.md similarity index 100% rename from examples/structure/hello.mq.md rename to tests/structure/hello.mq.md diff --git a/examples/structure/import/main.mq.md b/tests/structure/import/main.mq.md similarity index 100% rename from examples/structure/import/main.mq.md rename to tests/structure/import/main.mq.md diff --git a/examples/structure/import/utils.mq.md b/tests/structure/import/utils.mq.md similarity index 100% rename from examples/structure/import/utils.mq.md rename to tests/structure/import/utils.mq.md diff --git a/examples/structure/loop.mq.md b/tests/structure/loop.mq.md similarity index 100% rename from examples/structure/loop.mq.md rename to tests/structure/loop.mq.md diff --git a/examples/structure/nested-call.mq.md b/tests/structure/nested-call.mq.md similarity index 100% rename from examples/structure/nested-call.mq.md rename to tests/structure/nested-call.mq.md diff --git a/examples/structure/positional-call.mq.md b/tests/structure/positional-call.mq.md similarity index 100% rename from examples/structure/positional-call.mq.md rename to tests/structure/positional-call.mq.md