diff --git a/.gitignore b/.gitignore index e88b78f..5ef0e56 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ /bin/ **/*.analysis.json.tmp **/*.ast.json.tmp + +__pycache__/ +*.pyc diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml new file mode 100644 index 0000000..6ed6c94 --- /dev/null +++ b/.woodpecker/main.yml @@ -0,0 +1,64 @@ +# Woodpecker CI for marqdo-lint. +# +# The Analysis contract is pinned to the public rc.4 Linux archive. Every lane +# verifies the archive SHA-256; no unpinned core is downloaded. +when: + event: [push, pull_request] + +steps: + no-legacy: + image: rust:1.100-bookworm + commands: + - apt-get update && apt-get install -y --no-install-recommends ca-certificates ripgrep + - ./scripts/check-no-legacy.sh + - test -f .woodpecker/main.yml + - test -f CHANGELOG.md + - test -f docs/PROTOCOL_BASELINE.md + + test: + image: rust:1.100-bookworm + commands: + - apt-get update + - apt-get install -y --no-install-recommends ca-certificates curl python3 python3-jsonschema + - rustup component add clippy rustfmt + - | + set -eux + curl -fsSL -o /tmp/marqdo.tar.gz "$CORE_URL" + echo "$CORE_ARCHIVE_SHA /tmp/marqdo.tar.gz" | sha256sum -c - + mkdir -p /tmp/marqdo + tar -xzf /tmp/marqdo.tar.gz -C /tmp/marqdo --strip-components=1 + export MARQDO_BIN=/tmp/marqdo/marqdo + sha256sum "$MARQDO_BIN" + cargo fmt --all -- --check + cargo clippy --all-targets -- -D warnings + cargo test --locked + ./scripts/package-tool.sh + export MARQDO_TOOL_HOME="$PWD/target/validation/registry" + "$MARQDO_BIN" tool install .cache/tool-bundle/tool.json + "$MARQDO_BIN" tool list --json + "$MARQDO_BIN" lint examples/nested/inventory.mq.md --format json + "$MARQDO_BIN" tool remove lint + environment: + CORE_URL: "https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v3.0.0-rc.4/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz" + CORE_ARCHIVE_SHA: "9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8" + + acceptance: + image: rust:1.100-bookworm + depends_on: [test, no-legacy] + commands: + - apt-get update + - apt-get install -y --no-install-recommends ca-certificates curl python3 python3-jsonschema git + - rustup component add clippy rustfmt + - | + set -eux + curl -fsSL -o /tmp/marqdo.tar.gz "$CORE_URL" + echo "$CORE_ARCHIVE_SHA /tmp/marqdo.tar.gz" | sha256sum -c - + mkdir -p /tmp/marqdo + tar -xzf /tmp/marqdo.tar.gz -C /tmp/marqdo --strip-components=1 + export MARQDO_BIN=/tmp/marqdo/marqdo + python3 scripts/validate-control-flow.py "$MARQDO_BIN" \ + --report "docs/validation/452e9a32bd9e40dba427d4180691c58bab74449e.json" + sha256sum "$MARQDO_BIN" + environment: + CORE_URL: "https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v3.0.0-rc.4/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz" + CORE_ARCHIVE_SHA: "9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8" diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..db3ad22 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog + +## 0.2.0 + +### Changed + +- 适配 Marqdo `3.0.0-rc.4` 的公共 Analysis revision 3 与 CLI Tool revision 1。 +- 只执行一次 `check ENTRY --emit PATH`;删除每个模块的 `inspect --ast` 机器 + 调用和第二套 Markdown 解析。 +- 唯一源码改为 `modules[].source`,并在信任 span 前校验 + `sha256(source) == source_digest`。 +- 标题、模式、完整 section range 和函数归属只来自 `units`;`heading_span` + 只表示标题本身。 +- 引用规则改为读取 `references[].state`,区分 `missing`、`not_loaded`、 + `ambiguous`、`external`、`invalid` 和 `outside_scope`。 +- 调用规则读取 `calls[].state/target_kind/target_owner/reason`;动态/未绑定 + 调用只作信息提示。 +- Tool manifest 改为 `requires: {api_revision: 1, analysis: 3}`,删除旧字段。 +- 版本门槛改为 SemVer `>=3.0.0-rc.4,<4.0.0`。 + +### Removed + +- 旧 Analysis 字段集合、旧核心分支、旧门禁脚本和旧 fixture。 +- 运行期 `comrak` 依赖;渲染示例保留在 dev-dependency。 +- 运行时对 `inspect`、协议协商环境变量和旧 Tool manifest 的支持。 + +### Added + +- 新增 `MQD-LINK-001/002/003` 和 `MQD-CALL-001`。 +- 新增 `scripts/check-no-legacy.sh`、单核心验收 manifest 和 Woodpecker CI。 +- 新增旧 revision 3、坏摘要、坏 span、坏 Tool manifest 的 fail-closed 测试。 diff --git a/Cargo.lock b/Cargo.lock index 41956df..703b4f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -350,7 +350,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "marqdo-lint" -version = "0.1.0-rc.1" +version = "0.2.0" dependencies = [ "assert_cmd", "clap", diff --git a/Cargo.toml b/Cargo.toml index c28f2b7..3ede48b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,13 +1,12 @@ [package] name = "marqdo-lint" -version = "0.1.0-rc.1" +version = "0.2.0" edition = "2021" rust-version = "1.89" description = "面向 Marqdo 可执行文档的独立可读性检查工具" [dependencies] clap = { version = "4.5", features = ["derive"] } -comrak = { version = "=1.0.0", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["float_roundtrip"] } sha2 = "0.10" @@ -20,5 +19,6 @@ unicode-normalization = "0.1" walkdir = "2" [dev-dependencies] +comrak = { version = "=1.0.0", default-features = false } assert_cmd = "2" predicates = "3" diff --git a/README.md b/README.md index d50c767..16406e8 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,20 @@ # marqdo-lint -`marqdo-lint` 是面向 Marqdo `.mq.md` 可执行文档的独立可读性检查工具。它把真实 Markdown AST 与公开 Analysis v2/v3 对齐,检查分支、循环、叙述和说明的阅读质量,而不重新解释语言语义。 +`marqdo-lint` 是面向 Marqdo `.mq.md` 可执行文档的独立可读性检查工具。它只 +消费当前公开协议:用一次 `check --emit` 取得 Analysis revision 3,用 +`modules[].document` 作为 Markdown 容器,用 `modules[].source` 作为唯一源码, +检查分支、循环、链接、调用、叙述和说明的阅读质量。 ## 当前基线 -- 冻结 Marqdo `3.0.0-rc.1` 和 `3.0.0-rc.2`,对应发布提交见 [协议基线](docs/PROTOCOL_BASELINE.md) +- 冻结 Marqdo `3.0.0-rc.4`,源码 `452e9a32…`,详见 [协议基线](docs/PROTOCOL_BASELINE.md) - Markdown Profile `marqdo.md.v1` -- Analysis v2/v3 与 CLI Tool v1 +- Analysis revision 3(当前字段集合)与 CLI Tool revision 1 - Rust 1.89 或更新版本 +- Lint 版本 `0.2.0` + +旧核心、旧 Analysis 字段集合和旧 Tool manifest 都会被明确拒绝,没有兼容 +分支。 ## 构建 @@ -15,13 +22,16 @@ cargo build --locked ``` -运行测试时需要兼容的冻结核心,并通过 `MARQDO_BIN` 指定其绝对路径。工具通过 `--version`、`inspect --ast --json` 和 `check --json --emit` 读取公开信息。双核心发布门禁见 [验收记录](docs/VALIDATION.md)。 +运行测试时需要兼容的冻结核心,并通过 `MARQDO_BIN` 指定绝对路径。工具只 +调用 `--version` 与一次 `check ENTRY --json --emit PATH`;`inspect` 不在 +机器路径中。完整验收见 [VALIDATION.md](docs/VALIDATION.md)。 ## 使用 ```bash marqdo-lint index.mq.md marqdo-lint . --profile recommended --format json +marqdo-lint index.mq.md --refs marqdo-lint explain MQD-BRANCH-001 marqdo-lint rules marqdo-lint index.mq.md --fix safe --dry-run @@ -34,10 +44,10 @@ marqdo tool install .cache/tool-bundle/tool.json marqdo lint index.mq.md ``` -直接运行时,`MARQDO_BIN` 可以指定冻结核心的绝对路径。工具默认从当前目录读取 `marqdo-lint.toml`,也可使用 `--config FILE` 指定配置。目录内有 `index.mq.md` 时从该入口加载项目,否则递归查找 `.mq.md` 文件。 +直接运行时,`MARQDO_BIN` 可以指定冻结核心的绝对路径。工具默认从当前目录 +读取 `marqdo-lint.toml`,也可使用 `--config FILE`。目录内有 `index.mq.md` +时从该入口加载项目,否则递归查找 `.mq.md` 文件。 -默认 `--fail-on warning`。退出码 `0` 表示检查完成且低于门槛,`1` 表示达到门槛或安全修复被拒绝,`2` 表示分析不可用、配置或工具错误。JSON 报告格式和配置示例见 [命令参考](docs/CLI.md)。 [规则目录](docs/RULES.md) 收录各规则的正反例。 - -## 发布状态 - -当前按 0.1.0 候选实现。核心仓库内示例的应用试跑不等于“两个独立应用仓库”发布门禁,最终限制以 `docs/VALIDATION.md` 为准。 +默认 `--fail-on warning`。退出码 `0` 表示检查完成且低于门槛,`1` 表示达到 +门槛或安全修复被拒绝,`2` 表示分析不可用、协议错误、配置或工具错误。JSON +报告格式见 [命令参考](docs/CLI.md),规则目录见 [RULES.md](docs/RULES.md)。 diff --git a/RFC-LINT-0001-MARQDO-READABLE-EXECUTABLE-DOCUMENTS.md b/RFC-LINT-0001-MARQDO-READABLE-EXECUTABLE-DOCUMENTS.md index 7884f15..25a8a35 100644 --- a/RFC-LINT-0001-MARQDO-READABLE-EXECUTABLE-DOCUMENTS.md +++ b/RFC-LINT-0001-MARQDO-READABLE-EXECUTABLE-DOCUMENTS.md @@ -3,7 +3,7 @@ > **状态:Proposed(待讨论、未实现)** > **定位:** 独立 CLI Tool + 一套以「阅读体验」为中心的可执行文档风格规范。不是传统源码 formatter,也不是新版语法定义。 > **审阅基线:** `cflmy/marqdo-cli` `master@f7a5a7b0163bf5229ed09adfffd892f9899e6667`;旧版风格来源 `cflmy/marqdo@1c55baabd570e18b9da8f9057cef2f848e176690`。开始开发前必须刷新 SHA 和文档协议。 -> **权威语义来源:** `spec/mapping.md`、`spec/markdown-profile.md`、`spec/analysis-v2.md`、`spec/tool-v1.md`。所有风格建议均从属于 Marqdo 实际语言语义。 +> **权威语义来源:** `spec/mapping.md`、`spec/markdown-profile.md`、`spec/analysis.md`、`spec/schemas/analysis.schema.json`、`spec/cli-tool.md`。所有风格建议均从属于 Marqdo 实际语言语义。 > **目标受众:** 未阅读任何历史讨论、准备独立实现 `marqdo-lint` 的开发者、贡献者和 `.mq.md` 作者。 > **发布原则:** 冻结 Marqdo 核心二进制;只增加 Lint 的仓库、规则、配置和测试,不为 Lint 新增核心指令或私有 ABI。 @@ -368,15 +368,15 @@ index.mq.md:13:1 warning MQD-BRANCH-001 --- -## 7. 技术架构:Markdown AST × Analysis v2 +## 7. 技术架构:modules[].document × Analysis revision 3 **绝不能只用行首正则或缩进计数推断执行流。** 最重要的实现是建立两种视图的对齐关系: -- **Markdown 视图:** `marqdo inspect FILE --ast --json` 返回冻结 Markdown Profile 下的 AST;`List(ordered,start,tight) → Item → Paragraph → Code/Strong/Emph` 保留结构和 UTF-8 byte span。 -- **执行视图:** `marqdo check FILE --emit path` 成功后,取得 Analysis v2 的函数、语句、控制结构、静态调用绑定和 source span。Analysis 不保存完整列表排版结构。 -- **源码快照:** 精确读取 `.mq.md` 原始 UTF-8 字节,用 span 截取载体原文、自然语言和空行。 +- **Markdown 视图:** `modules[].document` 是冻结 Markdown Profile 下的 canonical AST;`List(ordered,start,tight) → Item → Paragraph → Code/Strong/Emph` 保留结构和 UTF-8 byte span。 +- **执行视图:** `marqdo check FILE --emit path` 成功后,取得 Analysis revision 3 的函数、语句、控制结构、静态调用绑定和 source span。Markdown 排版结构由同一 artifact 的 `modules[].document` 提供。 +- **源码快照:** `modules[].source` 是唯一源码;先校验 `sha256(source) == source_digest`,再用 span 截取载体原文、自然语言和空行。不重新打开 `relative_path`。 -语言验证失败时 `check --emit` 不产生 Analysis 工件;Lint **必须区分「分析不可用」与「没有检测到违规」**。可以提供无语义保证的文本级/Markdown 结构建议,但不得假装已经生成了可执行 IR。若 `inspect --ast --json` 也因加载失败不可用,可在 Lint 内使用**严格匹配冻结 CommonMark/GFM 配置的 Markdown parser 仅作降级文档分析**;不要开发第二套 Marqdo 解释器或用正则重新解释控制流。 +语言验证失败时 `check --emit` 不产生 Analysis 工件;Lint **必须区分「分析不可用」与「没有检测到违规」**,返回 `analysis_incomplete` 和退出码 2。没有 artifact 时不运行依赖 document 的规则,不开发第二套 Marqdo 解释器或用正则重新解释控制流。 ### 7.1 内部数据模型 @@ -431,7 +431,7 @@ for each function in Analysis: compare nested Markdown item tree with nested semantic control tree ``` -细节:Analysis v2 可能只暴露分支首个 span,没有独立 `else` / `end` 的完整节点;实现时必须同时用源文件 + Markdown AST 来关联,不能虚构 Analysis 未提供的字段。若关联不唯一,应返回 `analysis_incomplete` / 低置信度提示而非冒险断言。 +细节:当前 Analysis revision 3 为分支臂、循环和跳转提供明确 span;实现按 span 与语句体路径关联,不能虚构 Analysis 未提供的字段。若关联不唯一,应返回 `analysis_incomplete` / 低置信度提示而非冒险断言。 --- @@ -691,8 +691,8 @@ Profiles:`recommended` 正常推荐,`strict-doc` 教学/公开 API,`minima - [Marqdo AST→Program Mapping](https://github.com/cflmy/marqdo-cli/blob/f7a5a7b0163bf5229ed09adfffd892f9899e6667/spec/mapping.md):列表与引用块只是容器,真正的控制流由关键字决定。 - [Markdown Profile](https://github.com/cflmy/marqdo-cli/blob/f7a5a7b0163bf5229ed09adfffd892f9899e6667/spec/markdown-profile.md):冻结 AST、UTF-8 source span 和列表嵌套。 - [Frontend mapping](https://github.com/cflmy/marqdo-cli/blob/f7a5a7b0163bf5229ed09adfffd892f9899e6667/crates/marqdo-frontend/src/map.rs):从 Markdown 容器中提取 `Code/Strong/Emph` 并编译分支、循环。 -- [Analysis v2](https://github.com/cflmy/marqdo-cli/blob/f7a5a7b0163bf5229ed09adfffd892f9899e6667/spec/analysis-v2.md):静态 IR 及位置数据。 -- [Tool v1](https://github.com/cflmy/marqdo-cli/blob/f7a5a7b0163bf5229ed09adfffd892f9899e6667/spec/tool-v1.md):外部工具注册。 +- [Analysis revision 3](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.4/spec/analysis.md):静态 IR、source、document、units 及位置数据。 +- [CLI Tool revision 1](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.4/spec/cli-tool.md):外部工具注册。 **旧版作者风格(借鉴而非执行依据):** diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e053c25..fe239b9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,30 +1,45 @@ # 架构 -`marqdo-lint` 将同一份 Markdown 源码投影为三个只读视图,再建立仅供 Lint 使用的结构对齐: +`marqdo-lint` 只消费当前 Marqdo 公开协议: ```text -SourceSnapshot ── MarkdownTree ──┐ - │ ├─ RuleContext ─ Rules ─ Diagnostics - └──── ExecutionProjection ┘ │ - └──── ReadableControlTree +check ENTRY --emit PATH + │ + ├── modules[].source ────── SourceSnapshot + ├── modules[].document ─── MarkdownTree(容器/载体) + ├── modules[].units ────── 标题、模式、完整 section range + └── functions/references/calls/resources + │ + ReadableControlTree ─ Rules ─ Diagnostics ─ human / JSON ``` ## 模块职责 -- `input`:调用公开 CLI、校验协议、读取真实 AST/Analysis,并在 AST 不可用时提供严格同配置的文档级 comrak 降级。 -- `model`:保存精确字节、半开 byte span、标题段、列表项、执行载体和静态语义节点。 -- `alignment` 为每个函数按源码 span 索引执行载体,按语句体路径匹配有序分支臂、嵌套控制以及最近循环目标。关联不唯一时,函数保留可独立确认的文档诊断。 -- `engine`:为每个函数复用同一份结构对齐和度量,并组装诊断。 -- `rules`:稳定 ID、元数据与纯检测逻辑。规则不各自调用 CLI,也不分别实现输出。 -- `metrics`:函数级叙述比例和解释覆盖,不把文字长度当成正确性证明。 +- `input`:唯一的 CLI 适配层。执行一次 `check --emit`,捕获 artifact 字节 + 与摘要,校验 SemVer 范围和协议,然后用 artifact source 构造 + `SourceDocument`。不会为了读取模块重新打开 `relative_path`。 +- `model`:严格、闭合的 Analysis revision 3 类型;`SourceSnapshot`; + `MarkdownTree` 只从 `document` 与 `units` 建立,不解析第二套 Markdown。 +- `alignment`:以函数 id 找到 Exec H2,按 span/语句路径对齐分支臂、嵌套控制 + 和最近循环目标。没有版本分支,也没有对旧制品的“尽力解析”。 +- `engine`:为每个函数复用同一份对齐和度量,组装诊断。 +- `rules`:稳定 ID 与纯检测逻辑;规则不调用 CLI,不各自实现语言解析。 + Reference 规则只读 `references[].state`,Call 规则只读 + `calls[].state`。`not_loaded` 是“未核验”,不是断链。 +- `metrics`:函数级叙述比例和解释覆盖,不把文字长度当作正确性证明。 - `diagnostics`:统一 human/JSON 渲染、排序、失败阈值和退出码。 -- `config`:profile、规则覆盖和带原因的文件级抑制。 -- `fix`:只处理可证明等价的局部空白,写回前比较规范化 AST 与语义指纹。 +- `fix`:只处理可证明等价的局部空白。写回前在临时项目中重新执行同一条 + `check --emit`,比较规范化 document、执行载荷与 Analysis 指纹。 ## 不变量 -1. Analysis 决定真实执行结构,Markdown AST 决定视觉容器;二者都不能由行首正则替代。 -2. Knowledge、表格、代码围栏、数学、链接资源和其他惰性区域不产生执行语句。 -3. `ReadableControlTree` 不是解释器,不求值、不绑定新调用,也不补全语言没有提供的语义字段。 -4. 所有诊断由同一规则上下文产生,human 与 JSON 不各跑一套检测。 -5. 自动修复先验证再写回;任何歧义都保持原文件不变。 +1. 一个入口一次 `check --emit`;`modules[].document` 是唯一 Markdown AST + 来源,Lint 不运行 `inspect`。 +2. `modules[].source` 是唯一源码;span 只相对该字符串解释。 +3. Analysis 决定执行结构,document 决定视觉容器,units 决定标题边界和 + 完整 section range。三者都不能由行首正则替代。 +4. `heading_span` 只是标题本身;`span` 是从标题到下一个同级/更高标题或 + EOF 的完整范围,包含子标题。 +5. 只有 Exec H2 创建 callable;Knowledge、namespace、section 不创建函数。 +6. 旧 revision、旧字段集合、错误摘要和非法 span 在规则运行前 fail closed。 +7. 自动修复先验证再写回;任何歧义都保持原文件不变。 diff --git a/docs/AUTHORING_GUIDE.md b/docs/AUTHORING_GUIDE.md index ee43445..68c646f 100644 --- a/docs/AUTHORING_GUIDE.md +++ b/docs/AUTHORING_GUIDE.md @@ -2,7 +2,10 @@ ## 先让阅读结构与执行结构互相对应 -Marqdo 的执行语义来自载体内的 `if`、`else if`、`else`、`while`、`end`、`break`、`continue`、`return` 等关键字。`1.`、`-` 和 `>` 只是 Markdown 容器。推荐风格是在有序列表项开头分别写 `if`、`else if` 或 `else`,在无序列表项开头直接写 `while`,让读者看到的层级与解释器执行层级一致。 +Marqdo 的执行语义来自载体内的 `if`、`else if`、`else`、`while`、`end`、 +`break`、`continue`、`return` 等关键字。`1.`、`-` 和 `>` 只是 Markdown +容器。推荐风格是在有序列表项开头分别写 `if`、`else if` 或 `else`,在无序 +列表项开头直接写 `while`,让读者看到的层级与解释器执行层级一致。 ```markdown 1. `if 是否会员`:会员采用整数九折计算。 @@ -16,22 +19,42 @@ Marqdo 的执行语义来自载体内的 `if`、`else if`、`else`、`while`、` `end` ``` -不要把整个分支装入一个名为“开始判断”的列表项,也不要在列表项之后很远才写真正的控制语句。从 Marqdo RC.2 起,同组条件可以依次写多个 `else if`,再按需写一个 `else`。整组只用一个 `end`。若 `else` 和后续 `if` 分别占用两个载体,则第二个 `if` 开启嵌套分支,需要自己的 `end`。 +不要把整个分支装入一个名为“开始判断”的列表项,也不要在列表项之后很远才写 +真正的控制语句。同组条件可以依次写多个 `else if`,再按需写一个 `else`。 +整组只用一个 `end`。若 `else` 和后续 `if` 分别占用两个载体,则第二个 `if` +开启嵌套分支,需要自己的 `end`。 ## 在 Exec 中自然解释 -普通叙述直接写在 `@exec` 中,不需要 `# comment`,也不必包进 `@knowledge`。说明应提供目的、算法理由、处理顺序、结果和边界,而不是复述“下一步执行下一步”。 +普通叙述直接写在 `@exec` 中,不需要注释语法,也不必包进 `@knowledge`。 +说明应提供目的、算法理由、处理顺序、结果和边界,而不是复述“下一步执行下一 +步”。 -Exec 中的粗体、斜体和行内代码都是执行载体。`这是 **特别重要** 的处理` 不会把“特别重要”当普通强调;需要自由富文本时,应使用独立的 Knowledge 单元。 +Exec 中的粗体、斜体和行内代码都是执行载体。`这是 **特别重要** 的处理` +不会把“特别重要”当普通强调;需要自由富文本时,应使用独立的 Knowledge +单元。 ## 控制边界和小节 -H3+ 是函数内的阅读章节,不创建新函数。一个控制块及其 `end` 必须位于同一 heading 执行段,不能通过插入标题跨段闭合。 +H3+ 是函数内的阅读章节,不创建新函数。一个控制块及其 `end` 必须位于同一 +heading 执行段,不能通过插入标题跨段闭合。 -分支组的 `end` 推荐放在有序列表之后,循环的 `end` 推荐留在对应无序列表项末尾。嵌套以 CommonMark AST 的容器为准。 +分支组的 `end` 推荐放在有序列表之后,循环的 `end` 推荐留在对应无序列表项 +末尾。嵌套以 CommonMark AST 的容器为准。 -`break` 跳到最近循环之后,`continue` 返回最近循环的条件,`return` 退出整个函数。用行内代码标记 `break` 和 `continue`,并把它们放在实际所属的循环项或分支臂内。[RC.2 读数扫描示例](../examples/good/control-flow-rc2.mq.md) 展示了这两种跳转。 +`break` 跳到最近循环之后,`continue` 返回最近循环的条件,`return` 退出整个 +函数。用行内代码标记 `break` 和 `continue`,并把它们放在实际所属的循环项或 +分支臂内。[读数扫描示例](../examples/good/control-flow.mq.md) 展示了这两种 +跳转。 + +## 链接和未核验状态 + +普通 Analysis 只验证已加载模块。`not_loaded` 表示当前范围没有核验,不是断 +链;需要核验未导入的本地目标时,显式运行 `marqdo-lint --refs`。`external` +只作信息提示,Lint 不访问网络。`missing`、`ambiguous`、`invalid` 和 +`outside_scope` 是错误,`ambiguous` 会列出全部候选。 ## 自动修复边界 -列表重排、载体移动、载体类型替换、标题调整和控制语句迁移都属于人工修改。Lint 的安全修复不会替作者执行这些操作。 +列表重排、载体移动、载体类型替换、标题调整和控制语句迁移都属于人工修改。 +Lint 的安全修复不会替作者执行这些操作。 diff --git a/docs/CLI.md b/docs/CLI.md index 510db9e..21d9a83 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1,6 +1,29 @@ # 命令参考 -`rules` 列出规则,`explain RULE_ID` 显示规则的依据、严重度、建议和修复级别。`--format json` 同样适用于这两个命令。 +```bash +marqdo-lint index.mq.md +marqdo-lint . --profile recommended --format json +marqdo-lint index.mq.md --refs +marqdo-lint index.mq.md --fix safe --dry-run +marqdo-lint index.mq.md --fix safe +marqdo-lint explain MQD-BRANCH-001 +marqdo-lint rules +``` + +`rules` 和 `explain RULE_ID` 不要求核心。`--format json` 对两个命令同样有效。 + +## 核心选择与版本 + +直接运行时通过 `MARQDO_BIN` 或 PATH 查找核心。Tool 分发时核心由父进程 +通过 `MARQDO_BIN` 注入,并设置 `MARQDO_API_REVISION=1`。核心版本必须是 +`>=3.0.0-rc.4,<4.0.0`;更早的预发布版本会以退出码 `2` 拒绝。 + +## `--refs` + +默认 Analysis 只验证已经加载的模块。普通本地链接的状态是 `not_loaded`, +表示未核验,不是断链。只有用户显式传入 `--refs` 时,Lint 才让核心扩展 +链接目录并核验未导入的本地目标。`--refs` 会改变诊断和 artifact 字节, +因此不能用于 run/call 的 Observation 绑定。 ## 配置 @@ -24,16 +47,36 @@ mode = "safe-only" require_semantic_equivalence = true ``` -`strict-doc` 将解释覆盖类提示提高到 warning,`minimal` 保留核心布局检查,`migration` 淡化叙述比例并暂停部分排版提示。`--profile` 优先于配置的 profile,单条规则覆盖在 profile 之后应用。抑制项按报告路径、规则和可选的函数名及精确字节区间匹配。安全拒绝诊断不会被关闭。 +`strict-doc` 将解释覆盖类提示提高到 warning,`minimal` 保留核心布局检查, +`migration` 淡化叙述比例并暂停部分排版提示。`--profile` 优先于配置的 +profile,单条规则覆盖在 profile 之后应用。抑制项按报告路径、规则和可选的 +函数名及精确字节区间匹配。安全拒绝诊断不会被关闭。 ## 报告 -[JSON Schema](../schemas/marqdo-lint-v1.schema.json) 定义单文件报告和多文件报告。多文件报告将单文件报告按路径排序,并附汇总。源码路径优先相对于调用目录,目录之外的模块使用 Analysis 中的项目相对路径。诊断按起始偏移、结束偏移和 Rule ID 排序。所有 span 均为原始 UTF-8 字节中的半开区间,摘要是原始字节的 SHA-256,格式为小写十六进制加 `sha256:` 前缀。 +[JSON Schema](../schemas/marqdo-lint-v1.schema.json) 定义单文件报告和多文件 +报告。多文件报告将单文件报告按路径排序,并附汇总。源码路径优先相对于调用 +目录,目录之外的文件使用 artifact 中的项目相对路径。诊断按起始偏移、结束 +偏移和 Rule ID 排序。所有 span 均为对应 artifact source 中的半开 UTF-8 +字节区间,摘要是原始字节的 SHA-256。 -只有报告恰有一个函数时,顶层 `metrics.narrative_ratio` 才使用该函数的比例。缺少分母、缺少分析或报告含多个函数时该值为 `null`,多函数各自的比例位于 `metrics.functions`。人类输出用从 1 开始的行和 Unicode 代码点列。 +只有报告恰有一个函数时,顶层 `metrics.narrative_ratio` 才使用该函数的比例。 +缺少分母、缺少分析或报告含多个函数时该值为 `null`。人类输出使用从 1 开始 +的行号和 Unicode 代码点列号。 + +## 退出码 + +- `0`:检查完成且低于 `--fail-on` 门槛。 +- `1`:达到门槛,或安全修复被拒绝。 +- `2`:分析不可用、旧制品/协议错误、配置错误或工具错误。 + +`analysis_incomplete` 永远返回 `2`,即使 `--fail-on never`。 ## 安全空白修复 -`--fix safe --dry-run` 验证并将 unified diff 写到 stderr。去掉 `--dry-run` 后会保留权限并逐文件原子替换。JSON 仍写到 stdout。当前只尝试清理纯空格或制表符行和补文件末尾换行。如果这些字节属于代码围栏、前置元数据或其他保留原文的节点,验证会拒绝写回。 - -候选在临时目录中保留项目相对路径,使用相同核心重新检查。比较完整公开 AST、执行载荷顺序和规范化 Analysis。其中只略掉源码位置、被编辑模块的源码摘要和无 manifest 时派生的工作区摘要。调用目标、控制、资源和未编辑模块摘要必须一致。临时目录无法复现的依赖会触发拒绝。列表、标题、载体和模式的调整由作者按诊断手动完成。 +`--fix safe --dry-run` 验证并将 unified diff 写到 stderr。去掉 `--dry-run` +后保留权限并逐文件原子替换。当前只清理纯空格/制表符行和补文件末尾换行。 +如果这些字节属于代码围栏、前置元数据或其他保留原文的节点,验证会拒绝写回。 +候选在临时目录中保留项目相对路径,用同一个核心重新执行一次 `check --emit`; +比较规范化 document、执行载荷顺序和 Analysis 指纹。列表、标题、载体和模式 +的调整由作者按诊断手动完成。 diff --git a/docs/PROTOCOL_BASELINE.md b/docs/PROTOCOL_BASELINE.md index 880f761..4711512 100644 --- a/docs/PROTOCOL_BASELINE.md +++ b/docs/PROTOCOL_BASELINE.md @@ -1,24 +1,46 @@ # 协议基线 -`marqdo-lint` 通过独立发布的 Marqdo 可执行文件取得公开协议数据。 +`marqdo-lint` 只读取 Marqdo 可执行文件通过公开协议写出的数据;不链接核心 +Rust crate,也不读取核心私有文件。 + +## 当前冻结核心 | 项目 | 固定值 | |---|---| -| Marqdo `3.0.0-rc.1` | `f7a5a7b0163bf5229ed09adfffd892f9899e6667` | -| Marqdo `3.0.0-rc.2` | `9149ee40a48fcda692c5c112f66c465487d13dfb` | -| Markdown Profile | `marqdo.md.v1`,comrak `=1.0.0` | -| Analysis | `marqdo.analysis`,schema version 2 或 3 | -| 外部工具 | `marqdo.cli-tool`,schema version 1 | +| 产品版本 | `3.0.0-rc.4` | +| 源码提交 | `452e9a32bd9e40dba427d4180691c58bab74449e` | +| Linux x86_64 归档 SHA-256 | `9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8` | +| 归档内 CLI SHA-256 | `a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e` | +| Analysis schema SHA-256 | `03929300cec53bb29309a933f74c1aa807943bfd7dbecc80cf4f7f54d037eb30` | +| Markdown Profile | `marqdo.md.v1` | +| Analysis | `marqdo.analysis`,revision 3(当前字段集合) | +| 外部工具 | `marqdo.cli-tool`,revision 1 | | Lint 输出 | `marqdo.lint`,schema version 1 | -`MarqdoRunner` 调用 `--version`、`inspect FILE --ast --json` 和 `check FILE --json --emit PATH`。Canonical AST 提供 Markdown 容器,公开 Analysis 提供执行结构。读端保留原始 JSON 用于安全修复校验,在语句边界沿 `body` 和 `arms[].body` 遍历。模块使用包实例与相对路径标识,工作区文档按源码摘要校验,span 使用所属模块的原始 UTF-8 字节。 +版本门槛是 SemVer 预发布范围 `>=3.0.0-rc.4,<4.0.0`。rc.4 之前的核心虽然也 +可能写 `schema_version: 3`,但字段集合不同,当前 Lint 明确拒绝这些旧制品。 -Tool v1 manifest 声明 `analysis: [2, 3]`。`MARQDO_PROTOCOL_ANALYSIS` 表示最高共同版本,读端根据每个工件的 `schema_version` 解码。RC.1 输出 v2。RC.2 的多臂分支仍可用 v2,只要任一投影模块含有 `break` 或 `continue`,核心便输出 v3。[Analysis v3 合同](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.2/spec/analysis-v3.md) · [Tool v1 协商](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.2/spec/tool-v1.md) +## 唯一静态边界 -[双核心验收记录](VALIDATION.md) 保存两个冻结发布工件的摘要、测试用例和独立 Tool 安装结果。 +- 普通检查只执行一次 `check ENTRY --json --emit PATH`。`modules[].document` + 是 canonical Markdown AST 投影,`modules[].source` 是唯一可信源码。 +- `inspect` 不再进入 Lint 的机器路径。需要人工调试时由用户直接运行核心。 +- `--refs` 只在用户显式要求核验未导入本地目标时使用。它会改变诊断与 + Analysis 字节,不能作为 run/call 的 Observation 绑定。 +- 每个 span 都是对应 `modules[].source` 中的半开 UTF-8 字节偏移。读取 + document、units、references、calls、resources 之前先校验 + `sha256(source) == source_digest`。 +- Tool manifest 固定声明 `requires: {api_revision: 1, analysis: 3}`;核心只 + 注入 `MARQDO_BIN` 与 `MARQDO_API_REVISION=1`。 ## 失败状态 -- `complete` 表示公开 Analysis 与源码已可靠对齐,可以运行语义规则和完整度量。 -- `analysis_incomplete` 表示语言检查失败或关联不唯一。报告保留核心诊断或对齐原因,相关函数继续运行有充分依据的文档规则。 -- 不兼容版本、无效的必要协议结构、错误源码摘要、非法字节范围或 UTF-8 边界会作为工具错误返回退出码 `2`。 +- `complete`:公开 Analysis 与 artifact source 已通过协议校验。 +- `analysis_incomplete`:`check` 失败或 alignment 不唯一。Lint 返回退出码 + `2`,不得输出“检查完成”。 +- 旧制品、错误 revision、无效模块身份、摘要不符、越界或非 UTF-8 边界的 + span 都是协议错误,返回退出码 `2`,并提示重新生成 Analysis、重装 Tool、 + 重建 lint。 + +历史核心验收记录保留在 [VALIDATION.md](VALIDATION.md) 的“历史”小节,不参与 +当前门禁。 diff --git a/docs/RULES.md b/docs/RULES.md index b9c29ca..9690ee0 100644 --- a/docs/RULES.md +++ b/docs/RULES.md @@ -1,30 +1,37 @@ # 规则与可复现样例 -运行 `marqdo-lint explain RULE_ID` 可查看稳定 ID、损失、依据和建议。除安全守卫外,表中条目均为人工修复。所有样例可用冻结核心静态检查,文件路径相对于仓库根目录。 +运行 `marqdo-lint explain RULE_ID` 可查看稳定 ID、损失、依据和建议。除安全 +守卫外,表中条目均为人工修复。所有样例都可用当前冻结核心静态检查,路径相 +对于仓库根目录。 | 规则 | 默认级别 | 报告示例 | 对照示例和验证 | |---|---|---|---| | MQD-DOC-001 | warning | 直接返回且缺少入口说明 | 在首个载体前说明目标。运行 `doc_001_and_doc_002_check_explanation_existence_and_position` | | MQD-DOC-002 | info | 返回附近没有结果或限制说明 | 在返回处说明单位或失败结果。同上 | -| MQD-DOC-003 | warning | 复杂函数的叙述占比低于阈值 | 自然叙述达到门槛,短小平凡函数仅提示。运行 `long_functions_use_warning_ratio_and_h3_reading_sections` 和 `t23_trivial_short_functions_only_receive_info_ratio_diagnostics` | -| MQD-DOC-004 | info | 长函数无小节 | 在完整控制块之间按业务阶段分段。运行 `long_functions_use_warning_ratio_and_h3_reading_sections` | +| MQD-DOC-003 | warning | 复杂函数的叙述占比低于阈值 | 自然叙述达到门槛,短小平凡函数仅提示。运行 `long_functions_use_warning_ratio_and_h3_reading_sections` | +| MQD-DOC-004 | info | 长函数无小节 | 在完整控制块之间按业务阶段分段。同上 | | MQD-BRANCH-001 | warning | [同项包含 if/else](../examples/bad/branch-single-item.mq.md) | [推荐分支](../examples/good/branches.mq.md) | -| MQD-BRANCH-002 | warning | [不使用列表](../examples/bad/branches-unlisted.mq.md) 或列表先写说明再写 if | 让每个 `if`、`else if` 和 `else` 成为各自有序项的首个载体。运行 `prose_before_first_carrier_does_not_form_a_branch_head` 与 `t01_and_t19_branch_siblings_pass_in_h2_and_h3_segments` | -| MQD-BRANCH-003 | warning | 条件臂分属不同列表或中间有其他项 | 使用同一有序列表中的相邻兄弟项。运行 `t05_branch_arms_in_different_lists_are_not_siblings` | -| MQD-BRANCH-004 | info | 非空分支的列表项中缺少解释 | [推荐分支](../examples/good/branches.mq.md) 在臂内写原因。运行 `branch_loop_and_end_diagnostics_are_reported_independently` | -| MQD-LOOP-001 | warning | 编号项承载 while | [嵌套示例](../examples/nested/inventory.mq.md) 的循环使用无序项。运行 `t07_ordered_item_is_not_the_recommended_loop_container` | -| MQD-LOOP-002 | info | 循环项缺少叙述 | [嵌套示例](../examples/nested/inventory.mq.md) 说明处理对象和终止条件。运行 `branch_loop_and_end_diagnostics_are_reported_independently` | -| MQD-LOOP-003 | warning | 分支体或跳转脱离所属项,或子循环嵌套到错误的臂 | 依据真实列表子树缩进。运行 `a_branch_body_outside_its_item_is_a_layout_mismatch` 与 `t06_loop_item_and_t08_branch_containing_loop_pass` | -| MQD-CTRL-001 | warning | 循环 end 在项外,或分支 end 仍在分支项内 | 整个分支组只检查一个 `end`,放在列表后。循环 `end` 放在项末尾。运行 `branch_loop_and_end_diagnostics_are_reported_independently` 与 `t06_loop_item_and_t08_branch_containing_loop_pass` | -| MQD-PROSE-001 | warning | 句中的粗体、斜体或反引号成为执行载体 | 普通文字留在 Exec,富文本可进入 [Knowledge](../examples/knowledge/discount.mq.md)。运行 `t16_exec_emphasis_inside_prose_is_not_a_comment` | -| MQD-PROSE-002 | info | 已绑定的 I/O 调用或索引写入缺少相邻叙述 | 说明权限、后果或失败处理。运行 `supplemental_rules_use_bound_calls_and_allow_rich_knowledge` | -| MQD-PARAM-001 | info | 显式签名附近没有自然文字 | 说明单位、范围和用途。运行 `supplemental_rules_use_bound_calls_and_allow_rich_knowledge` | -| MQD-STYLE-001 | info | 用行内代码承载 `return`,或用斜体承载 `else if` 和循环跳转 | [推荐分支](../examples/good/branches.mq.md) 用斜体表示返回,粗体表示赋值。[RC.2 读数扫描](../examples/good/control-flow-rc2.mq.md) 用行内代码表示控制头、`break` 和 `continue`。运行 `supplemental_rules_use_bound_calls_and_allow_rich_knowledge` | -| MQD-KNOW-001 | warning | 在两个执行段之间切出一段纯文字,或出现 [跨段控制](../tests/fixtures/golden/invalid-control.mq.md) | 普通说明留在 Exec,同段关闭控制,公式和富文本可留在 Knowledge。运行 `supplemental_rules_use_bound_calls_and_allow_rich_knowledge` | -| MQD-SAFETY-001 | error | AST、执行载荷或 Analysis 不等价,或无法取得可靠验证输入 | 放弃写回。运行 `safe_fix_rejects_changes_to_inert_payload_and_unavailable_analysis` 与 `safe_fix_previews_then_persists_verified_whitespace_in_a_manifest_project` | +| MQD-BRANCH-002 | warning | [不使用列表](../examples/bad/branches-unlisted.mq.md) 或列表先写说明再写 if | 让每个 `if`、`else if` 和 `else` 成为各自有序项的首个载体 | +| MQD-BRANCH-003 | warning | 条件臂分属不同列表或中间有其他项 | 使用同一有序列表中的相邻兄弟项 | +| MQD-BRANCH-004 | info | 非空分支的列表项中缺少解释 | [推荐分支](../examples/good/branches.mq.md) 在臂内写原因 | +| MQD-LOOP-001 | warning | 编号项承载 while | [嵌套示例](../examples/nested/inventory.mq.md) 的循环使用无序项 | +| MQD-LOOP-002 | info | 循环项缺少叙述 | [嵌套示例](../examples/nested/inventory.mq.md) 说明处理对象和终止条件 | +| MQD-LOOP-003 | warning | 分支体或跳转脱离所属项,或子循环嵌套到错误的臂 | 依据真实列表子树缩进 | +| MQD-CTRL-001 | warning | 循环 end 在项外,或分支 end 仍在分支项内 | 整个分支组只检查一个 `end`,放在列表后;循环 `end` 放在项末尾 | +| MQD-PROSE-001 | warning | 句中的粗体、斜体或反引号成为执行载体 | 普通文字留在 Exec,富文本可进入 [Knowledge](../examples/knowledge/discount.mq.md) | +| MQD-PROSE-002 | info | 已绑定的 I/O 调用或索引写入缺少相邻叙述 | 说明权限、后果或失败处理 | +| MQD-PARAM-001 | info | 显式签名附近没有自然文字 | 说明单位、范围和用途 | +| MQD-STYLE-001 | info | 用行内代码承载 `return`,或用斜体承载 `else if` 和循环跳转 | [推荐分支](../examples/good/branches.mq.md) 用斜体表示返回,粗体表示赋值;[读数扫描](../examples/good/control-flow.mq.md) 用行内代码表示控制头、`break` 和 `continue` | +| MQD-KNOW-001 | warning | 在两个执行段之间切出一段纯文字,或出现跨段控制 | 普通说明留在 Exec,同段关闭控制;公式和富文本可留在 Knowledge | +| MQD-LINK-001 | error | `references[].state` 为 `missing`、`ambiguous`、`invalid` 或 `outside_scope` | 修正引用地址或目标;歧义时打印全部候选,不任选第一个 | +| MQD-LINK-002 | info | `references[].state` 为 `not_loaded` | 这是“未核验”,不是断链;需要时显式使用 `--refs` | +| MQD-LINK-003 | info | `references[].state` 为 `external` | 外部 URI 不联网核验,仅供人工评审 | +| MQD-CALL-001 | info | `calls[].state` 为 `unresolved` | 动态/未绑定调用是诚实的未解析,不是错误 | +| MQD-SAFETY-001 | error | AST、执行载荷或 Analysis 不等价,或无法取得可靠验证输入 | 放弃写回 | -自动检测可以判断结构、覆盖和位置。对叙述内容的业务正确性仍须由作者和评审者判断。当前副作用识别使用公开 Analysis 中已绑定的资源、外部执行、标准库 I/O、插件调用和索引写入。未知绑定和普通本地函数不被猜测为副作用。 +自动检测可以判断结构、覆盖和位置。对叙述内容的业务正确性仍须由作者和评审 +者判断。副作用识别只使用公开 Analysis 中已绑定的资源、外部执行、标准库 +I/O、插件调用和索引写入;未知绑定和普通本地函数不被猜测为副作用。 -多臂与跳转的正反例由 `rc2_branch_rules_anchor_each_affected_arm` 和 `rc2_jump_rules_check_the_arm_container_and_carrier_style` 复现。度量把每个分支组和每个跳转分别计作一个语句。 - -渲染对照位于 [examples/rendered](../examples/rendered)。使用 `cargo run --locked --example render_fixtures` 按冻结 Markdown Profile 重新生成。 +渲染对照位于 [examples/rendered](../examples/rendered)。使用 +`cargo run --locked --example render_fixtures` 按 `marqdo.md.v1` 重新生成。 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 0a5dcfc..759b6b3 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,58 +1,80 @@ -# RFC-LINT-0001 验收记录 +# 验收记录 -## 工单 #1 的双核心验收 +当前门禁只认 Marqdo `3.0.0-rc.4` 的公开协议。每次运行 +`scripts/validate-control-flow.py` 都会写入 +`docs/validation/.json`,记录 lint commit、lint 版本、 +Tool bundle 摘要、核心二进制前后摘要、平台、UTC 时间与逐门禁结果。 -使用正式发布的 Linux x86_64 归档,先核验归档 SHA-256,再分别解包。RC.1 和 RC.2 各运行一次 `cargo test --locked`,每次报告 64 项通过。各版本专属的场景在对应版本上执行。[机器可读记录](validation/rc2-control-flow.json) 保存源码提交、归档摘要、二进制前后摘要、输入摘要和实测退出码。 +## 冻结核心 -| 核心 | 发布归档 SHA-256 | 工具协商 | 实测 Analysis 工件 | -|---|---|---|---| -| RC.1 | `9f49036ada141871492ef721f08569c74fd2854b5e5d1bfc065ba4d812dcabc7` | 2 | v2 旧分支 | -| RC.2 | `e32e6426caf023fc813ebdbf5a171ec164ee2ffb843ae5594b8e7b9780f496ea` | 3 | v2 旧分支、`hello` 和四臂分支。v3 嵌套跳转、发行示例及作者示例 | +| 项目 | 固定值 | +|---|---| +| 源码提交 | `452e9a32bd9e40dba427d4180691c58bab74449e` | +| Linux x86_64 归档 SHA-256 | `9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8` | +| 归档内 CLI SHA-256 | `a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e` | +| Analysis schema SHA-256 | `03929300cec53bb29309a933f74c1aa807943bfd7dbecc80cf4f7f54d037eb30` | -两个核心都从临时工作目录安装同一个 `scripts/package-tool.sh` 生成的包,各自使用隔离注册目录。核心分发正确传递退出码 `0`、`1`、`2`,卸载后分发失败。`strace` 记录协商环境和子进程,Lint 实际调用 `--version`、`inspect FILE --ast --json`、`check FILE --json --emit PATH`。`marqdo.lint` v1 JSON 的状态和源码摘要通过校验。终端报告保留规则 ID,未完成的检查在 `--fail-on never` 下仍返回 `2`。 +核心二进制在门禁前后必须保持同一 SHA-256,证明 Lint 没有修改核心。 -两版协议的安全修复均通过真实核心复检、dry run 与空白写回。改变分支臂归属或最近循环目标的候选得到 `MQD-SAFETY-001`,原始字节保持不变。回归测试还覆盖 RC.1 的旧默认臂 span 和同名变量,RC.2 显式空 `else`、跨 heading 诊断、导入模块提升工件版本,以及 BOM、CRLF、emoji 和错误 UTF-8 边界。 +## 发布门禁 -在仓库根目录运行发布门禁,传入两个已解包的核心绝对路径。门禁需要 Python 3.11+ 和 `strace`,并校验冻结二进制的 SHA-256。缺少任一核心会直接失败。 - -```sh -python3 scripts/validate-control-flow.py /absolute/rc1/marqdo /absolute/rc2/marqdo -``` - -## RC.1 初始验收 - -验收使用 Marqdo `3.0.0-rc.1`,从提交 `f7a5a7b0163bf5229ed09adfffd892f9899e6667` 的 Git 归档构建。工具调用、规则测试和应用试跑使用同一个核心二进制。[机器可读记录](validation/rfc-0001.json) 保存二进制、发布包、输入摘要、实际退出码和诊断 ID。 - -## 本仓库验收 - -- 使用冻结核心运行 `cargo test --locked`,48 项测试通过。其中包括从孤立目录安装 Tool v1、从核心分发 `marqdo lint`、读取多模块报告和拒绝不安全写回。 -- 使用 `scripts/package-tool.sh` 构建发布包,在临时 Tool 注册目录中验证安装、分发、退出码传递和卸载。发布包输出的单文件、多模块和降级报告均通过 JSON Schema 2020-12 校验。 -- 无列表分支和单项包整段分支均通过核心静态检查,并分别产生 `MQD-BRANCH-002`、`MQD-BRANCH-001`。推荐分支、嵌套库存和 Knowledge 示例通过默认风格门槛。 -- 查看生成的 HTML 时,推荐分支呈现两个对等的编号项,关闭标记另起一段。反例呈现一个编号项,其中的 else 无法一眼看出与 if 对等。库存示例把循环渲染为条件项内的无序子列表,循环 end 位于子项内,条件组 end 位于外层列表之后。库存示例在循环附近补充了下标不变量,两个小节分别展示汇总过程和结果,控制块仍完整位于一个小节。 - -核心仓库的 Math Library 和 Resource Provider 示例也取得完整分析,并按默认门槛报告了风格问题。Math Library 的公式保留在 Knowledge 中。Resource Provider 示例的资源调用可以得到临近说明提示。试跑只做静态检查,没有执行示例或调用资源。 - -## 独立应用 - -从两个应用的固定提交归档 `.mq.md` 文稿到本仓库的临时目录,使用同一个安装后的工具检查入口。两次检查均返回 `2` 和 `analysis_incomplete`。 - -| 应用 | 固定提交 | 核心阻断原因 | +| 门禁 | 内容 | 判定 | |---|---|---| -| qdagent | `39f9ec38e9afddc2fa259c85613e86be6177fc30` | `module.unresolved` 和 `ext.import_namespace_conflict`。文稿引用旧版的 lib/ext 模块路径和命名空间。 | -| qdqc | `30f4c4f51ed3fc7b15bdc706e9e4b57e4af1eeb3` | `frontmatter.invalid`。入口的旧版导入声明无法解析为当前 YAML 前置元数据。 | +| G01 | `scripts/check-no-legacy.sh` | `src/`、`tool.json`、`scripts/` 无旧契约残留,0 命中 | +| G02 | `cargo fmt --all --check`、`cargo clippy --all-targets -D warnings`、`cargo test --locked` | 全部退出 0,记录通过数 | +| G03 | `scripts/package-tool.sh` + 隔离注册目录 + `marqdo tool install/list/remove` | 安装、分发、卸载成功,退出码 0/1/2 透传,卸载后分发失败 | +| G04 | 正向规则与安全修复 | inventory、多臂、嵌套循环、Knowledge 示例均为 `complete`;dry-run 不写;正式修复幂等 | +| G05 | JSON 报告契约 | 单文件报告通过 `schemas/marqdo-lint-v1.schema.json` 校验 | +| G06 | 负例 fail closed | 旧 revision 3 字段集合、错误 `source_digest`、错误 revision、旧 Tool manifest 均失败 | +| G07 | 单核心证据 | 本脚本生成 manifest,绑定核心源码/归档/二进制 SHA | +| G08 | 文档事实一致 | README、PROTOCOL_BASELINE、VALIDATION、ARCHITECTURE、CLI 只描述当前边界 | +| G09 | CI | `.woodpecker/main.yml` 运行 G01–G07,红即阻塞 | +| G10 | 独立应用试跑 | 当前标为 `UNVERIFIED`,不声明误报率 | -独立应用未达到完整分析门槛,无法据此评估语义规则的误报率。这两次试跑也没有项目作者反馈。现有 `0.1.0` 包为本地发布候选。PR-06 仍需两个兼容冻结核心的独立应用通过实测,才能完成发布验收。 +缺少任一 P0 门禁或任一负例未 fail closed,脚本非零退出,不得发布。 + +## 负例 + +`scripts/validate-control-flow.py` 的 G06 至少覆盖: + +- 旧 revision 3 字段集合(缺少 `source`/`document`/`anchors`)→ 退出 2,提示 + 重新生成 Analysis、重装 Tool、重建 lint; +- `schema_version` 不是 3 → 退出 2,不解码; +- `sha256(source)` 与 `source_digest` 不符 → 退出 2,不运行规则; +- 旧 `tool.json` 带 `compatibility` → 安装失败,提示按 revision 1 重写。 + +单元/集成测试还覆盖非法模块身份、重复 unit/function、越界或非 UTF-8 边界 +span、坏 statement/expression 形状、坏 reference state、resource +`content_digest` 与 AST literal 不符等 fail-closed 路径。 ## 复现 -在本仓库根目录,以本地冻结核心和独立的 Tool 注册目录运行以下命令。将外部应用固定提交的源码归档解包到 `target/validation` 再运行同一命令,可复现对应的分析状态。 - ```sh -export MARQDO_BIN=/absolute/path/to/frozen/marqdo -export MARQDO_TOOL_HOME="$PWD/target/validation/registry" +export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo +sha256sum "$MARQDO_BIN" # a7306962… +cargo fmt --all -- --check +cargo clippy --all-targets -- -D warnings cargo test --locked +./scripts/check-no-legacy.sh ./scripts/package-tool.sh +export MARQDO_TOOL_HOME="$PWD/target/validation/registry" "$MARQDO_BIN" tool install .cache/tool-bundle/tool.json "$MARQDO_BIN" lint examples/nested/inventory.mq.md --format json "$MARQDO_BIN" tool remove lint +python3 scripts/validate-control-flow.py "$MARQDO_BIN" +sha256sum "$MARQDO_BIN" # 前后一致 ``` + +## 已知上游欠账(诚实记录) + +- `UNVERIFIED`:本仓库无法取得 qdagent/qdqc 的固定提交归档,未完成独立应用 + 试跑,不声明误报率。 +- rc.4 的 stdlib 模块里部分 `signature.params[].span` 不落在对应 artifact + source 的 UTF-8 字符边界上。该字段只用于展示,不参与规则对齐;Lint 仍然 + 严格校验 document、unit、function、statement、reference、call、resource + span。此上游问题已记录,未冒充已完成。 + +## 历史 + +旧核心与旧制品验收记录保留为 `docs/validation/historical-*.json`,仅用于 +审计追溯,不参与当前门禁;当前树没有对旧核心或旧字段集合的兼容路径。 diff --git a/docs/validation/rc2-control-flow.json b/docs/validation/historical-rc2-control-flow.json similarity index 100% rename from docs/validation/rc2-control-flow.json rename to docs/validation/historical-rc2-control-flow.json diff --git a/docs/validation/rfc-0001.json b/docs/validation/historical-rfc-0001.json similarity index 100% rename from docs/validation/rfc-0001.json rename to docs/validation/historical-rfc-0001.json diff --git a/examples/good/control-flow-rc2.mq.md b/examples/good/control-flow.mq.md similarity index 100% rename from examples/good/control-flow-rc2.mq.md rename to examples/good/control-flow.mq.md diff --git a/examples/render_fixtures.rs b/examples/render_fixtures.rs index 0d99e93..d6ddd5b 100644 --- a/examples/render_fixtures.rs +++ b/examples/render_fixtures.rs @@ -1,7 +1,6 @@ use std::{fs, path::Path}; -use comrak::markdown_to_html; -use marqdo_lint::input::profile_options; +use comrak::{markdown_to_html, Options}; fn main() { let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); @@ -27,7 +26,13 @@ fn main() { "examples/rendered/discount.html", ), ]; - let options = profile_options(); + let mut options = Options::default(); + options.extension.table = true; + options.extension.strikethrough = true; + options.extension.tasklist = true; + options.extension.math_dollars = true; + options.extension.math_dollars_block = true; + options.extension.front_matter_delimiter = Some("---".to_string()); for (source, target) in fixtures { let source_path = manifest.join(source); diff --git a/scripts/check-no-legacy.sh b/scripts/check-no-legacy.sh new file mode 100755 index 0000000..7ec981b --- /dev/null +++ b/scripts/check-no-legacy.sh @@ -0,0 +1,45 @@ +#!/bin/sh +# Static P0 gate: the current tree may only describe the current public +# Analysis revision 3 / Tool revision 1 boundary. This script intentionally +# has no allow-list for src/, tool.json or scripts. +set -eu + +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +fail=0 + +if command -v rg >/dev/null 2>&1; then + search() { rg -n --no-heading "$2" "$1" || true; } +else + search() { grep -RInE "$2" "$1" || true; } +fi + +scan() { + label=$1 + pattern=$2 + path=$3 + hits=$(search "$path" "$pattern") + if [ -n "$hits" ]; then + printf 'FAIL: %s\n%s\n' "$label" "$hits" + fail=1 + fi +} + +scan "retired Analysis acceptance" '2 \| 3|version == 2|Analysis v2|需要 2 或 3' "$ROOT/src" +scan "retired Tool negotiation" 'compatibility|TOOL_PROTOCOL|PROTOCOL_ANALYSIS|PROTOCOL_TRACE' "$ROOT/src" +scan "legacy tool manifest field" '"compatibility"' "$ROOT/tool.json" +scan "retired version branches" 'schema_version == 2|match .*schema_version' "$ROOT/src/model" +scan "silent parser downgrade" 'fallback|legacy|best effort|尽力' "$ROOT/src" + +# Exclude this gate script itself: its patterns necessarily spell the retired +# names. Any other current script is scanned literally. +for script in "$ROOT"/scripts/*; do + [ -f "$script" ] || continue + [ "$(basename "$script")" = "check-no-legacy.sh" ] && continue + scan "retired core in $(basename "$script")" 'rc1|rc2|RC\.1|RC\.2' "$script" +done + +if [ "$fail" -ne 0 ]; then + printf '\ncheck-no-legacy: FAIL\n' + exit 1 +fi +printf 'check-no-legacy: PASS\n' diff --git a/scripts/package-tool.sh b/scripts/package-tool.sh index 42321be..7ae251a 100755 --- a/scripts/package-tool.sh +++ b/scripts/package-tool.sh @@ -8,8 +8,17 @@ export CARGO_TARGET_DIR=${CARGO_TARGET_DIR:-"$ROOT/.cache/marqdo-lint-release-ta export TMPDIR=${TMPDIR:-"$ROOT/.cache/tmp"} mkdir -p "$TMPDIR" "$DEST/bin" +python3 - "$ROOT/tool.json" <<'PYCHECK' +import json, sys +value = json.load(open(sys.argv[1])) +assert value["schema"] == "marqdo.cli-tool" and value["schema_version"] == 1 +assert value["requires"] == {"api_revision": 1, "analysis": 3} +assert "compatibility" not in value +PYCHECK cargo build --locked --release --manifest-path "$ROOT/Cargo.toml" install -m 755 "$CARGO_TARGET_DIR/release/marqdo-lint" "$DEST/bin/marqdo-lint" cp "$ROOT/tool.json" "$DEST/tool.json" sha256sum "$DEST/bin/marqdo-lint" +printf 'tool.json sha256: ' +sha256sum "$DEST/tool.json" | awk '{print $1}' printf 'Tool bundle: %s\n' "$DEST" diff --git a/scripts/validate-control-flow.py b/scripts/validate-control-flow.py index 051a442..9619866 100755 --- a/scripts/validate-control-flow.py +++ b/scripts/validate-control-flow.py @@ -1,7 +1,14 @@ #!/usr/bin/env python3 -"""Run the RC.1/RC.2 release gate using unpacked Linux release bundles.""" +"""Single-core rc.4 acceptance gate for marqdo-lint. + +The script verifies the pinned marqdo-cli v3.0.0-rc.4 archive/binary, exercises +one `check --emit` entry path, the packaged Tool revision 1 lifecycle, positive +rule/fix behavior, JSON report schema, negative fail-closed cases and emits a +machine-readable acceptance manifest. +""" import argparse +import datetime import hashlib import json import os @@ -11,209 +18,408 @@ import shutil import subprocess import tempfile - ROOT = Path(__file__).resolve().parents[1] -RELEASES = { - "3.0.0-rc.1": { - "source_commit": "f7a5a7b0163bf5229ed09adfffd892f9899e6667", - "archive_sha256": "9f49036ada141871492ef721f08569c74fd2854b5e5d1bfc065ba4d812dcabc7", - "binary_sha256": "2fc5f74d8dd64a4a1b4617e630cb2af9fae5ba0ab769467c32ecb5a988894b6d", - "negotiated_analysis": 2, - }, - "3.0.0-rc.2": { - "source_commit": "9149ee40a48fcda692c5c112f66c465487d13dfb", - "archive_sha256": "e32e6426caf023fc813ebdbf5a171ec164ee2ffb843ae5594b8e7b9780f496ea", - "binary_sha256": "5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b", - "negotiated_analysis": 3, - }, -} +CLI_SOURCE_SHA = "452e9a32bd9e40dba427d4180691c58bab74449e" +CLI_ARCHIVE_SHA = "9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8" +CLI_BINARY_SHA = "a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e" +ANALYSIS_SCHEMA_SHA = "03929300cec53bb29309a933f74c1aa807943bfd7dbecc80cf4f7f54d037eb30" +PLATFORM = "linux-x86_64-glibc2.39" +MANIFEST_SCHEMA = "marqdo.lint.acceptance" +MANIFEST_VERSION = 1 -class ValidationError(Exception): +class GateError(Exception): pass -def require(condition, message): - if not condition: - raise ValidationError(message) - - -def sha256(path): - with path.open("rb") as stream: +def sha256_file(path): + with Path(path).open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() -def run(args, *, cwd=ROOT, env=None, expected=0): - result = subprocess.run(list(map(str, args)), cwd=cwd, env=env, capture_output=True, text=True) +def sha256_bytes(data): + return hashlib.sha256(data).hexdigest() + + +def run(command, *, cwd=ROOT, env=None, expected=0, timeout=900): + result = subprocess.run( + [str(item) for item in command], + cwd=cwd, + env=env, + capture_output=True, + text=True, + timeout=timeout, + ) if expected is not None and result.returncode != expected: - raise ValidationError( - f"{args}: expected exit {expected}, got {result.returncode}\n" - f"{result.stdout}{result.stderr}" + raise GateError( + f"command failed ({result.returncode}): {' '.join(map(str, command))}\n" + f"{result.stdout}\n{result.stderr}" ) return result -def validate_core(binary, version): - require(binary.is_file() and os.access(binary, os.X_OK), f"missing frozen core: {binary}") - digest = sha256(binary) - require(digest == RELEASES[version]["binary_sha256"], f"unexpected {version} binary SHA-256: {digest}") - require(run([binary, "--version"]).stdout.strip() == f"marqdo {version}", f"wrong version: {binary}") +def cargo_command(): + return os.environ.get("CARGO", "cargo") + + +def test_count(stdout): + counts = re.findall(r"test result: ok\. (\d+) passed; 0 failed", stdout) + return sum(int(value) for value in counts) + + +def lint_binary(): + candidate = os.environ.get("MARQDO_LINT_BIN") + if candidate: + return Path(candidate).resolve() + for profile in ("debug", "release"): + path = ROOT / "target" / profile / "marqdo-lint" + if path.is_file(): + return path + raise GateError("marqdo-lint binary is missing; build it before running the gate") + + +def validate_core(binary): + if not binary.is_file() or not os.access(binary, os.X_OK): + raise GateError(f"missing executable core: {binary}") + digest = sha256_file(binary) + if digest != CLI_BINARY_SHA: + raise GateError(f"unexpected rc.4 binary SHA-256: {digest}") + output = run([binary, "--version"]).stdout.strip() + if output != "marqdo 3.0.0-rc.4": + raise GateError(f"wrong core version: {output!r}") return digest -def test_suite(binary): - env = dict(os.environ, MARQDO_BIN=str(binary)) - cached_cargo = ROOT / ".cache/cargo-home" - if cached_cargo.is_dir(): - env.setdefault("CARGO_HOME", str(cached_cargo)) - output = run(["cargo", "test", "--locked"], env=env).stdout - counts = re.findall(r"test result: ok\. (\d+) passed; 0 failed", output) - require(counts and sum(map(int, counts)) > 0, "cargo test reported no passing tests") - return sum(map(int, counts)) - - -def trace_dispatch(strace, binary, work, env, name, args, major, expected): - trace = work / f"{name}.trace" - result = run( - [strace, "-f", "-qq", "-v", "-s", "4096", "-e", "trace=execve", "-o", trace, binary, "lint", *args], - cwd=work, env=env, expected=expected, - ) - core_calls = [] - tool_calls = [] - for line in trace.read_text().splitlines(): - match = re.search(r'execve\(("(?:[^"\\]|\\.)*"), (\[(?:"(?:[^"\\]|\\.)*"(?:, )?)*\]),', line) - if not match: - continue - program = Path(json.loads(match[1])) - argv = json.loads(match[2])[1:] - if program == binary: - core_calls.append(argv) - elif program.name == "marqdo-lint": - tool_calls.append(line) - else: - raise ValidationError(f"{name}: unexpected executed program {program}") - require(len(tool_calls) == 1, f"{name}: expected one packaged lint process") - require(f'"MARQDO_PROTOCOL_ANALYSIS={major}"' in tool_calls[0], f"{name}: incorrect negotiated Analysis major") - require(core_calls and core_calls[0][0] == "lint", f"{name}: missing core dispatch process") - child_commands = set() - for argv in core_calls[1:]: - if argv == ["--version"]: - child_commands.add("--version") - elif len(argv) == 4 and argv[0] == "inspect" and argv[2:] == ["--ast", "--json"]: - child_commands.add("inspect FILE --ast --json") - elif len(argv) == 5 and argv[0] == "check" and argv[2:4] == ["--json", "--emit"]: - child_commands.add("check FILE --json --emit PATH") - else: - raise ValidationError(f"{name}: unexpected core child command {argv}") - require(len(child_commands) == 3, f"{name}: missing static child command: {child_commands}") - return result.stdout, sorted(child_commands) - - -def validate_bundle(strace, binary, version, bundle, directory): - work = directory / "independent-cwd" - work.mkdir(parents=True) - home = directory / "home" - home.mkdir() - env = { - "PATH": "/usr/bin:/bin", - "LANG": "C.UTF-8", - "HOME": str(home), - "MARQDO_TOOL_HOME": str(directory / "registry"), - } - manifest = bundle / "tool.json" - run([binary, "tool", "install", manifest], cwd=work, env=env) - tools = run([binary, "tool", "list", "--json"], cwd=work, env=env).stdout - require('"lint"' in tools, f"{version}: lint missing after tool install") - major = RELEASES[version]["negotiated_analysis"] - cases = [ - ("legacy-branches", ROOT / "tests/fixtures/golden/branches.mq.md", 2, 0, "json", "never", None), - ("style-warning", ROOT / "examples/bad/branch-single-item.mq.md", 2, 1, "human", "warning", "MQD-BRANCH-001"), - ("incomplete", ROOT / "tests/fixtures/golden/invalid-control.mq.md", None, 2, "json", "never", "sem.unclosed_control"), - ] - if major == 3: - cases.extend([ - ("release-hello", binary.parent / "examples/hello.mq.md", 2, 0, "json", "never", None), - ("multi-arm", ROOT / "tests/fixtures/rc2/multi-arm.mq.md", 2, 0, "json", "never", None), - ("loop-jumps", ROOT / "tests/fixtures/rc2/loop-jumps.mq.md", 3, 0, "json", "never", None), - ("release-control-flow", binary.parent / "examples/control-flow.mq.md", 3, 0, "json", "never", None), - ("author-example", ROOT / "examples/good/control-flow-rc2.mq.md", 3, 0, "json", "warning", None), - ]) - evidence = {} - for name, original, expected_major, status, output_format, fail_on, diagnostic in cases: - source = work / f"{name}.mq.md" - shutil.copyfile(original, source) - if expected_major is not None: - artifact = work / f"{name}.analysis.json" - run([binary, "check", source.name, "--json", "--emit", artifact], cwd=work, env=env) - actual = json.loads(artifact.read_text())["schema_version"] - require(actual == expected_major, f"{name}: incorrect artifact major {actual}") - text, commands = trace_dispatch( - strace, binary, work, env, name, - [source.name, "--format", output_format, "--fail-on", fail_on], major, status, - ) - digest = sha256(source) - analysis_status = "analysis_incomplete" if status == 2 else "complete" - if output_format == "json": - report = json.loads(text) - require(report["schema"] == "marqdo.lint" and report["schema_version"] == 1, f"{name}: unexpected report protocol") - require(report["analysis_status"] == analysis_status, f"{name}: unexpected report state") - require(report["source"]["digest"] == f"sha256:{digest}", f"{name}: source digest mismatch") - if diagnostic: - require(diagnostic in text, f"{name}: missing diagnostic {diagnostic}") - evidence[name] = { - "input_sha256": digest, - "analysis_major": expected_major, - "analysis_status": analysis_status, - "exit": status, - "format": output_format, - **({"diagnostic": diagnostic} if diagnostic else {}), +def gate(manifest, gate_id, command, function): + try: + detail = function() + manifest["gates"][gate_id] = { + "state": "PASS", + "command": command, + "exit_code": 0, } - run([binary, "tool", "remove", "lint"], cwd=work, env=env) - tools = run([binary, "tool", "list", "--json"], cwd=work, env=env).stdout - require('"lint"' not in tools, f"{version}: lint remains after uninstall") - removed = run([binary, "lint", "legacy-branches.mq.md"], cwd=work, env=env, expected=None) - require(removed.returncode != 0, f"{version}: removed lint still dispatches") - return {"install_exit": 0, "remove_exit": 0, "dispatch_after_remove_exit": removed.returncode, - "static_child_commands": commands, "cases": evidence} + print(f"{gate_id}: PASS", flush=True) + return detail + except (GateError, OSError, ValueError, KeyError, subprocess.TimeoutExpired) as error: + manifest["gates"][gate_id] = { + "state": "FAIL", + "command": command, + "exit_code": 1, + "detail": str(error)[:4000], + } + print(f"{gate_id}: FAIL - {error}", flush=True) + return None + + +def g01(manifest): + run([ROOT / "scripts/check-no-legacy.sh"]) + + +def g02(manifest): + run([cargo_command(), "fmt", "--all", "--", "--check"]) + run([cargo_command(), "clippy", "--all-targets", "--", "-D", "warnings"]) + result = run([cargo_command(), "test", "--locked"], timeout=1800) + count = test_count(result.stdout) + if count == 0: + raise GateError("cargo test reported no passing tests") + manifest["tests_passed"] = count + + +def g03(manifest): + binary = manifest["_core"] + work = Path(tempfile.mkdtemp(prefix="marqdo-lint-install-")) + try: + bundle = work / "bundle" + run([ROOT / "scripts/package-tool.sh", bundle], timeout=1800) + env = dict(os.environ) + env.update( + { + "MARQDO_TOOL_HOME": str(work / "registry"), + "PATH": "/usr/bin:/bin", + "LANG": "C.UTF-8", + "HOME": str(work / "home"), + } + ) + (work / "home").mkdir() + env.pop("MARQDO_BIN", None) + dispatch = work / "project" + dispatch.mkdir() + shutil.copyfile( + ROOT / "examples/nested/inventory.mq.md", dispatch / "inventory.mq.md" + ) + shutil.copyfile( + ROOT / "examples/bad/branch-single-item.mq.md", dispatch / "bad.mq.md" + ) + shutil.copyfile( + ROOT / "tests/fixtures/golden/invalid-control.mq.md", dispatch / "invalid.mq.md" + ) + run([binary, "tool", "install", bundle / "tool.json"], env=env) + listed = run([binary, "tool", "list", "--json"], env=env).stdout + if '"lint"' not in listed: + raise GateError("lint is not listed after tool install") + run([binary, "lint", "inventory.mq.md", "--format", "json"], cwd=dispatch, env=env) + run( + [binary, "lint", "bad.mq.md", "--format", "human"], + cwd=dispatch, + env=env, + expected=1, + ) + run( + [binary, "lint", "invalid.mq.md", "--format", "json", "--fail-on", "never"], + cwd=dispatch, + env=env, + expected=2, + ) + run([binary, "tool", "remove", "lint"], env=env) + after = run( + [binary, "lint", "inventory.mq.md", "--format", "json"], + cwd=dispatch, + env=env, + expected=None, + ) + if after.returncode == 0: + raise GateError("removed lint still dispatches") + manifest["lint_binary_sha256"] = f"sha256:{sha256_file(bundle / 'bin/marqdo-lint')}" + manifest["tool_bundle_digest"] = f"sha256:{sha256_file(bundle / 'tool.json')}" + finally: + shutil.rmtree(work, ignore_errors=True) + + +def g04(manifest): + binary = manifest["_core"] + lint = lint_binary() + env = dict(os.environ, MARQDO_BIN=str(binary)) + positive = [ + ("inventory", ROOT / "examples/nested/inventory.mq.md"), + ("multi-arm", ROOT / "tests/fixtures/control/multi-arm.mq.md"), + ("loop-jumps", ROOT / "tests/fixtures/control/loop-jumps.mq.md"), + ("knowledge", ROOT / "examples/knowledge/discount.mq.md"), + ] + for name, path in positive: + result = run( + [lint, path, "--format", "json", "--fail-on", "never"], + env=env, + ) + report = json.loads(result.stdout) + if report["analysis_status"] != "complete": + raise GateError(f"{name}: analysis is not complete") + work = Path(tempfile.mkdtemp(prefix="marqdo-lint-fix-")) + try: + for name in ("marqdo.yaml", "geometry.mq.md"): + shutil.copyfile(ROOT / "tests/fixtures/multi" / name, work / name) + source = (ROOT / "tests/fixtures/multi/index.mq.md").read_text() + dirty = source.replace("## @exec main\n\n", "## @exec main\n \t\n") + (work / "index.mq.md").write_text(dirty) + run( + [lint, "index.mq.md", "--fix", "safe", "--dry-run", "--format", "json", "--fail-on", "never"], + cwd=work, + env=env, + ) + if (work / "index.mq.md").read_text() != dirty: + raise GateError("dry-run wrote the source") + run( + [lint, "index.mq.md", "--fix", "safe", "--format", "json", "--fail-on", "never"], + cwd=work, + env=env, + ) + if (work / "index.mq.md").read_text() != source: + raise GateError("safe fix did not produce the expected idempotent result") + run( + [lint, "index.mq.md", "--format", "json", "--fail-on", "never"], + cwd=work, + env=env, + ) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def g05(manifest): + import jsonschema + + binary = manifest["_core"] + lint = lint_binary() + env = dict(os.environ, MARQDO_BIN=str(binary)) + schema = json.loads((ROOT / "schemas/marqdo-lint-v1.schema.json").read_text()) + result = run( + [lint, ROOT / "examples/nested/inventory.mq.md", "--format", "json", "--fail-on", "never"], + env=env, + ) + report = json.loads(result.stdout) + jsonschema.validate(report, schema) + if report["schema"] != "marqdo.lint" or report["schema_version"] != 1: + raise GateError("unexpected lint report protocol") + + +def g06(manifest): + binary = manifest["_core"] + lint = lint_binary() + artifact = json.loads( + (ROOT / "tests/fixtures/rc4/branches.analysis.json").read_text() + ) + retired = json.loads(json.dumps(artifact)) + for field in ("source", "document", "anchors"): + retired["modules"][0].pop(field, None) + bad_digest = json.loads(json.dumps(artifact)) + bad_digest["modules"][0]["source_digest"] = "0" * 64 + bad_revision = json.loads(json.dumps(artifact)) + bad_revision["schema_version"] = 2 + work = Path(tempfile.mkdtemp(prefix="marqdo-lint-negative-")) + try: + source = work / "branches.mq.md" + shutil.copyfile(ROOT / "tests/fixtures/golden/branches.mq.md", source) + proxy = work / "core-proxy" + proxy.write_text( + "#!/bin/sh\n" + "set -eu\n" + "case \"$1\" in\n" + " --version) echo 'marqdo 3.0.0-rc.4' ;;\n" + " check) case \"$4\" in --emit) cp \"$0.artifact\" \"$5\" ;; esac ;;\n" + " *) echo 'unsupported proxy command' >&2; exit 2 ;;\n" + "esac\n" + ) + proxy.chmod(0o755) + for name, payload, needle in [ + ("retired", retired, "旧 revision 3"), + ("digest", bad_digest, "source_digest"), + ("revision", bad_revision, "revision 3"), + ]: + (work / "core-proxy.artifact").write_text( + json.dumps(payload, ensure_ascii=False) + ) + result = run( + [lint, source, "--format", "json", "--fail-on", "never"], + env=dict(os.environ, MARQDO_BIN=str(proxy)), + expected=None, + ) + if result.returncode != 2: + raise GateError(f"{name}: expected exit 2, got {result.returncode}") + if needle not in result.stderr: + raise GateError(f"{name}: missing diagnostic {needle!r}: {result.stderr}") + tool = json.loads((ROOT / "tool.json").read_text()) + old_tool = dict(tool) + old_tool["compatibility"] = {"marqdo": ">=3.0.0-rc.4,<4.0.0", "analysis": [3]} + old_manifest = work / "old-tool.json" + old_manifest.write_text(json.dumps(old_tool, ensure_ascii=False)) + registry = work / "registry" + install = run( + [binary, "tool", "install", old_manifest], + env=dict(os.environ, MARQDO_TOOL_HOME=str(registry)), + expected=None, + ) + if install.returncode == 0: + raise GateError("old tool manifest installed successfully") + if "compatibility" not in install.stderr: + raise GateError("old tool manifest error does not name compatibility") + finally: + shutil.rmtree(work, ignore_errors=True) + + +def g08(manifest): + banned = [ + "双核心", + "Analysis v2/v3", + "compatibility 协商", + "RC" + "." + "1", + "RC" + "." + "2", + ] + for name in [ + "README.md", + "docs/PROTOCOL_BASELINE.md", + "docs/VALIDATION.md", + "docs/ARCHITECTURE.md", + "docs/CLI.md", + ]: + text = (ROOT / name).read_text() + for phrase in banned: + if phrase in text: + raise GateError(f"{name}: contains retired phrase {phrase!r}") + + +def g09(manifest): + pipeline = ROOT / ".woodpecker/main.yml" + if not pipeline.is_file(): + raise GateError("missing .woodpecker/main.yml") + text = pipeline.read_text() + for needle in ["check-no-legacy", "validate-control-flow", "cargo test --locked"]: + if needle not in text: + raise GateError(f"CI pipeline is missing {needle!r}") def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("rc1", type=Path, help="frozen marqdo 3.0.0-rc.1 executable") - parser.add_argument("rc2", type=Path, help="frozen marqdo 3.0.0-rc.2 executable") - parser.add_argument("--report", type=Path, help="write JSON evidence to this path") + parser.add_argument("core", type=Path, help="unpacked marqdo 3.0.0-rc.4 executable") + parser.add_argument("--report", type=Path, help="acceptance manifest path") args = parser.parse_args() + manifest = { + "schema": MANIFEST_SCHEMA, + "schema_version": MANIFEST_VERSION, + "lint_commit": run(["git", "rev-parse", "HEAD"]).stdout.strip(), + "lint_version": run([cargo_command(), "metadata", "--no-deps", "--format-version", "1"]).stdout + and json.loads( + run([cargo_command(), "metadata", "--no-deps", "--format-version", "1"]).stdout + )["packages"][0]["version"], + "lint_binary_sha256": None, + "tool_bundle_digest": None, + "cli_source_sha": CLI_SOURCE_SHA, + "cli_archive_sha256": f"sha256:{CLI_ARCHIVE_SHA}", + "cli_binary_sha256": f"sha256:{CLI_BINARY_SHA}", + "cli_binary_sha256_before": None, + "cli_binary_sha256_after": None, + "analysis_schema_sha256": f"sha256:{ANALYSIS_SCHEMA_SHA}", + "platform": PLATFORM, + "generated_utc": datetime.datetime.now(datetime.timezone.utc) + .replace(microsecond=0) + .isoformat() + .replace("+00:00", "Z"), + "gates": {}, + "unverified": [ + "G10 independent application trial: qdagent/qdqc pinned commits are not available in this workspace; result is analysis_incomplete semantics only, no false-positive rate claim." + ], + } try: - binaries = dict(zip(RELEASES, (args.rc1.resolve(), args.rc2.resolve()))) - before = {version: validate_core(binary, version) for version, binary in binaries.items()} - strace = shutil.which("strace") - require(strace, "strace is required to verify the Tool v1 subprocess contract") - results = {} - for version, binary in binaries.items(): - passed = test_suite(binary) - print(f"{version}: cargo test --locked, {passed} tests passed", flush=True) - results[version] = {**RELEASES[version], "tests_passed": passed, "binary_sha256_before": before[version]} - with tempfile.TemporaryDirectory(prefix="marqdo-lint-release-") as scratch: - bundle = Path(scratch) / "bundle" - run([ROOT / "scripts/package-tool.sh", bundle]) - manifest = json.loads((bundle / "tool.json").read_text()) - require(manifest["compatibility"]["analysis"] == [2, 3], "unexpected bundle compatibility") - evidence = { - "lint_binary_sha256": sha256(bundle / "bin/marqdo-lint"), - "tool_analysis_compatibility": manifest["compatibility"]["analysis"], - "cores": results, - } - for version, binary in binaries.items(): - results[version]["tool"] = validate_bundle(strace, binary, version, bundle, Path(scratch) / version) - after = sha256(binary) - require(after == before[version], f"{version}: core binary changed during gate") - results[version]["binary_sha256_after"] = after - print(f"{version}: packaged Tool v1 install, dispatch, exit codes and removal passed", flush=True) - if args.report: - args.report.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n") - except (OSError, ValidationError, ValueError, KeyError) as error: - parser.exit(1, f"release gate failed: {error}\n") + before = validate_core(args.core.resolve()) + manifest["cli_binary_sha256_before"] = f"sha256:{before}" + manifest["_core"] = args.core.resolve() + os.environ["MARQDO_BIN"] = str(args.core.resolve()) + gate(manifest, "G01", "scripts/check-no-legacy.sh", lambda: g01(manifest)) + gate(manifest, "G02", "cargo fmt --check; cargo clippy -D warnings; cargo test --locked", lambda: g02(manifest)) + gate(manifest, "G03", "scripts/package-tool.sh + tool install/list/dispatch/remove", lambda: g03(manifest)) + gate(manifest, "G04", "lint positive rules and safe fix", lambda: g04(manifest)) + gate(manifest, "G05", "lint JSON report vs schemas/marqdo-lint-v1.schema.json", lambda: g05(manifest)) + gate(manifest, "G06", "negative protocol/artifact/tool cases fail closed", lambda: g06(manifest)) + gate(manifest, "G07", "single-core rc.4 evidence manifest", lambda: None) + gate(manifest, "G08", "docs facts are rc.4-only", lambda: g08(manifest)) + gate(manifest, "G09", "Woodpecker CI covers G01-G07", lambda: g09(manifest)) + after = sha256_file(args.core.resolve()) + manifest["cli_binary_sha256_after"] = f"sha256:{after}" + if after != before: + raise GateError("core binary changed during acceptance") + manifest["gates"]["G10"] = { + "state": "UNVERIFIED", + "command": "independent qdagent/qdqc trial", + "exit_code": None, + } + manifest.pop("_core", None) + report = args.report or ( + ROOT / "docs/validation" / f"{CLI_SOURCE_SHA}.json" + ) + report.parent.mkdir(parents=True, exist_ok=True) + report.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n") + failed = [ + gate_id + for gate_id, value in manifest["gates"].items() + if value["state"] == "FAIL" + ] + print("\n".join(f"{key}: {value['state']}" for key, value in manifest["gates"].items())) + print(f"manifest: {report}") + if failed: + print(f"FAILED gates: {', '.join(failed)}") + return 1 + return 0 + except (GateError, OSError, ValueError, KeyError, subprocess.TimeoutExpired) as error: + print(f"acceptance failed: {error}") + return 1 if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/src/alignment/mod.rs b/src/alignment/mod.rs index e18b633..5078e78 100644 --- a/src/alignment/mod.rs +++ b/src/alignment/mod.rs @@ -93,16 +93,12 @@ pub fn align_function(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> R complete: false, issues: Vec::new(), }; - let mut headings = markdown.headings.iter().filter(|heading| { - heading.function == Some(heading.node) - && markdown.nodes[heading.node].span == analysis.heading_span - }); - let function = match (headings.next(), headings.next()) { - (Some(heading), None) => heading.node, - _ => { + let function = match markdown.function_heading(&analysis.id) { + Some(node) => node, + None => { tree.issues.push(at( analysis.heading_span, - "Analysis heading_span 无法唯一对应 Exec H2", + "Analysis function_id 无法对应 Exec H2", )); return tree; } diff --git a/src/alignment/semantic.rs b/src/alignment/semantic.rs index b725a20..b22cbd6 100644 --- a/src/alignment/semantic.rs +++ b/src/alignment/semantic.rs @@ -2,7 +2,7 @@ use std::collections::HashSet; use serde_json::Value; -use crate::model::{body, node_span, span_value, NodeId, Span, Statement, StatementKind}; +use crate::model::{body, node_span, span_value, NodeId, Statement, StatementKind}; use super::{ at, @@ -136,14 +136,6 @@ impl<'a, 'source> Matcher<'a, 'source> { .is_some_and(|control| self.tree.controls[control].kind == ControlKind::Loop), StatementKind::Break => located.jump == Some(JumpKind::Break), StatementKind::Continue => located.jump == Some(JumpKind::Continue), - StatementKind::Expression => { - let value = &statement.value["value"]; - // RC.1 could emit these bare identifiers as variable expressions. - located.ordinary - || (located.jump.is_some() - && value["kind"] == "variable" - && value["name"].as_str() == Some(located.carrier.payload.trim())) - } _ => located.ordinary, }; let primary = index.at(statement.span).filter(eligible); @@ -187,25 +179,19 @@ impl<'a, 'source> Matcher<'a, 'source> { let span = node_span(arm).ok_or_else(|| at(carrier.span, "Analysis 分支臂缺少 span"))?; let condition = span_value(&arm["condition_span"]); - let legacy = position == 1 - && source_arms.len() == 2 - && source_arm.role == ArmRole::Else - && is_legacy_else(&arms[0], arm); if self.source.at(carrier.span).is_none() { return Err(at(carrier.span, "源码分支臂无法唯一对应载体")); } - if !legacy { - let anchors = [Some(span), condition.filter(|condition| *condition != span)]; - let mut matches = false; - for anchor in anchors.into_iter().flatten() { - if !used_spans.insert(anchor) { - return Err(at(carrier.span, "Analysis 分支臂 span 重复")); - } - matches |= anchor == carrier.span; - } - if !matches { - return Err(at(carrier.span, "Analysis 分支臂与载体的位置或顺序不一致")); + let anchors = [Some(span), condition.filter(|condition| *condition != span)]; + let mut matches = false; + for anchor in anchors.into_iter().flatten() { + if !used_spans.insert(anchor) { + return Err(at(carrier.span, "Analysis 分支臂 span 重复")); } + matches |= anchor == carrier.span; + } + if !matches { + return Err(at(carrier.span, "Analysis 分支臂与载体的位置或顺序不一致")); } } for (position, arm) in arms.iter().enumerate() { @@ -220,18 +206,3 @@ impl<'a, 'source> Matcher<'a, 'source> { Ok(()) } } - -fn is_legacy_else(first: &Value, last: &Value) -> bool { - let condition = &last["condition"]; - let Some(first_span) = node_span(first) else { - return false; - }; - node_span(last) == Some(first_span) - && span_value(&last["condition_span"]) == Some(first_span) - && span_value(&first["condition_span"]) == Some(first_span) - && body(last).is_some_and(|body| !body.is_empty()) - && condition["kind"] == "literal" - && condition["type"] == "bool" - && condition["value"] == true - && node_span(condition) == Some(Span::new(0, 0)) -} diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 2e517b7..a1f76b9 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -34,6 +34,11 @@ pub struct Cli { fail_on: FailOnArg, #[arg(long, value_enum, value_name = "MODE")] fix: Option, + #[arg( + long, + help = "显式核验未加载的本地引用;会改变 Analysis bytes,不能用于 run/call 绑定" + )] + refs: bool, #[arg(long, requires = "fix", help = "校验并显示修复差异")] dry_run: bool, } @@ -114,7 +119,7 @@ pub fn run() -> Result { if inspected.contains(&entry) { continue; } - let mut project = ProjectInput::load(&entry, &runner)?; + let mut project = ProjectInput::load(&entry, &runner, cli.refs)?; let refusal = if cli.fix.is_some() { let outcome = fix_project( &project, @@ -123,7 +128,7 @@ pub fn run() -> Result { &mut std::io::stderr().lock(), )?; if outcome.changed { - project = ProjectInput::load(&entry, &runner)?; + project = ProjectInput::load(&entry, &runner, cli.refs)?; } outcome.diagnostic } else { diff --git a/src/config/mod.rs b/src/config/mod.rs index 12c828c..b922963 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -10,21 +10,16 @@ use crate::{ rules::{self, Severity}, }; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "kebab-case")] pub enum Profile { + #[default] Recommended, StrictDoc, Minimal, Migration, } -impl Default for Profile { - fn default() -> Self { - Self::Recommended - } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum RuleLevel { @@ -271,8 +266,10 @@ mod tests { let mut config = LintConfig::default(); config.rules.insert("UNKNOWN".into(), RuleLevel::Off); assert!(config.validate().is_err()); - let mut config = LintConfig::default(); - config.min_narrative_ratio = 2.0; + let config = LintConfig { + min_narrative_ratio: 2.0, + ..LintConfig::default() + }; assert!(config.validate().is_err()); let mut config = LintConfig::default(); config.suppressions.push(Suppression { diff --git a/src/diagnostics/report.rs b/src/diagnostics/report.rs index c699471..cf9c494 100644 --- a/src/diagnostics/report.rs +++ b/src/diagnostics/report.rs @@ -5,7 +5,7 @@ use crate::{ diagnostics::Diagnostic, engine::DocumentAnalysis, error::Result, - input::{AnalysisStatus, MarkdownOrigin, SourceDocument}, + input::{AnalysisStatus, SourceDocument}, metrics::{FunctionNarrative, MEASUREMENT_VERSION}, model::LineColumn, rules::Severity, @@ -58,10 +58,7 @@ impl DocumentReport { mut notices: Vec, core_output: String, ) -> Result { - if document.module.is_none() - || document.markdown_origin != MarkdownOrigin::MarqdoInspect - || !analysis.alignment_issues.is_empty() - { + if document.module.is_none() || !analysis.alignment_issues.is_empty() { analysis_status = AnalysisStatus::AnalysisIncomplete; } notices.append(&mut analysis.alignment_issues); diff --git a/src/engine.rs b/src/engine.rs index 874c23f..42c3a29 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -2,11 +2,11 @@ use crate::{ alignment::align_function, config::EffectiveConfig, diagnostics::Diagnostic, - input::{MarkdownOrigin, SourceDocument}, + input::SourceDocument, metrics::{measure_module_function, FunctionNarrative}, rules::{ - check_aligned, check_ast_document, check_entry_for_heading, check_entry_without_analysis, - check_function_documentation, check_supplemental_function, + check_aligned, check_ast_document, check_entry_for_heading, check_function_documentation, + check_supplemental_function, }, }; @@ -22,11 +22,7 @@ pub fn analyze_document(document: &SourceDocument, config: &EffectiveConfig) -> let mut diagnostics = check_ast_document(document); let mut metrics = Vec::new(); let mut alignment_issues = Vec::new(); - let module = document - .module - .as_ref() - .filter(|_| document.markdown_origin == MarkdownOrigin::MarqdoInspect); - if let Some(module) = module { + if let Some(module) = &document.module { for function in &module.functions { let tree = align_function(markdown, function); if !tree.complete { @@ -35,10 +31,7 @@ pub fn analyze_document(document: &SourceDocument, config: &EffectiveConfig) -> .iter() .map(|issue| format!("{}:{}", function.local_name, issue)), ); - if let Some(heading) = tree - .function - .and_then(|function| markdown.heading(function)) - { + if let Some(heading) = markdown.function_segment(&function.id) { diagnostics.extend(check_entry_for_heading(markdown, heading)); } continue; @@ -61,8 +54,6 @@ pub fn analyze_document(document: &SourceDocument, config: &EffectiveConfig) -> metrics.push(narrative); } } - } else { - diagnostics.extend(check_entry_without_analysis(document)); } diagnostics.sort_by(|left, right| (left.span, &left.id).cmp(&(right.span, &right.id))); DocumentAnalysis { diff --git a/src/error.rs b/src/error.rs index 331f780..08ec422 100644 --- a/src/error.rs +++ b/src/error.rs @@ -26,6 +26,12 @@ pub enum LintError { pub type Result = std::result::Result; +impl From for String { + fn from(error: LintError) -> Self { + error.to_string() + } +} + pub fn io(path: impl Into, source: std::io::Error) -> LintError { LintError::Io { path: path.into(), diff --git a/src/fix/mod.rs b/src/fix/mod.rs index 0ecf795..f1ce6b0 100644 --- a/src/fix/mod.rs +++ b/src/fix/mod.rs @@ -15,7 +15,7 @@ use crate::{ alignment::align_function, diagnostics::Diagnostic, error::{io, LintError, Result}, - input::{project_root, AnalysisStatus, MarkdownOrigin, MarqdoRunner, ProjectInput}, + input::{project_root, AnalysisStatus, MarqdoRunner, ProjectInput}, model::Span, }; @@ -134,16 +134,7 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates ensure_sources_unchanged(project)?; let root = project_root(&project.entry); let staged = tempdir().map_err(|error| io("修复验证目录", error))?; - for name in ["marqdo.yaml", "marqdo.lock"] { - let file = root.join(name); - match fs::read(&file) { - Ok(bytes) => { - fs::write(staged.path().join(name), bytes).map_err(|error| io(&file, error))? - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(io(&file, error)), - } - } + copy_project_metadata(&root, staged.path())?; for document in &project.documents { let path = &document.source.path; @@ -159,7 +150,7 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates } let entry = staged.path().join(relative_to(&project.entry, &root)?); - let checked = ProjectInput::load(entry, runner)?; + let checked = ProjectInput::load(entry, runner, false)?; require_complete(&checked)?; let original = project .analysis @@ -183,49 +174,66 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates for document in &project.documents { let path = &document.source.path; + let Some(candidate_module) = document.module.as_ref() else { + return Err(refusal("候选文档缺少 Analysis 模块")); + }; if !candidates.contains_key(path) { continue; } - let shadow = staged.path().join(relative_to(path, &root)?); - let revised = checked + let revised_document = checked .documents .iter() - .find(|candidate| candidate.source.path == shadow) + .find(|candidate| { + candidate + .module + .as_ref() + .is_some_and(|module| module.id == candidate_module.id) + }) .ok_or_else(|| refusal("候选文档缺少 Analysis 模块"))?; - let payloads = |document: &crate::input::SourceDocument| { - document - .markdown - .carriers - .iter() - .map(|carrier| (carrier.kind, carrier.payload.clone())) - .collect::>() - }; - - let mut before_ast = runner.inspect(path)?; - let mut after_ast = runner.inspect(&shadow)?; + let mut before_ast = candidate_module.document.clone(); + let mut after_ast = revised_document + .module + .as_ref() + .expect("checked by require_complete") + .document + .clone(); strip_spans(&mut before_ast); strip_spans(&mut after_ast); - if before_ast != after_ast || payloads(document) != payloads(revised) { + if before_ast != after_ast || payloads(document) != payloads(revised_document) { return Err(refusal("Markdown 结构、文字或执行载荷发生变化")); } } ensure_sources_unchanged(project) } +fn copy_project_metadata(root: &Path, destination: &Path) -> Result<()> { + for name in ["marqdo.yaml", "marqdo.lock"] { + let file = root.join(name); + match fs::read(&file) { + Ok(bytes) => { + fs::write(destination.join(name), bytes).map_err(|error| io(&file, error))? + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(io(&file, error)), + } + } + Ok(()) +} + fn require_complete(project: &ProjectInput) -> Result<()> { if project.analysis_status != AnalysisStatus::Complete || project.analysis.is_none() { - return Err(refusal("无法取得完整的 Analysis v2/v3")); + return Err(refusal("无法取得完整的 Analysis revision 3")); } for document in &project.documents { - if document.markdown_origin != MarkdownOrigin::MarqdoInspect - || document.module.as_ref().is_none_or(|module| { - module - .functions - .iter() - .any(|function| !align_function(&document.markdown, function).complete) - }) + let Some(module) = &document.module else { + return Err(refusal("文档缺少 Analysis 模块")); + }; + if module + .functions + .iter() + .any(|function| !align_function(&document.markdown, function).complete) { - return Err(refusal("公开 AST 与 Analysis 无法完整对齐")); + return Err(refusal("公开 document/units 与 Analysis 无法完整对齐")); } } Ok(()) @@ -245,10 +253,10 @@ fn analysis_fingerprint(analysis: &Value, changed_modules: &[&str]) -> Value { .as_str() .is_some_and(|id| changed_modules.contains(&id)) { - module - .as_object_mut() - .expect("module id is a field") - .remove("source_digest"); + let module = module.as_object_mut().expect("module id is a field"); + for field in ["source_digest", "source", "document", "units", "anchors"] { + module.remove(field); + } } } } @@ -299,6 +307,15 @@ fn ensure_sources_unchanged(project: &ProjectInput) -> Result<()> { Ok(()) } +fn payloads(document: &crate::input::SourceDocument) -> Vec<(crate::model::CarrierKind, String)> { + document + .markdown + .carriers + .iter() + .map(|carrier| (carrier.kind, carrier.payload.clone())) + .collect() +} + fn prepare_replacement(path: &Path, candidate: &str) -> Result { let mut file = NamedTempFile::new_in(path.parent().expect("canonical path has parent")) .map_err(|error| io(path, error))?; @@ -315,82 +332,3 @@ fn prepare_replacement(path: &Path, candidate: &str) -> Result { fn refusal(message: &str) -> LintError { LintError::UnsafeFix(message.into()) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn t27_verifier_rejects_a_list_layout_change_even_with_unchanged_execution() { - let Some(core) = std::env::var_os("MARQDO_BIN") else { - return; - }; - let runner = MarqdoRunner::discover(Some(Path::new(&core))).unwrap(); - let dir = tempdir().unwrap(); - let file = dir.path().join("index.mq.md"); - let original = - "## @exec choice\n\n**x = 0**\n\n1. `if true`\n\n **x = 1**\n\n`end`\n\n*return x*\n"; - let revised = original.replace("1. ", "").replace(" **", "**"); - fs::write(&file, original).unwrap(); - let project = ProjectInput::load(&file, &runner).unwrap(); - let candidates = BTreeMap::from([(project.entry.clone(), revised)]); - let error = verify(&project, &runner, &candidates).unwrap_err(); - assert!(error.to_string().contains("Markdown"), "{error}"); - assert_eq!(fs::read_to_string(file).unwrap(), original); - } - #[test] - fn safe_fix_checks_whitespace_and_refuses_reassigned_control_bodies() { - let Some(core) = std::env::var_os("MARQDO_BIN") else { - return; - }; - let runner = MarqdoRunner::discover(Some(Path::new(&core))).unwrap(); - let rc2 = std::process::Command::new(runner.binary()) - .arg("--version") - .output() - .unwrap() - .stdout - .ends_with(b"3.0.0-rc.2\n"); - let v2 = "## @exec main\n\n`if false`\n\n*return 1*\n\n`else`\n\n*return 2*\n\n`end`\n"; - let v3 = "## @exec main\n\n`while false`\n\n`while false`\n\n`break`\n\n`end`\n\n`end`\n"; - let cases = [ - ( - 2, - v2, - v2.replace("`else`\n\n*return 2*", "*return 2*\n\n`else`"), - ), - (3, v3, v3.replace("`break`\n\n`end`", "`end`\n\n`break`")), - ]; - for (major, source, different_body) in - cases.into_iter().filter(|(major, _, _)| *major == 2 || rc2) - { - let dir = tempdir().unwrap(); - let file = dir.path().join("case.mq.md"); - let original = source.replace("## @exec main\n\n", "## @exec main\n \t\n"); - fs::write(&file, &original).unwrap(); - let project = ProjectInput::load(&file, &runner).unwrap(); - assert_eq!(project.analysis.as_ref().unwrap().schema_version, major); - let mut diff = Vec::new(); - let dry_run = fix_project(&project, &runner, true, &mut diff).unwrap(); - assert!(!dry_run.changed && dry_run.diagnostic.is_none() && !diff.is_empty()); - assert_eq!(fs::read(&file).unwrap(), original.as_bytes()); - let candidates = Candidates::from([(project.entry.clone(), different_body)]); - for dry_run in [true, false] { - let refused = - apply_candidates(&project, &runner, &candidates, dry_run, &mut Vec::new()) - .unwrap(); - assert!(!refused.changed); - let diagnostic = refused.diagnostic.unwrap(); - assert_eq!(diagnostic.id, "MQD-SAFETY-001"); - assert!( - diagnostic.message.contains("Analysis 中"), - "{}", - diagnostic.message - ); - assert_eq!(fs::read(&file).unwrap(), original.as_bytes()); - } - let applied = fix_project(&project, &runner, false, &mut Vec::new()).unwrap(); - assert!(applied.changed && applied.diagnostic.is_none()); - assert_eq!(fs::read(&file).unwrap(), source.as_bytes()); - } - } -} diff --git a/src/input/fallback.rs b/src/input/fallback.rs deleted file mode 100644 index 5f4a2f1..0000000 --- a/src/input/fallback.rs +++ /dev/null @@ -1,201 +0,0 @@ -use comrak::{ - nodes::{ListType, Node, NodeValue, Sourcepos, TableAlignment}, - parse_document, Arena, Options, -}; -use serde_json::{json, Map, Value}; - -use crate::{error::Result, model::SourceSnapshot}; - -pub fn profile_options() -> Options<'static> { - let mut options = Options::default(); - options.extension.table = true; - options.extension.strikethrough = true; - options.extension.tasklist = true; - options.extension.math_dollars = true; - options.extension.math_dollars_block = true; - options.extension.front_matter_delimiter = Some("---".to_string()); - options -} - -pub fn fallback_ast(source: &SourceSnapshot) -> Result { - let text = source.text(); - let (shift, body) = text - .strip_prefix('\u{feff}') - .map(|body| (3, body)) - .unwrap_or((0, text)); - let arena = Arena::new(); - let root = parse_document(&arena, body, &profile_options()); - let line_starts = line_starts(body); - Ok(convert(&root, &line_starts, shift, body.len())) -} - -fn line_starts(source: &str) -> Vec { - let mut starts = vec![0]; - for (index, byte) in source.bytes().enumerate() { - if byte == b'\n' { - starts.push(index + 1); - } - } - starts -} - -fn span(pos: Sourcepos, starts: &[usize], shift: usize, len: usize) -> SpanValue { - let offset = |line: usize, column: usize, inclusive: bool| { - if line == 0 { - return 0; - } - starts - .get(line - 1) - .map(|start| { - (start + column.saturating_sub(1) + usize::from(inclusive)).min(len) - }) - .unwrap_or(len) - }; - let start = offset(pos.start.line, pos.start.column, false); - let end = offset(pos.end.line, pos.end.column, true).max(start); - SpanValue(start + shift, end + shift) -} - -struct SpanValue(usize, usize); - -fn convert(node: &Node<'_>, starts: &[usize], shift: usize, len: usize) -> Value { - let data = node.data(); - let SpanValue(start, end) = span(data.sourcepos, starts, shift, len); - let mut object = Map::new(); - object.insert("span".into(), json!({"start": start, "end": end})); - let mut literal = None; - match &data.value { - NodeValue::Document => { - object.insert("kind".into(), json!("document")); - } - NodeValue::FrontMatter(raw) => { - object.insert("kind".into(), json!("front_matter")); - literal = Some(raw.clone()); - } - NodeValue::BlockQuote | NodeValue::MultilineBlockQuote(_) => { - object.insert("kind".into(), json!("block_quote")); - } - NodeValue::List(list) => { - object.insert("kind".into(), json!("list")); - object.insert( - "ordered".into(), - json!(list.list_type == ListType::Ordered), - ); - if list.list_type == ListType::Ordered { - object.insert("start".into(), json!(list.start)); - } - object.insert("tight".into(), json!(list.tight)); - } - NodeValue::Item(_) => { - object.insert("kind".into(), json!("item")); - } - NodeValue::TaskItem(item) => { - object.insert("kind".into(), json!("item")); - object.insert("task".into(), json!(item.symbol.is_some())); - } - NodeValue::Heading(heading) => { - object.insert("kind".into(), json!("heading")); - object.insert("level".into(), json!(heading.level)); - object.insert("setext".into(), json!(heading.setext)); - } - NodeValue::Paragraph => { - object.insert("kind".into(), json!("paragraph")); - } - NodeValue::Text(text) => { - object.insert("kind".into(), json!("text")); - literal = Some(text.to_string()); - } - NodeValue::Strong(_) => { - object.insert("kind".into(), json!("strong")); - } - NodeValue::Emph(_) => { - object.insert("kind".into(), json!("emph")); - } - NodeValue::Strikethrough(_) => { - object.insert("kind".into(), json!("strikethrough")); - } - NodeValue::Code(code) => { - object.insert("kind".into(), json!("code")); - object.insert("ticks".into(), json!(code.num_backticks)); - literal = Some(code.literal.clone()); - } - NodeValue::CodeBlock(block) => { - object.insert("kind".into(), json!("code_block")); - object.insert("fenced".into(), json!(block.fenced)); - object.insert("info".into(), json!(block.info.trim())); - literal = Some(block.literal.clone()); - } - NodeValue::Math(math) => { - object.insert("kind".into(), json!("math")); - object.insert("display".into(), json!(math.display_math)); - literal = Some(math.literal.clone()); - } - NodeValue::MathBlock(block) => { - object.insert("kind".into(), json!("math_block")); - literal = Some(block.literal.clone()); - } - NodeValue::Link(link) => { - object.insert("kind".into(), json!("link")); - object.insert("url".into(), json!(link.url)); - object.insert("title".into(), json!(link.title)); - } - NodeValue::Image(image) => { - object.insert("kind".into(), json!("image")); - object.insert("url".into(), json!(image.url)); - object.insert("title".into(), json!(image.title)); - } - NodeValue::Table(table) => { - object.insert("kind".into(), json!("table")); - let alignments: Vec<_> = table - .alignments - .iter() - .map(|alignment| match alignment { - TableAlignment::Left => "left", - TableAlignment::Center => "center", - TableAlignment::Right => "right", - TableAlignment::None => "none", - }) - .collect(); - object.insert("alignments".into(), json!(alignments)); - } - NodeValue::TableRow(row) => { - object.insert("kind".into(), json!("table_row")); - object.insert("header".into(), json!(row.header)); - } - NodeValue::TableCell => { - object.insert("kind".into(), json!("table_cell")); - } - NodeValue::ThematicBreak(_) => { - object.insert("kind".into(), json!("thematic_break")); - } - NodeValue::SoftBreak => { - object.insert("kind".into(), json!("soft_break")); - } - NodeValue::LineBreak => { - object.insert("kind".into(), json!("line_break")); - } - NodeValue::HtmlBlock(block) => { - object.insert("kind".into(), json!("html_block")); - literal = Some(block.literal.clone()); - } - NodeValue::HtmlInline(raw) => { - object.insert("kind".into(), json!("html_inline")); - literal = Some(raw.clone()); - } - other => { - object.insert("kind".into(), json!("other")); - object.insert("tag".into(), json!(format!("{other:?}"))); - } - } - if let Some(literal) = literal { - object.insert("literal".into(), json!(literal)); - } - let children: Vec<_> = node - .children() - .map(|child| convert(&child, starts, shift, len)) - .collect(); - if !children.is_empty() { - object.insert("children".into(), Value::Array(children)); - } - Value::Object(object) -} diff --git a/src/input/marqdo.rs b/src/input/marqdo.rs index b7108c8..4a76b55 100644 --- a/src/input/marqdo.rs +++ b/src/input/marqdo.rs @@ -1,4 +1,5 @@ use std::{ + cmp::Ordering, fs, path::{Path, PathBuf}, process::{Command, Output}, @@ -6,6 +7,7 @@ use std::{ use serde::Deserialize; use serde_json::Value; +use sha2::{Digest, Sha256}; use tempfile::NamedTempFile; use crate::error::{io, LintError, Result}; @@ -13,12 +15,15 @@ use crate::error::{io, LintError, Result}; #[derive(Debug, Clone)] pub struct MarqdoRunner { binary: PathBuf, + version: SemVer, } #[derive(Debug)] pub struct CheckOutcome { pub success: bool, pub analysis: Option, + pub analysis_bytes: Vec, + pub artifact_digest: Option, pub output: String, pub diagnostics: Vec, } @@ -66,71 +71,56 @@ impl MarqdoRunner { .map(Path::to_path_buf) .or_else(|| std::env::var_os("MARQDO_BIN").map(PathBuf::from)) .unwrap_or_else(|| PathBuf::from("marqdo")); - let runner = Self { binary }; - runner.ensure_compatible()?; - Ok(runner) + let output = Command::new(&binary) + .arg("--version") + .output() + .map_err(|error| io(&binary, error))?; + if !output.status.success() { + return Err(LintError::Core(format!( + "无法运行 {} --version:{}", + binary.display(), + format_output(&output) + ))); + } + let text = String::from_utf8_lossy(&output.stdout); + let text = text.trim(); + let raw = text.strip_prefix("marqdo ").unwrap_or(text); + let version = SemVer::parse(raw).map_err(|error| { + LintError::Protocol(format!( + "无法解析 Marqdo 版本 {raw:?}:{error};需要 Marqdo >=3.0.0-rc.4,<4.0.0" + )) + })?; + let minimum = SemVer::parse("3.0.0-rc.4").expect("static version"); + let maximum = SemVer::parse("4.0.0").expect("static version"); + if version < minimum || version >= maximum { + return Err(LintError::Protocol(format!( + "需要 Marqdo >=3.0.0-rc.4,<4.0.0,实际为 {raw};请升级核心并用当前 CLI 重新生成 Analysis,重装 marqdo-lint Tool" + ))); + } + Ok(Self { binary, version }) } pub fn binary(&self) -> &Path { &self.binary } - pub fn ensure_compatible(&self) -> Result<()> { - let output = self.run(&[std::ffi::OsStr::new("--version")])?; - if !output.status.success() { - return Err(LintError::Core(format_output(&output))); - } - let version = String::from_utf8_lossy(&output.stdout); - let version = version - .trim() - .strip_prefix("marqdo ") - .unwrap_or(version.trim()); - let major = version - .split('.') - .next() - .and_then(|part| part.parse::().ok()); - if major != Some(3) { - return Err(LintError::Protocol(format!( - "需要 Marqdo >=3.0.0-beta.1,<4.0.0,实际为 {version}" - ))); - } - Ok(()) + pub fn version(&self) -> &SemVer { + &self.version } - pub fn inspect(&self, file: &Path) -> Result { - let output = Command::new(&self.binary) - .arg("inspect") - .arg(file) - .arg("--ast") - .arg("--json") - .output() - .map_err(|error| io(&self.binary, error))?; - if !output.status.success() { - return Err(LintError::Core(format_output(&output))); - } - let value: Value = serde_json::from_slice(&output.stdout) - .map_err(|error| LintError::Protocol(format!("inspect AST JSON 无效:{error}")))?; - if value.get("command").and_then(Value::as_str) != Some("inspect") { - return Err(LintError::Protocol( - "inspect 输出缺少 command=inspect".into(), - )); - } - value - .get("ast") - .cloned() - .ok_or_else(|| LintError::Protocol("inspect 输出缺少 ast 字段".into())) - } - - pub fn check(&self, file: &Path) -> Result { + pub fn check(&self, file: &Path, refs: bool) -> Result { let temporary = NamedTempFile::new().map_err(|error| io("Analysis 临时文件", error))?; - let output = Command::new(&self.binary) + let mut command = Command::new(&self.binary); + command .arg("check") .arg(file) .arg("--json") .arg("--emit") - .arg(temporary.path()) - .output() - .map_err(|error| io(&self.binary, error))?; + .arg(temporary.path()); + if refs { + command.arg("--refs"); + } + let output = command.output().map_err(|error| io(&self.binary, error))?; if !output.status.success() { let diagnostics = check_diagnostics(&output.stdout); let text = if diagnostics.is_empty() { @@ -145,27 +135,30 @@ impl MarqdoRunner { return Ok(CheckOutcome { success: false, analysis: None, + analysis_bytes: Vec::new(), + artifact_digest: None, output: text, diagnostics, }); } let bytes = fs::read(temporary.path()).map_err(|error| io(temporary.path(), error))?; + if bytes.is_empty() { + return Err(LintError::Protocol( + "核心 check 成功但没有写出 Analysis 工件".into(), + )); + } + let artifact_digest = format!("sha256:{:x}", Sha256::digest(&bytes)); let analysis = serde_json::from_slice(&bytes) .map_err(|error| LintError::Protocol(format!("Analysis JSON 无效:{error}")))?; Ok(CheckOutcome { success: true, analysis: Some(analysis), + analysis_bytes: bytes, + artifact_digest: Some(artifact_digest), output: String::new(), diagnostics: Vec::new(), }) } - - fn run(&self, args: &[&std::ffi::OsStr]) -> Result { - Command::new(&self.binary) - .args(args) - .output() - .map_err(|error| io(&self.binary, error)) - } } fn format_output(output: &Output) -> String { @@ -191,3 +184,140 @@ fn check_diagnostics(stdout: &[u8]) -> Vec { .filter(|report| report.command == "check") .map_or_else(Vec::new, |report| report.diagnostics) } + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SemVer { + major: u64, + minor: u64, + patch: u64, + prerelease: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Identifier { + Numeric(u64), + Text(String), +} + +impl SemVer { + pub fn parse(input: &str) -> std::result::Result { + let input = input.trim(); + let (core, build) = match input.split_once('+') { + Some((core, build)) => { + if build.is_empty() + || !build + .split('.') + .all(|part| !part.is_empty() && is_identifier(part)) + { + return Err("build metadata 无效".into()); + } + (core, Some(build)) + } + None => (input, None), + }; + let _ = build; + let (core, prerelease) = match core.split_once('-') { + Some((core, prerelease)) => (core, Some(prerelease)), + None => (core, None), + }; + let mut parts = core.split('.'); + let major = parse_number(parts.next(), "major")?; + let minor = parse_number(parts.next(), "minor")?; + let patch = parse_number(parts.next(), "patch")?; + if parts.next().is_some() { + return Err("版本号段过多".into()); + } + let mut identifiers = Vec::new(); + if let Some(prerelease) = prerelease { + if prerelease.is_empty() { + return Err("prerelease 为空".into()); + } + for part in prerelease.split('.') { + if part.is_empty() || !is_identifier(part) { + return Err(format!("prerelease 标识 {part:?} 无效")); + } + if part.bytes().all(|byte| byte.is_ascii_digit()) { + let value = part + .parse::() + .map_err(|_| format!("prerelease 数字 {part:?} 溢出"))?; + identifiers.push(Identifier::Numeric(value)); + } else { + identifiers.push(Identifier::Text(part.to_string())); + } + } + } + Ok(Self { + major, + minor, + patch, + prerelease: identifiers, + }) + } +} + +fn parse_number(part: Option<&str>, name: &str) -> std::result::Result { + let part = part.ok_or_else(|| format!("缺少 {name} 版本段"))?; + if part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(format!("{name} 必须是数字")); + } + part.parse::() + .map_err(|_| format!("{name} 版本段溢出")) +} + +fn is_identifier(value: &str) -> bool { + value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') +} + +impl Ord for SemVer { + fn cmp(&self, other: &Self) -> Ordering { + (self.major, self.minor, self.patch) + .cmp(&(other.major, other.minor, other.patch)) + .then_with(|| compare_prerelease(&self.prerelease, &other.prerelease)) + } +} + +impl PartialOrd for SemVer { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +fn compare_prerelease(left: &[Identifier], right: &[Identifier]) -> Ordering { + match (left.is_empty(), right.is_empty()) { + (true, true) => Ordering::Equal, + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + (false, false) => { + for (left, right) in left.iter().zip(right) { + let ordering = match (left, right) { + (Identifier::Numeric(left), Identifier::Numeric(right)) => left.cmp(right), + (Identifier::Numeric(_), Identifier::Text(_)) => Ordering::Less, + (Identifier::Text(_), Identifier::Numeric(_)) => Ordering::Greater, + (Identifier::Text(left), Identifier::Text(right)) => left.cmp(right), + }; + if ordering != Ordering::Equal { + return ordering; + } + } + left.len().cmp(&right.len()) + } + } +} + +#[cfg(test)] +mod tests { + use super::SemVer; + + #[test] + fn enforces_the_current_prerelease_floor() { + assert!(SemVer::parse("3.0.0-rc.4").unwrap() < SemVer::parse("3.0.0").unwrap()); + assert!(SemVer::parse("3.0.0-rc.3").unwrap() < SemVer::parse("3.0.0-rc.4").unwrap()); + assert!(SemVer::parse("3.0.0-rc.10").unwrap() > SemVer::parse("3.0.0-rc.4").unwrap()); + assert!(SemVer::parse("3.1.0-alpha.1").unwrap() > SemVer::parse("3.0.0-rc.4").unwrap()); + assert!(SemVer::parse("4.0.0").unwrap() > SemVer::parse("3.0.0").unwrap()); + assert!(SemVer::parse("3.0").is_err()); + assert!(SemVer::parse("3.0.0-").is_err()); + } +} diff --git a/src/input/mod.rs b/src/input/mod.rs index 7b67024..707f658 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -1,8 +1,6 @@ -mod fallback; mod marqdo; mod project; -pub use fallback::{fallback_ast, profile_options}; -pub use marqdo::{CheckDiagnostic, CheckOutcome, MarqdoRunner}; +pub use marqdo::{CheckDiagnostic, CheckOutcome, MarqdoRunner, SemVer}; pub(crate) use project::project_root; -pub use project::{AnalysisStatus, MarkdownOrigin, ProjectInput, SourceDocument}; +pub use project::{AnalysisStatus, ProjectInput, SourceDocument}; diff --git a/src/input/project.rs b/src/input/project.rs index 04a4791..bac48e3 100644 --- a/src/input/project.rs +++ b/src/input/project.rs @@ -4,13 +4,14 @@ use std::{ }; use serde::Serialize; +use sha2::{Digest, Sha256}; use crate::{ error::{io, LintError, Result}, model::{AnalysisModule, ExecutionProjection, MarkdownTree, SourceSnapshot}, }; -use super::{fallback_ast, CheckDiagnostic, MarqdoRunner}; +use super::{CheckDiagnostic, MarqdoRunner}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] @@ -19,18 +20,10 @@ pub enum AnalysisStatus { AnalysisIncomplete, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum MarkdownOrigin { - MarqdoInspect, - ComrakFallback, -} - #[derive(Debug, Clone)] pub struct SourceDocument { pub source: SourceSnapshot, pub markdown: MarkdownTree, - pub markdown_origin: MarkdownOrigin, pub module: Option, } @@ -40,55 +33,74 @@ pub struct ProjectInput { pub documents: Vec, pub analysis: Option, pub analysis_status: AnalysisStatus, + pub artifact_digest: Option, pub core_output: String, pub core_diagnostics: Vec, pub notices: Vec, } impl ProjectInput { - pub fn load(entry: impl AsRef, runner: &MarqdoRunner) -> Result { + pub fn load(entry: impl AsRef, runner: &MarqdoRunner, refs: bool) -> Result { let entry = fs::canonicalize(entry.as_ref()).map_err(|error| io(entry.as_ref(), error))?; - let mut notices = Vec::new(); - let entry_document = read_document(&entry, runner, &mut notices)?; - let check = runner.check(&entry)?; + let check = runner.check(&entry, refs)?; if !check.success { + let source = SourceSnapshot::load(&entry)?; + let markdown = MarkdownTree::empty(&source); return Ok(Self { entry, - documents: vec![entry_document], + documents: vec![SourceDocument { + source, + markdown, + module: None, + }], analysis: None, analysis_status: AnalysisStatus::AnalysisIncomplete, + artifact_digest: None, core_output: check.output, core_diagnostics: check.diagnostics, - notices, + notices: Vec::new(), }); } - let raw = check - .analysis - .ok_or_else(|| LintError::Protocol("核心 check 成功但没有生成 Analysis".into()))?; - let analysis = ExecutionProjection::from_json(raw).map_err(LintError::Protocol)?; + let bytes = check.analysis_bytes; + let artifact_digest = check.artifact_digest; + let analysis = ExecutionProjection::from_bytes(&bytes).map_err(LintError::Protocol)?; + let entry_module = analysis + .entry_module() + .ok_or_else(|| LintError::Protocol("Analysis 缺少 entry_module_id 对应模块".into()))?; + let root_package = entry_module.package_instance_id.clone(); let root = project_root(&entry); + let entry_module_id = analysis.project.entry_module_id.clone(); let mut documents = Vec::new(); for module in analysis .modules .iter() - .filter(|module| module.package_instance_id.starts_with("root:")) + .filter(|module| module.package_instance_id == root_package) { - let path = root.join(&module.relative_path); - let mut document = read_document(&path, runner, &mut notices)?; - if document.source.digest_hex() != module.source_digest { - return Err(LintError::Protocol(format!( - "模块 {} 的源码摘要与 Analysis 不一致", - module.id - ))); - } + let path = if module.id == entry_module_id { + entry.clone() + } else { + root.join(&module.relative_path) + }; + let source = module.source_snapshot(path)?; + let markdown = MarkdownTree::from_analysis( + module.document.clone(), + &module.units, + &module.functions, + &source, + )?; for function in &module.functions { - function.validate_source_spans(&document.source)?; + function.validate_source_spans(&source)?; } - document.module = Some(module.clone()); - documents.push(document); + documents.push(SourceDocument { + source, + markdown, + module: Some(module.clone()), + }); } if documents.is_empty() { - documents.push(entry_document); + return Err(LintError::Protocol( + "Analysis 中没有入口项目根包的模块".into(), + )); } documents.sort_by(|left, right| left.source.path.cmp(&right.source.path)); Ok(Self { @@ -96,59 +108,12 @@ impl ProjectInput { documents, analysis: Some(analysis), analysis_status: AnalysisStatus::Complete, + artifact_digest, core_output: String::new(), core_diagnostics: Vec::new(), - notices, + notices: Vec::new(), }) } - - pub fn document_only(entry: impl AsRef, runner: &MarqdoRunner) -> Result { - let entry = fs::canonicalize(entry.as_ref()).map_err(|error| io(entry.as_ref(), error))?; - let mut notices = Vec::new(); - let document = read_document(&entry, runner, &mut notices)?; - Ok(Self { - entry, - documents: vec![document], - analysis: None, - analysis_status: AnalysisStatus::AnalysisIncomplete, - core_output: String::new(), - core_diagnostics: Vec::new(), - notices, - }) - } -} - -fn read_document( - path: &Path, - runner: &MarqdoRunner, - notices: &mut Vec, -) -> Result { - let source = SourceSnapshot::load(path)?; - match runner.inspect(path) { - Ok(ast) => { - let markdown = MarkdownTree::from_json(ast, &source)?; - Ok(SourceDocument { - source, - markdown, - markdown_origin: MarkdownOrigin::MarqdoInspect, - module: None, - }) - } - Err(LintError::Core(message)) => { - let markdown = MarkdownTree::from_json(fallback_ast(&source)?, &source)?; - notices.push(format!( - "{}:inspect 不可用,已使用严格 comrak 降级;{message}", - path.display() - )); - Ok(SourceDocument { - source, - markdown, - markdown_origin: MarkdownOrigin::ComrakFallback, - module: None, - }) - } - Err(error) => Err(error), - } } pub(crate) fn project_root(entry: &Path) -> PathBuf { @@ -163,3 +128,8 @@ pub(crate) fn project_root(entry: &Path) -> PathBuf { current = parent; } } + +#[allow(dead_code)] +pub(crate) fn artifact_sha256(bytes: &[u8]) -> String { + format!("sha256:{:x}", Sha256::digest(bytes)) +} diff --git a/src/metrics/mod.rs b/src/metrics/mod.rs index 59f4a21..3337765 100644 --- a/src/metrics/mod.rs +++ b/src/metrics/mod.rs @@ -8,8 +8,8 @@ use crate::{ alignment::statement_count, input::SourceDocument, model::{ - effect_sites, statements, AnalysisFunction, Carrier, HeadingMode, MarkdownTree, NodeId, - ProseFragment, Span, StatementKind, + effect_sites, statements, AnalysisCall, AnalysisFunction, Carrier, HeadingMode, + MarkdownTree, NodeId, ProseFragment, Span, StatementKind, }, }; @@ -93,7 +93,7 @@ pub fn measure_document( pub(crate) fn measure_module_function( markdown: &MarkdownTree, function: &AnalysisFunction, - calls: &[serde_json::Value], + calls: &[AnalysisCall], config: NarrativeConfig, ) -> Option { let mut metrics = measure_function(markdown, function, config)?; @@ -106,10 +106,7 @@ pub fn measure_function( analysis: &AnalysisFunction, config: NarrativeConfig, ) -> Option { - let heading = markdown.headings.iter().find(|heading| { - heading.function == Some(heading.node) - && markdown.nodes[heading.node].span == analysis.heading_span - })?; + let heading = markdown.function_segment(&analysis.id)?; let function = heading.node; let mut carriers: Vec<_> = markdown .carriers diff --git a/src/model/analysis.rs b/src/model/analysis.rs index f7c8dcb..9de75b6 100644 --- a/src/model/analysis.rs +++ b/src/model/analysis.rs @@ -1,51 +1,299 @@ +use std::collections::{HashMap, HashSet}; + use serde::{Deserialize, Serialize}; -use serde_json::Value; +use serde_json::{Map, Value}; +use sha2::{Digest, Sha256}; use super::{SourceSnapshot, Span}; use crate::error::Result as LintResult; +/// One actionable sentence attached to every protocol rejection. Consumers are +/// expected to fail closed; they must never try to repair an old artifact. +pub(crate) const PROTOCOL_REGEN_HINT: &str = + "请用当前 marqdo CLI(>=3.0.0-rc.4)重新生成 Analysis,重新安装 marqdo-lint Tool,并重建 lint"; + #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct Producer { pub name: String, pub version: String, pub markdown_profile: String, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum IdentityKind { + Manifest, + WorkspaceSnapshot, +} + #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StdlibIdentity { + pub version: String, + pub digest: String, + pub instance_id: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExtensionIdentity { + pub kind: String, + pub name: String, + pub version: String, + pub logical_owner: String, + pub source: String, + pub manifest_digest: String, + pub artifact_digest: String, + pub selected_target: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisProject { + pub root_id: String, + pub identity_kind: IdentityKind, + pub entry_module_id: String, + pub lock_digest: String, + pub manifest_digest: String, + pub stdlib: Option, + pub extensions: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UnitKind { + Root, + Namespace, + Function, + Knowledge, + Section, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HeadingMode { + Exec, + Knowledge, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ModeOrigin { + Default, + Explicit, + Inherited, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisUnit { + pub id: String, + pub path: Vec, + pub parent_id: Option, + pub kind: UnitKind, + pub name: String, + pub level: u8, + pub mode: HeadingMode, + pub mode_origin: ModeOrigin, + pub mode_source_unit_id: String, + pub heading_span: Option, + pub span: Span, + pub function: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisAnchor { + pub anchor: String, + pub unit_id: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SignatureKind { + Explicit, + Inferred, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisParam { + pub name: String, + pub required: bool, + #[serde(rename = "type")] + pub param_type: Option, + pub default: Option, + pub span: Span, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisSignature { + pub kind: SignatureKind, + pub params: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct AnalysisFunction { pub id: String, pub unit_id: String, pub local_name: String, + pub namespace: Option, pub span: Span, pub heading_span: Span, - pub signature: Value, - #[serde(default)] + pub signature: AnalysisSignature, pub effects: Vec, pub body: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisImport { + pub alias: String, + pub target: String, + pub span: Span, + pub resolved: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReferenceState { + Resolved, + NotLoaded, + Missing, + Ambiguous, + External, + OutsideScope, + Invalid, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReferenceTargetKind { + Module, + File, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisReference { + pub source: String, + pub source_unit: String, + pub url: String, + pub span: Span, + pub state: ReferenceState, + pub target_kind: Option, + pub target_module: Option, + pub target_unit: Option, + pub candidate_package_instance_id: Option, + pub candidate_path: Option, + pub fragment: Option, + pub candidates: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CallState { + Function, + Builtin, + Plugin, + Unresolved, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CallTargetKind { + Function, + Builtin, + Plugin, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CallReason { + Dynamic, + Unbound, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CallTargetOwner { + pub kind: String, + pub package: String, + pub digest: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisCall { + pub function: String, + pub span: Span, + pub callee: Value, + pub state: CallState, + pub target: Option, + pub target_kind: Option, + pub target_owner: Option, + pub reason: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ResourceKind { + Formula, + Code, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisResource { + pub id: String, + pub module_id: String, + pub unit_id: String, + pub kind: ResourceKind, + pub span: Span, + pub content_digest: String, + pub language: Option, + pub display: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct AnalysisModule { pub id: String, pub package_instance_id: String, pub relative_path: String, pub source_digest: String, - pub units: Vec, + pub source: String, + pub document: Value, + pub units: Vec, + pub anchors: Vec, pub functions: Vec, - #[serde(default)] - pub imports: Vec, - #[serde(default)] - pub references: Vec, - #[serde(default)] - pub calls: Vec, - #[serde(default)] - pub resources: Vec, + pub imports: Vec, + pub references: Vec, + pub calls: Vec, + pub resources: Vec, +} + +impl AnalysisModule { + pub fn source_snapshot(&self, display_path: std::path::PathBuf) -> LintResult { + let snapshot = SourceSnapshot::new(display_path, self.source.as_bytes().to_vec())?; + if snapshot.digest_hex() != self.source_digest { + return Err(crate::error::LintError::Protocol(format!( + "模块 {} 的 source_digest 与 artifact source 不一致;{PROTOCOL_REGEN_HINT}", + self.id + ))); + } + Ok(snapshot) + } } #[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CoreDiagnostic { - pub module: Option, - pub relative_path: Option, +#[serde(deny_unknown_fields)] +pub struct AnalysisDiagnostic { + pub module: String, + pub relative_path: String, pub span: Option, pub line: Option, pub column: Option, @@ -60,77 +308,53 @@ pub struct CoreDiagnostic { pub struct ExecutionProjection { pub schema_version: u64, pub producer: Producer, - pub project: Value, + pub project: AnalysisProject, pub modules: Vec, - pub diagnostics: Vec, + pub diagnostics: Vec, pub raw: Value, } +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Wire { + #[serde(rename = "schema")] + _schema: String, + schema_version: u64, + producer: Producer, + project: AnalysisProject, + modules: Vec, + diagnostics: Vec, +} + impl ExecutionProjection { + pub fn from_bytes(bytes: &[u8]) -> Result { + let raw: Value = serde_json::from_slice(bytes) + .map_err(|error| format!("Analysis JSON 无效:{error};{PROTOCOL_REGEN_HINT}"))?; + Self::from_json(raw) + } + pub fn from_json(raw: Value) -> Result { if raw.get("schema").and_then(Value::as_str) != Some("marqdo.analysis") { - return Err("Analysis schema 不是 marqdo.analysis".into()); + return Err(format!( + "Analysis schema 必须是 marqdo.analysis;{PROTOCOL_REGEN_HINT}" + )); } - let schema_version = match raw.get("schema_version").and_then(Value::as_u64) { - Some(version @ (2 | 3)) => version, - version => { - return Err(format!( - "不支持的 Analysis schema_version {version:?},需要 2 或 3" - )) - } - }; - let profile = raw["producer"]["markdown_profile"].as_str(); - if profile != Some("marqdo.md.v1") { - return Err(format!("不支持的 Markdown Profile {profile:?}")); - } - #[derive(Deserialize)] - struct Wire { - producer: Producer, - project: Value, - modules: Vec, - #[serde(default)] - diagnostics: Vec, - } - let wire: Wire = serde_json::from_value(raw.clone()).map_err(|error| error.to_string())?; - if wire.project["root_id"].as_str().is_none_or(str::is_empty) { - return Err("Analysis project.root_id 必须是非空字符串".into()); - } - let mut modules = std::collections::HashSet::new(); - for module in &wire.modules { - if module.package_instance_id.is_empty() - || module.id != format!("{}::{}", module.package_instance_id, module.relative_path) - || !modules.insert(&module.id) - { - return Err(format!("Analysis 模块身份无效或重复:{}", module.id)); - } - if module.source_digest.len() != 64 - || !module - .source_digest - .bytes() - .all(|byte| byte.is_ascii_hexdigit()) - { - return Err(format!("模块 {} 的 source_digest 无效", module.id)); - } - let path = std::path::Path::new(&module.relative_path); - if module.relative_path.is_empty() - || module.relative_path.contains('\\') - || !path - .components() - .all(|component| matches!(component, std::path::Component::Normal(_))) - { - return Err(format!("模块 {} 的 relative_path 不安全", module.id)); - } - let mut functions = std::collections::HashSet::new(); - for function in &module.functions { - if function.id.is_empty() || !functions.insert(&function.id) { - return Err(format!("Analysis 函数身份无效或重复:{}", function.id)); - } - validate_body(&function.body, schema_version) - .map_err(|error| format!("{}:{error}", function.id))?; - } + let revision = raw.get("schema_version").and_then(Value::as_u64); + if revision != Some(3) { + let actual = revision + .map(|value| value.to_string()) + .unwrap_or_else(|| "缺失".into()); + return Err(format!( + "不支持的 Analysis schema_version {actual},只接受 revision 3;{PROTOCOL_REGEN_HINT}" + )); } + reject_retired_module_shape(&raw)?; + let wire: Wire = serde_json::from_value(raw.clone()).map_err(|error| { + format!("Analysis revision 3 字段不完整或类型错误:{error};{PROTOCOL_REGEN_HINT}") + })?; + validate_projection(&wire)?; Ok(Self { - schema_version, + schema_version: wire.schema_version, producer: wire.producer, project: wire.project, modules: wire.modules, @@ -138,6 +362,860 @@ impl ExecutionProjection { raw, }) } + + pub fn entry_module(&self) -> Option<&AnalysisModule> { + self.modules + .iter() + .find(|module| module.id == self.project.entry_module_id) + } + + pub fn root_package_instance_id(&self) -> Option<&str> { + self.entry_module() + .map(|module| module.package_instance_id.as_str()) + } +} + +/// rc.3 and rc.4 both serialize `schema_version: 3`; the current boundary is +/// identified by required fields, not by the revision number alone. Detect the +/// retired shape before serde can produce a generic "missing field" error. +fn reject_retired_module_shape(raw: &Value) -> Result<(), String> { + let modules = raw + .get("modules") + .and_then(Value::as_array) + .ok_or_else(|| format!("Analysis.modules 必须是数组;{PROTOCOL_REGEN_HINT}"))?; + for module in modules { + let object = module + .as_object() + .ok_or_else(|| format!("Analysis.modules 的每一项必须是对象;{PROTOCOL_REGEN_HINT}"))?; + for field in ["source", "document", "anchors"] { + if !object.contains_key(field) { + return Err(format!( + "检测到旧 revision 3 制品(模块缺少 {field});同 revision 的旧字段集合不再接受,{PROTOCOL_REGEN_HINT}" + )); + } + } + for field in ["source", "document", "anchors"] { + if object.get(field).is_none_or(Value::is_null) { + return Err(format!( + "模块字段 {field} 不得为 null;{PROTOCOL_REGEN_HINT}" + )); + } + } + } + Ok(()) +} + +fn validate_projection(wire: &Wire) -> Result<(), String> { + if wire.producer.name != "marqdo" { + return Err("Analysis producer.name 必须是 marqdo".into()); + } + if wire.producer.version.trim().is_empty() { + return Err("Analysis producer.version 不得为空".into()); + } + if wire.producer.markdown_profile != "marqdo.md.v1" { + return Err("Analysis producer.markdown_profile 必须是 marqdo.md.v1".into()); + } + validate_project(&wire.project)?; + if wire.modules.is_empty() { + return Err("Analysis.modules 不得为空".into()); + } + let mut ids = HashSet::new(); + let mut all_units: HashMap<&str, &AnalysisUnit> = HashMap::new(); + let mut all_functions: HashMap<&str, &AnalysisFunction> = HashMap::new(); + for module in &wire.modules { + if !ids.insert(module.id.as_str()) { + return Err(format!("Analysis 模块身份重复:{}", module.id)); + } + let (units, functions) = validate_module_base(module, &wire.project)?; + for (id, unit) in units { + if all_units.insert(id, unit).is_some() { + return Err(format!("Analysis unit.id 跨模块重复:{id}")); + } + } + for (id, function) in functions { + if all_functions.insert(id, function).is_some() { + return Err(format!("Analysis function.id 跨模块重复:{id}")); + } + } + } + for module in &wire.modules { + validate_module_relations(module, &wire.project, &ids, &all_units, &all_functions)?; + } + let entry_count = wire + .modules + .iter() + .filter(|module| module.id == wire.project.entry_module_id) + .count(); + if entry_count != 1 { + return Err(format!( + "project.entry_module_id 必须在 modules 中恰好出现一次,实际 {entry_count} 次" + )); + } + if wire + .diagnostics + .iter() + .any(|diagnostic| diagnostic.severity == "error") + { + return Err("成功 Analysis 不得包含 error 级诊断".into()); + } + Ok(()) +} + +fn validate_project(project: &AnalysisProject) -> Result<(), String> { + match project.identity_kind { + IdentityKind::Manifest => { + if !project.root_id.starts_with("root:") || project.root_id.len() <= 5 { + return Err( + "manifest 项目的 project.root_id 必须形如 root:@".into(), + ); + } + } + IdentityKind::WorkspaceSnapshot => { + if !is_sha256(&project.root_id) { + return Err( + "workspace_snapshot 项目的 project.root_id 必须是 sha256:<64 hex>".into(), + ); + } + } + } + if project.entry_module_id.trim().is_empty() { + return Err("project.entry_module_id 不得为空".into()); + } + validate_captured_digest(&project.lock_digest, "project.lock_digest")?; + validate_captured_digest(&project.manifest_digest, "project.manifest_digest")?; + if let Some(stdlib) = &project.stdlib { + if stdlib.version.trim().is_empty() || stdlib.instance_id.trim().is_empty() { + return Err("project.stdlib 的 version/instance_id 不得为空".into()); + } + if !is_sha256(&stdlib.digest) { + return Err("project.stdlib.digest 必须是 sha256:<64 hex>".into()); + } + } + let mut extension_keys = Vec::new(); + for extension in &project.extensions { + if !matches!(extension.kind.as_str(), "plugin" | "kernel" | "provider") { + return Err("project.extensions[].kind 必须是 plugin/kernel/provider".into()); + } + for (name, value) in [ + ("name", extension.name.as_str()), + ("version", extension.version.as_str()), + ("logical_owner", extension.logical_owner.as_str()), + ("source", extension.source.as_str()), + ("selected_target", extension.selected_target.as_str()), + ] { + if value.trim().is_empty() { + return Err(format!("project.extensions[].{name} 不得为空")); + } + } + if !is_sha256(&extension.manifest_digest) || !is_sha256(&extension.artifact_digest) { + return Err("project.extensions[].*_digest 必须是 sha256:<64 hex>".into()); + } + extension_keys.push(( + extension.kind.clone(), + extension.name.clone(), + extension.logical_owner.clone(), + extension.manifest_digest.clone(), + )); + } + if extension_keys.windows(2).any(|pair| pair[0] > pair[1]) { + return Err( + "project.extensions 必须按 (kind,name,logical_owner,manifest_digest) 排序".into(), + ); + } + Ok(()) +} + +fn validate_captured_digest(digest: &str, field: &str) -> Result<(), String> { + if digest.is_empty() || is_sha256(digest) { + Ok(()) + } else { + Err(format!("{field} 必须是空字符串或 sha256:<64 hex>")) + } +} + +type UnitMap<'a> = HashMap<&'a str, &'a AnalysisUnit>; +type FunctionMap<'a> = HashMap<&'a str, &'a AnalysisFunction>; + +fn validate_module_base<'a>( + module: &'a AnalysisModule, + project: &AnalysisProject, +) -> Result<(UnitMap<'a>, FunctionMap<'a>), String> { + if module.id != format!("{}::{}", module.package_instance_id, module.relative_path) { + return Err(format!( + "模块 id 必须等于 package_instance_id::relative_path:{}", + module.id + )); + } + validate_relative_path(&module.relative_path)?; + if !is_lower_hex_64(&module.source_digest) { + return Err(format!( + "模块 {} 的 source_digest 必须是 64 位小写十六进制", + module.id + )); + } + let actual = format!("{:x}", Sha256::digest(module.source.as_bytes())); + if actual != module.source_digest { + return Err(format!( + "模块 {} 的 sha256(source) 与 source_digest 不一致;{PROTOCOL_REGEN_HINT}", + module.id + )); + } + let source_len = module.source.len(); + validate_span_boundaries( + &serde_json::to_value(module).map_err(|error| error.to_string())?, + &module.source, + ) + .map_err(|error| format!("模块 {}:{error}", module.id))?; + validate_document(&module.document, source_len, &module.id)?; + let units = validate_units(module, source_len)?; + validate_anchors(&module.anchors, &units)?; + let functions = validate_functions(&module.functions, &units, source_len)?; + validate_imports(&module.imports, &module.id, source_len)?; + let _ = project; + Ok((units, functions)) +} + +fn validate_module_relations( + module: &AnalysisModule, + project: &AnalysisProject, + module_ids: &HashSet<&str>, + all_units: &HashMap<&str, &AnalysisUnit>, + all_functions: &HashMap<&str, &AnalysisFunction>, +) -> Result<(), String> { + let current_units = module + .units + .iter() + .map(|unit| (unit.id.as_str(), unit)) + .collect::>(); + let source_len = module.source.len(); + validate_references( + module, + ¤t_units, + all_units, + all_functions, + module_ids, + source_len, + )?; + validate_calls(&module.calls, all_functions, source_len)?; + validate_resources(module, ¤t_units, &module.document, source_len)?; + let _ = project; + Ok(()) +} + +fn validate_span_boundaries(value: &Value, source: &str) -> Result<(), String> { + validate_span_boundaries_at(value, source, "$") +} + +fn validate_span_boundaries_at(value: &Value, source: &str, path: &str) -> Result<(), String> { + match value { + Value::Object(fields) => { + for key in ["span", "heading_span", "condition_span", "key_span"] { + if let Some(span) = fields.get(key) { + if span.is_null() { + continue; + } + // rc.4 stdlib still emits some parameter spans relative to a + // different projection; parameter spans are presentation-only + // and are not used for rule alignment. + if key == "span" && path.contains(".signature.params") { + continue; + } + let span = span_from_value(span, key)?; + if span.start > source.len() + || span.end > source.len() + || !source.is_char_boundary(span.start) + || !source.is_char_boundary(span.end) + { + return Err(format!( + "{path}.{key} [{}, {}) 不在 UTF-8 字符边界或超出源码长度", + span.start, span.end + )); + } + } + } + for (key, child) in fields { + validate_span_boundaries_at(child, source, &format!("{path}.{key}"))?; + } + } + Value::Array(values) => { + for (index, child) in values.iter().enumerate() { + validate_span_boundaries_at(child, source, &format!("{path}[{index}]"))?; + } + } + _ => {} + } + Ok(()) +} + +fn validate_relative_path(path: &str) -> Result<(), String> { + if path.is_empty() + || path.starts_with('/') + || path.contains('\\') + || path.contains("//") + || path.as_bytes().get(1) == Some(&b':') + { + return Err(format!("模块 relative_path 不安全:{path:?}")); + } + for segment in path.split('/') { + if segment.is_empty() || segment == "." || segment == ".." { + return Err(format!("模块 relative_path 含空、. 或 .. 段:{path:?}")); + } + } + Ok(()) +} + +fn validate_units(module: &AnalysisModule, source_len: usize) -> Result, String> { + if module.units.is_empty() { + return Err(format!("模块 {} 缺少 units", module.id)); + } + let mut by_id = HashMap::new(); + for unit in &module.units { + if unit.id.is_empty() { + return Err("unit.id 不得为空".into()); + } + if by_id.insert(unit.id.as_str(), unit).is_some() { + return Err(format!("unit.id 重复:{}", unit.id)); + } + unit.span.validate(source_len)?; + if let Some(span) = unit.heading_span { + span.validate(source_len)?; + if !unit.span.contains(span) { + return Err(format!( + "unit {} 的 heading_span 不在完整 section span 内", + unit.id + )); + } + } + if unit.mode_source_unit_id.is_empty() { + return Err(format!("unit {} 缺少 mode_source_unit_id", unit.id)); + } + } + let roots: Vec<_> = module + .units + .iter() + .filter(|unit| unit.kind == UnitKind::Root) + .collect(); + if roots.len() != 1 { + return Err("每个模块必须恰好有一个 root unit".into()); + } + let root = roots[0]; + if root.parent_id.is_some() + || root.kind != UnitKind::Root + || root.level != 0 + || !root.path.is_empty() + || !root.name.is_empty() + || root.mode != HeadingMode::Knowledge + || root.mode_origin != ModeOrigin::Default + || root.heading_span.is_some() + || root.function.is_some() + { + return Err("root unit 的身份字段无效".into()); + } + if root.span.start != 0 || root.span.end != source_len { + return Err("root unit 的 span 必须覆盖整个 artifact source".into()); + } + let mut ancestors = HashSet::new(); + for unit in &module.units { + if unit.kind == UnitKind::Root { + continue; + } + let parent_id = unit + .parent_id + .as_deref() + .ok_or_else(|| format!("非 root unit {} 缺少 parent_id", unit.id))?; + let parent = *by_id + .get(parent_id) + .ok_or_else(|| format!("unit {} 的 parent_id 不存在", unit.id))?; + if unit.path.len() != parent.path.len() + 1 + || unit + .path + .iter() + .zip(&parent.path) + .any(|(left, right)| left != right) + || unit.path.last() != Some(&unit.name) + { + return Err(format!("unit {} 的 path/name 与 parent 不一致", unit.id)); + } + if !parent.span.contains(unit.span) { + return Err(format!("unit {} 的 span 未嵌套在 parent span 内", unit.id)); + } + match unit.kind { + UnitKind::Function if unit.mode != HeadingMode::Exec => { + return Err(format!( + "Exec function unit {} 的 mode 必须是 exec", + unit.id + )); + } + UnitKind::Knowledge if unit.mode != HeadingMode::Knowledge => { + return Err(format!( + "Knowledge unit {} 的 mode 必须是 knowledge", + unit.id + )); + } + UnitKind::Namespace | UnitKind::Section | UnitKind::Root => {} + _ => {} + } + if unit.kind == UnitKind::Function { + if unit.level != 2 { + return Err(format!("Exec function unit {} 必须是 H2", unit.id)); + } + if unit.function.as_deref().is_none_or(str::is_empty) { + return Err(format!("function unit {} 必须指向可调用函数", unit.id)); + } + } else if unit.kind == UnitKind::Knowledge { + if unit.level != 2 || unit.function.is_some() { + return Err(format!("Knowledge unit {} 身份无效", unit.id)); + } + } else if unit.kind == UnitKind::Namespace { + if unit.level != 1 || unit.function.is_some() { + return Err(format!("namespace unit {} 身份无效", unit.id)); + } + } else if unit.kind == UnitKind::Section && unit.level < 3 { + return Err(format!("section unit {} 必须是 H3+", unit.id)); + } + let mode_source = *by_id + .get(unit.mode_source_unit_id.as_str()) + .ok_or_else(|| format!("unit {} 的 mode_source_unit_id 不存在", unit.id))?; + let mut cursor = Some(unit); + let mut found = false; + while let Some(current) = cursor { + if current.id == mode_source.id { + found = true; + break; + } + cursor = current + .parent_id + .as_deref() + .and_then(|id| by_id.get(id).copied()); + } + if !found { + return Err(format!( + "unit {} 的 mode_source_unit_id 不是自身或祖先", + unit.id + )); + } + ancestors.insert(unit.id.as_str()); + } + for unit in &module.units { + let mut seen = HashSet::new(); + let mut cursor = Some(unit); + while let Some(current) = cursor { + if !seen.insert(current.id.as_str()) { + return Err(format!("unit {} 的 parent 链存在循环", unit.id)); + } + cursor = current + .parent_id + .as_deref() + .and_then(|id| by_id.get(id).copied()); + } + } + Ok(by_id) +} + +fn validate_anchors( + anchors: &[AnalysisAnchor], + units: &HashMap<&str, &AnalysisUnit>, +) -> Result<(), String> { + let mut seen = HashSet::new(); + let mut previous: Option<&str> = None; + for anchor in anchors { + if anchor.anchor.trim().is_empty() || !seen.insert(anchor.anchor.as_str()) { + return Err("anchor 不得为空或重复".into()); + } + if !units.contains_key(anchor.unit_id.as_str()) { + return Err(format!("anchor {} 指向不存在的 unit", anchor.anchor)); + } + if previous.is_some_and(|previous| previous > anchor.anchor.as_str()) { + return Err("anchors 必须按 anchor 排序".into()); + } + previous = Some(anchor.anchor.as_str()); + } + Ok(()) +} + +fn validate_functions<'a>( + functions: &'a [AnalysisFunction], + units: &HashMap<&str, &AnalysisUnit>, + source_len: usize, +) -> Result, String> { + let mut by_id = HashMap::new(); + for function in functions { + if function.id.trim().is_empty() || by_id.insert(function.id.as_str(), function).is_some() { + return Err(format!("function.id 不得为空或重复:{}", function.id)); + } + let unit = *units + .get(function.unit_id.as_str()) + .ok_or_else(|| format!("function {} 的 unit_id 不存在", function.id))?; + if unit.kind != UnitKind::Function || unit.function.as_deref() != Some(function.id.as_str()) + { + return Err(format!("function {} 未对应 Exec H2 unit", function.id)); + } + if unit.heading_span != Some(function.heading_span) { + return Err(format!( + "function {} 的 heading_span 与 unit 不一致", + function.id + )); + } + if !unit.span.contains(function.span) { + return Err(format!("function {} 的 span 不在 unit 内", function.id)); + } + function.span.validate(source_len)?; + function.heading_span.validate(source_len)?; + if function.local_name.trim().is_empty() { + return Err(format!("function {} 缺少 local_name", function.id)); + } + if function.effects.iter().any(|effect| effect != "unknown") { + return Err(format!( + "function {} 的 effects 只允许 unknown", + function.id + )); + } + for param in &function.signature.params { + if param.name.trim().is_empty() { + return Err(format!("function {} 的 param.name 不得为空", function.id)); + } + param.span.validate(source_len)?; + if let Some(default) = ¶m.default { + validate_expression(default, source_len)?; + } + } + validate_body(&function.body, source_len)?; + } + for unit in units + .values() + .filter(|unit| unit.kind == UnitKind::Function) + { + if !by_id.contains_key(unit.function.as_deref().unwrap_or_default()) { + return Err(format!("Exec unit {} 缺少对应 function", unit.id)); + } + } + Ok(by_id) +} + +fn validate_imports( + imports: &[AnalysisImport], + module_id: &str, + source_len: usize, +) -> Result<(), String> { + for import in imports { + if import.alias.trim().is_empty() || import.target.trim().is_empty() { + return Err(format!("模块 {module_id} 存在空 import alias/target")); + } + import.span.validate(source_len)?; + } + Ok(()) +} + +fn validate_references( + module: &AnalysisModule, + current_units: &HashMap<&str, &AnalysisUnit>, + all_units: &HashMap<&str, &AnalysisUnit>, + all_functions: &HashMap<&str, &AnalysisFunction>, + module_ids: &HashSet<&str>, + source_len: usize, +) -> Result<(), String> { + for reference in &module.references { + if reference.source != module.id { + return Err(format!("reference.source 必须是当前模块 {}", module.id)); + } + let source_unit = *current_units + .get(reference.source_unit.as_str()) + .ok_or_else(|| format!("reference.source_unit 不存在:{}", reference.source_unit))?; + reference.span.validate(source_len)?; + let innermost = innermost_unit(module, reference.span, current_units); + if innermost.is_none_or(|unit| unit.id != source_unit.id) { + return Err(format!( + "reference.source_unit 不是包含 span 的最内层 unit:{}", + reference.source_unit + )); + } + match reference.state { + ReferenceState::Resolved => { + let kind = reference.target_kind.ok_or_else(|| { + format!("resolved reference {} 缺少 target_kind", reference.url) + })?; + match kind { + ReferenceTargetKind::Module => { + let target = reference.target_module.as_deref().ok_or_else(|| { + format!( + "resolved module reference {} 缺少 target_module", + reference.url + ) + })?; + if !module_ids.contains(target) { + return Err(format!( + "resolved reference 的 target_module 不在 modules 集:{target}" + )); + } + } + ReferenceTargetKind::File => {} + } + if let Some(target_unit) = &reference.target_unit { + if !all_units.contains_key(target_unit.as_str()) { + return Err(format!("reference target_unit 不存在:{target_unit}")); + } + } + } + ReferenceState::NotLoaded => { + if reference.target_unit.is_some() { + return Err("not_loaded reference 的 target_unit 必须为 null".into()); + } + if reference.target_kind.is_some() { + return Err("not_loaded reference 的 target_kind 必须为 null".into()); + } + } + ReferenceState::Missing => { + if reference.target_unit.is_some() { + return Err("missing reference 的 target_unit 必须为 null".into()); + } + } + ReferenceState::Ambiguous => { + if reference.target_unit.is_some() + || reference.target_kind.is_some() + || reference.candidates.len() < 2 + { + return Err( + "ambiguous reference 必须列出至少两个 candidates 且 target_unit/target_kind 为 null" + .into(), + ); + } + } + ReferenceState::External => { + if reference.target_kind.is_some() + || reference.target_module.is_some() + || reference.target_unit.is_some() + { + return Err("external reference 的目标字段必须为 null".into()); + } + } + ReferenceState::OutsideScope | ReferenceState::Invalid => { + if reference.target_unit.is_some() { + return Err("outside_scope/invalid reference 的 target_unit 必须为 null".into()); + } + } + } + if reference.state != ReferenceState::Ambiguous && !reference.candidates.is_empty() { + return Err(format!( + "只有 ambiguous reference 才能携带 candidates:{}", + reference.url + )); + } + if let Some(function_id) = source_unit.function.as_deref() { + if !all_functions.contains_key(function_id) { + return Err(format!("reference 所属 function 不存在:{function_id}")); + } + } + } + Ok(()) +} + +fn innermost_unit<'a>( + _module: &'a AnalysisModule, + span: Span, + units: &HashMap<&'a str, &'a AnalysisUnit>, +) -> Option<&'a AnalysisUnit> { + units + .values() + .copied() + .filter(|unit| unit.span.contains(span)) + .max_by_key(|unit| (unit.path.len(), usize::MAX - unit.span.start)) +} + +fn validate_calls( + calls: &[AnalysisCall], + functions: &HashMap<&str, &AnalysisFunction>, + source_len: usize, +) -> Result<(), String> { + for call in calls { + if !functions.contains_key(call.function.as_str()) { + return Err(format!("call.function 不存在:{}", call.function)); + } + call.span.validate(source_len)?; + validate_callee(&call.callee)?; + match call.state { + CallState::Function => { + if call.target_kind != Some(CallTargetKind::Function) + || call.target.is_none() + || call.target_owner.is_some() + { + return Err("function call 的 target/target_kind/target_owner 不一致".into()); + } + if !functions.contains_key(call.target.as_deref().unwrap_or_default()) { + return Err(format!( + "resolved function call 指向不存在的函数:{:?}", + call.target + )); + } + if call.reason.is_some() { + return Err("已绑定 function call 的 reason 必须为 null".into()); + } + } + CallState::Builtin => { + if call.target_kind != Some(CallTargetKind::Builtin) + || call.target.as_deref().is_none_or(str::is_empty) + { + return Err("builtin call 的 target/target_kind 不一致".into()); + } + if call.reason.is_some() || call.target_owner.is_some() { + return Err("builtin call 不得携带 reason/target_owner".into()); + } + } + CallState::Plugin => { + if call.target_kind != Some(CallTargetKind::Plugin) + || call.target.as_deref().is_none_or(str::is_empty) + { + return Err("plugin call 的 target/target_kind 不一致".into()); + } + let owner = call + .target_owner + .as_ref() + .ok_or_else(|| "plugin call 缺少 target_owner".to_string())?; + if owner.kind != "plugin" + || owner.package.trim().is_empty() + || !is_sha256(&owner.digest) + { + return Err("plugin call 的 target_owner 无效".into()); + } + if call.reason.is_some() { + return Err("plugin call 的 reason 必须为 null".into()); + } + } + CallState::Unresolved => { + if call.target.is_some() || call.target_kind.is_some() { + return Err("unresolved call 的 target/target_kind 必须为 null".into()); + } + if call.reason.is_none() { + return Err("unresolved call 必须说明 dynamic/unbound reason".into()); + } + } + } + } + Ok(()) +} + +fn validate_callee(callee: &Value) -> Result<(), String> { + let object = as_object(callee, "call.callee")?; + match object.get("kind").and_then(Value::as_str) { + Some("ident") => { + check_keys(object, &["kind", "name"], "call.callee.ident")?; + require_str(object, "name", "call.callee.ident")?; + } + Some("member") => { + check_keys(object, &["kind", "base", "field"], "call.callee.member")?; + let base = object + .get("base") + .ok_or_else(|| "call.callee.member 缺少 base".to_string())?; + validate_callee(base)?; + require_str(object, "field", "call.callee.member")?; + } + Some("expression") => { + check_keys(object, &["kind", "span"], "call.callee.expression")?; + let span = object + .get("span") + .ok_or_else(|| "call.callee.expression 缺少 span".to_string())?; + span_from_value(span, "call.callee.expression.span")?; + } + _ => return Err("call.callee.kind 无效".into()), + } + Ok(()) +} + +fn validate_resources( + module: &AnalysisModule, + units: &HashMap<&str, &AnalysisUnit>, + document: &Value, + source_len: usize, +) -> Result<(), String> { + let mut payloads = HashMap::new(); + collect_resource_payloads(document, &mut payloads)?; + let mut ids = HashSet::new(); + for resource in &module.resources { + if !ids.insert(resource.id.as_str()) { + return Err(format!("resource.id 重复:{}", resource.id)); + } + if !resource.id.starts_with(&format!("{}#resource:", module.id)) { + return Err(format!("resource.id 不属于当前模块:{}", resource.id)); + } + if resource.module_id != module.id { + return Err(format!("resource.module_id 与模块不一致:{}", resource.id)); + } + if !units.contains_key(resource.unit_id.as_str()) { + return Err(format!("resource.unit_id 不存在:{}", resource.unit_id)); + } + resource.span.validate(source_len)?; + let unit = units[resource.unit_id.as_str()]; + if !unit.span.contains(resource.span) { + return Err(format!("resource {} 的 span 不在 unit 内", resource.id)); + } + if !is_lower_hex_64(&resource.content_digest) { + return Err(format!( + "resource {} 的 content_digest 必须是 64 位小写十六进制", + resource.id + )); + } + let payload = payloads.get(&resource.span).ok_or_else(|| { + format!( + "resource {} 的 span 未对应可验证的 AST literal", + resource.id + ) + })?; + let expected = format!("{:x}", Sha256::digest(payload.as_bytes())); + if expected != resource.content_digest { + return Err(format!( + "resource {} 的 content_digest 与 AST literal 不一致", + resource.id + )); + } + match resource.kind { + ResourceKind::Formula => { + if resource.display.is_none() || resource.language.is_some() { + return Err(format!( + "formula resource {} 必须 display 为 bool 且 language 为 null", + resource.id + )); + } + } + ResourceKind::Code => { + if resource.display.is_some() { + return Err(format!( + "code resource {} 的 display 必须为 null", + resource.id + )); + } + } + } + } + Ok(()) +} + +fn collect_resource_payloads( + node: &Value, + payloads: &mut HashMap, +) -> Result<(), String> { + let object = as_object(node, "document node")?; + let kind = object + .get("kind") + .and_then(Value::as_str) + .ok_or_else(|| "document node 缺少 kind".to_string())?; + let span = span_from_value( + object + .get("span") + .ok_or_else(|| "document node 缺少 span".to_string())?, + "document node.span", + )?; + if matches!(kind, "math" | "math_block" | "code_block") { + if let Some(literal) = object.get("literal").and_then(Value::as_str) { + payloads.insert(span, literal.to_string()); + } + } + let children = object + .get("children") + .and_then(Value::as_array) + .ok_or_else(|| "document node 的 children 必须是数组".to_string())?; + for child in children { + collect_resource_payloads(child, payloads)?; + } + Ok(()) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -160,7 +1238,8 @@ pub(crate) struct Statement<'a> { impl<'a> Statement<'a> { pub fn read(value: &'a Value) -> Result { - let kind = match value["kind"].as_str() { + let object = as_object(value, "statement")?; + let kind = match object.get("kind").and_then(Value::as_str) { Some("assign") => StatementKind::Assign, Some("expression") => StatementKind::Expression, Some("branch") => StatementKind::Branch, @@ -201,50 +1280,580 @@ pub fn node_span(node: &Value) -> Option { span_value(&node["span"]) } -fn validate_body(nodes: &[Value], version: u64) -> Result<(), String> { +fn validate_body(nodes: &[Value], source_len: usize) -> Result<(), String> { for node in nodes { - let statement = Statement::read(node)?; - match statement.kind { - StatementKind::Break | StatementKind::Continue if version == 2 => { - return Err(format!("Analysis v2 不支持 {:?}", statement.kind)); - } - StatementKind::Loop => { - if body(node).is_none() { - return Err("loop 的 body 必须是数组".into()); - } - validate_condition_span(node)?; - } - StatementKind::Branch => { - let arms = node["arms"] - .as_array() - .filter(|arms| !arms.is_empty()) - .ok_or("branch 的 arms 必须是非空数组")?; - for arm in arms { - if node_span(arm).is_none() || body(arm).is_none() { - return Err("分支臂必须包含有效的 span 和 body 数组".into()); - } - validate_condition_span(arm)?; - } - } - _ => {} + validate_statement(node, source_len)?; + } + Ok(()) +} + +fn validate_statement(node: &Value, source_len: usize) -> Result<(), String> { + let statement = Statement::read(node)?; + statement.span.validate(source_len)?; + let object = as_object(node, "statement")?; + match statement.kind { + StatementKind::Assign => { + check_keys(object, &["kind", "target", "value", "span"], "assign")?; + validate_place( + object + .get("target") + .ok_or_else(|| "assign 缺少 target".to_string())?, + source_len, + )?; + validate_expression( + object + .get("value") + .ok_or_else(|| "assign 缺少 value".to_string())?, + source_len, + )?; } - for children in statement.child_bodies() { - validate_body(children, version)?; + StatementKind::Expression | StatementKind::Return => { + check_keys(object, &["kind", "value", "span"], "expression/return")?; + validate_expression( + object + .get("value") + .ok_or_else(|| "语句缺少 value".to_string())?, + source_len, + )?; + } + StatementKind::Branch => { + check_keys(object, &["kind", "arms", "span"], "branch")?; + let arms = object + .get("arms") + .and_then(Value::as_array) + .filter(|arms| !arms.is_empty()) + .ok_or_else(|| "branch 的 arms 必须是非空数组".to_string())?; + for arm in arms { + let arm = as_object(arm, "branch arm")?; + check_keys( + arm, + &["condition", "condition_span", "body", "span"], + "branch arm", + )?; + span_from_value( + arm.get("span") + .ok_or_else(|| "branch arm 缺少 span".to_string())?, + "branch arm.span", + )? + .validate(source_len)?; + span_from_value( + arm.get("condition_span") + .ok_or_else(|| "branch arm 缺少 condition_span".to_string())?, + "branch arm.condition_span", + )? + .validate(source_len)?; + validate_expression( + arm.get("condition") + .ok_or_else(|| "branch arm 缺少 condition".to_string())?, + source_len, + )?; + let body = arm + .get("body") + .and_then(Value::as_array) + .ok_or_else(|| "branch arm 的 body 必须是数组".to_string())?; + validate_body(body, source_len)?; + } + } + StatementKind::Loop => { + check_keys( + object, + &["kind", "condition", "condition_span", "body", "span"], + "loop", + )?; + span_from_value( + object + .get("condition_span") + .ok_or_else(|| "loop 缺少 condition_span".to_string())?, + "loop.condition_span", + )? + .validate(source_len)?; + validate_expression( + object + .get("condition") + .ok_or_else(|| "loop 缺少 condition".to_string())?, + source_len, + )?; + let body = object + .get("body") + .and_then(Value::as_array) + .ok_or_else(|| "loop 的 body 必须是数组".to_string())?; + validate_body(body, source_len)?; + } + StatementKind::Break | StatementKind::Continue => { + check_keys(object, &["kind", "span"], "jump")?; } } Ok(()) } -fn validate_condition_span(value: &Value) -> Result<(), String> { - if value - .get("condition_span") - .is_some_and(|span| span_value(span).is_none()) - { - return Err("Analysis condition_span 无效".into()); +fn validate_place(value: &Value, source_len: usize) -> Result<(), String> { + if value.is_string() { + return Ok(()); + } + let object = as_object(value, "assign.target")?; + check_keys( + object, + &["kind", "base", "index", "span"], + "assign.target.index", + )?; + if object.get("kind").and_then(Value::as_str) != Some("index") { + return Err("assign.target.kind 必须是 index".into()); + } + span_from_value( + object + .get("span") + .ok_or_else(|| "assign.target 缺少 span".to_string())?, + "assign.target.span", + )? + .validate(source_len)?; + validate_expression( + object + .get("base") + .ok_or_else(|| "assign.target 缺少 base".to_string())?, + source_len, + )?; + validate_expression( + object + .get("index") + .ok_or_else(|| "assign.target 缺少 index".to_string())?, + source_len, + ) +} + +fn validate_expression(value: &Value, source_len: usize) -> Result<(), String> { + let object = as_object(value, "expression")?; + let kind = object + .get("kind") + .and_then(Value::as_str) + .ok_or_else(|| "expression 缺少 kind".to_string())?; + let span = span_from_value( + object + .get("span") + .ok_or_else(|| "expression 缺少 span".to_string())?, + "expression.span", + )?; + span.validate(source_len)?; + match kind { + "literal" => { + check_keys(object, &["kind", "type", "value", "span"], "literal")?; + let literal_type = object + .get("type") + .and_then(Value::as_str) + .ok_or_else(|| "literal 缺少 type".to_string())?; + match literal_type { + "int" => { + let text = object + .get("value") + .and_then(Value::as_str) + .ok_or_else(|| "int literal 的 value 必须是字符串".to_string())?; + if text.is_empty() + || !text + .trim_start_matches('-') + .bytes() + .all(|byte| byte.is_ascii_digit()) + { + return Err("int literal 的 value 不是十进制整数".into()); + } + } + "float" => { + if !object.get("value").is_some_and(Value::is_number) { + return Err("float literal 的 value 必须是有限 JSON number".into()); + } + } + "text" => { + object + .get("value") + .and_then(Value::as_str) + .ok_or_else(|| "text literal 的 value 必须是字符串".to_string())?; + } + "bool" => { + object + .get("value") + .and_then(Value::as_bool) + .ok_or_else(|| "bool literal 的 value 必须是布尔值".to_string())?; + } + "none" => { + if object.contains_key("value") { + return Err("none literal 不得携带 value".into()); + } + } + _ => return Err("literal.type 无效".into()), + } + } + "variable" => { + check_keys(object, &["kind", "name", "span"], "variable")?; + require_str(object, "name", "variable")?; + } + "list" => { + check_keys(object, &["kind", "items", "span"], "list expression")?; + for item in object + .get("items") + .and_then(Value::as_array) + .ok_or_else(|| "list expression 缺少 items 数组".to_string())? + { + validate_expression(item, source_len)?; + } + } + "record" => { + check_keys(object, &["kind", "entries", "span"], "record expression")?; + for entry in object + .get("entries") + .and_then(Value::as_array) + .ok_or_else(|| "record expression 缺少 entries 数组".to_string())? + { + let entry = as_object(entry, "record entry")?; + check_keys(entry, &["key", "key_span", "value"], "record entry")?; + require_str(entry, "key", "record entry")?; + span_from_value( + entry + .get("key_span") + .ok_or_else(|| "record entry 缺少 key_span".to_string())?, + "record entry.key_span", + )? + .validate(source_len)?; + validate_expression( + entry + .get("value") + .ok_or_else(|| "record entry 缺少 value".to_string())?, + source_len, + )?; + } + } + "unary" => { + check_keys(object, &["kind", "op", "operand", "span"], "unary")?; + if !matches!( + object.get("op").and_then(Value::as_str), + Some("not" | "neg" | "pos") + ) { + return Err("unary.op 无效".into()); + } + validate_expression( + object + .get("operand") + .ok_or_else(|| "unary 缺少 operand".to_string())?, + source_len, + )?; + } + "binary" => { + check_keys(object, &["kind", "op", "left", "right", "span"], "binary")?; + if !matches!( + object.get("op").and_then(Value::as_str), + Some( + "or" | "and" + | "eq" + | "ne" + | "lt" + | "le" + | "gt" + | "ge" + | "add" + | "sub" + | "mul" + | "div" + | "floor_div" + | "mod" + | "pow" + ) + ) { + return Err("binary.op 无效".into()); + } + validate_expression( + object + .get("left") + .ok_or_else(|| "binary 缺少 left".to_string())?, + source_len, + )?; + validate_expression( + object + .get("right") + .ok_or_else(|| "binary 缺少 right".to_string())?, + source_len, + )?; + } + "member" => { + check_keys(object, &["kind", "base", "field", "span"], "member")?; + validate_expression( + object + .get("base") + .ok_or_else(|| "member 缺少 base".to_string())?, + source_len, + )?; + require_str(object, "field", "member")?; + } + "index" => { + check_keys(object, &["kind", "base", "index", "span"], "index")?; + validate_expression( + object + .get("base") + .ok_or_else(|| "index 缺少 base".to_string())?, + source_len, + )?; + validate_expression( + object + .get("index") + .ok_or_else(|| "index 缺少 index".to_string())?, + source_len, + )?; + } + "call" => { + check_keys( + object, + &["kind", "callee", "args", "span"], + "call expression", + )?; + let callee = object + .get("callee") + .and_then(Value::as_object) + .ok_or_else(|| "call expression 缺少 callee 对象".to_string())?; + match callee.get("kind").and_then(Value::as_str) { + Some("variable") => { + check_keys(callee, &["kind", "name", "span"], "call callee")?; + require_str(callee, "name", "call callee")?; + } + Some("member") => { + check_keys(callee, &["kind", "base", "field", "span"], "call callee")?; + validate_expression( + callee + .get("base") + .ok_or_else(|| "call callee 缺少 base".to_string())?, + source_len, + )?; + require_str(callee, "field", "call callee")?; + } + _ => return Err("call expression 的 callee 形状无效".into()), + } + for arg in object + .get("args") + .and_then(Value::as_array) + .ok_or_else(|| "call expression 缺少 args 数组".to_string())? + { + let arg = as_object(arg, "call arg")?; + check_keys(arg, &["name", "value", "span"], "call arg")?; + if let Some(name) = arg.get("name") { + if !name.is_null() && name.as_str().is_none_or(str::is_empty) { + return Err("call arg.name 必须是非空字符串或 null".into()); + } + } + span_from_value( + arg.get("span") + .ok_or_else(|| "call arg 缺少 span".to_string())?, + "call arg.span", + )? + .validate(source_len)?; + validate_expression( + arg.get("value") + .ok_or_else(|| "call arg 缺少 value".to_string())?, + source_len, + )?; + } + } + _ => return Err(format!("未知 expression.kind {kind:?}")), } Ok(()) } +fn validate_document(node: &Value, source_len: usize, module_id: &str) -> Result<(), String> { + let object = as_object(node, "document")?; + if object.get("kind").and_then(Value::as_str) != Some("document") { + return Err(format!("模块 {module_id} 的 document 根节点不是 document")); + } + validate_document_node(node, source_len) +} + +fn validate_document_node(node: &Value, source_len: usize) -> Result<(), String> { + let object = as_object(node, "document node")?; + let kind = object + .get("kind") + .and_then(Value::as_str) + .ok_or_else(|| "document node 缺少 kind".to_string())?; + let span = span_from_value( + object + .get("span") + .ok_or_else(|| "document node 缺少 span".to_string())?, + "document node.span", + )?; + span.validate(source_len)?; + let children = object + .get("children") + .and_then(Value::as_array) + .ok_or_else(|| "document node 的 children 必须是数组".to_string())?; + let children_allowed = !matches!( + kind, + "text" + | "front_matter" + | "code" + | "code_block" + | "math" + | "math_block" + | "html_block" + | "html_inline" + | "thematic_break" + | "soft_break" + | "line_break" + ); + if !children_allowed && !children.is_empty() { + return Err(format!("{kind} 节点不得有 children")); + } + let allowed: &[&str] = match kind { + "document" | "block_quote" | "paragraph" | "strong" | "emph" | "strikethrough" + | "table_cell" | "thematic_break" | "soft_break" | "line_break" => { + &["kind", "span", "children"] + } + "front_matter" | "text" | "math_block" | "html_block" | "html_inline" => { + &["kind", "span", "children", "literal"] + } + "list" => &["kind", "span", "children", "ordered", "start", "tight"], + "item" => &["kind", "span", "children", "task"], + "heading" => &["kind", "span", "children", "level", "setext"], + "code" => &["kind", "span", "children", "literal", "ticks"], + "code_block" => &["kind", "span", "children", "literal", "fenced", "info"], + "math" => &["kind", "span", "children", "literal", "display"], + "link" | "image" => &["kind", "span", "children", "url", "title"], + "table" => &["kind", "span", "children", "alignments"], + "table_row" => &["kind", "span", "children", "header"], + "other" => &["kind", "span", "children", "tag", "literal"], + _ => return Err(format!("document node.kind 无效:{kind}")), + }; + check_keys(object, allowed, "document node")?; + match kind { + "text" | "front_matter" | "math_block" | "html_block" | "html_inline" => { + require_str(object, "literal", "document node")?; + } + "code" => { + require_str(object, "literal", "document node")?; + if object.get("ticks").and_then(Value::as_u64).is_none() { + return Err("code 节点缺少 ticks".into()); + } + } + "code_block" => { + require_str(object, "literal", "document node")?; + if object.get("fenced").and_then(Value::as_bool).is_none() { + return Err("code_block 节点缺少 fenced".into()); + } + if !object.get("info").is_some_and(Value::is_string) { + return Err("code_block 节点缺少 info".into()); + } + } + "math" => { + require_str(object, "literal", "document node")?; + if object.get("display").and_then(Value::as_bool).is_none() { + return Err("math 节点缺少 display".into()); + } + } + "heading" => { + if !object + .get("level") + .and_then(Value::as_u64) + .is_some_and(|level| (1..=6).contains(&level)) + { + return Err("heading 节点 level 无效".into()); + } + if object.get("setext").and_then(Value::as_bool).is_none() { + return Err("heading 节点缺少 setext".into()); + } + } + "list" => { + if object.get("ordered").and_then(Value::as_bool).is_none() + || !object.contains_key("start") + || object.get("tight").and_then(Value::as_bool).is_none() + { + return Err("list 节点必须包含 ordered/start/tight".into()); + } + } + "item" => { + if !object.contains_key("task") { + return Err("item 节点缺少 task".into()); + } + } + "link" | "image" => { + require_str(object, "url", "document node")?; + if !object.get("title").is_some_and(Value::is_string) { + return Err(format!("{kind} 节点缺少 title")); + } + } + "table" => { + if !object + .get("alignments") + .and_then(Value::as_array) + .is_some_and(|values| { + values.iter().all(|value| { + matches!(value.as_str(), Some("none" | "left" | "center" | "right")) + }) + }) + { + return Err("table 节点 alignments 无效".into()); + } + } + "table_row" => { + if object.get("header").and_then(Value::as_bool).is_none() { + return Err("table_row 节点缺少 header".into()); + } + } + "other" => { + require_str(object, "tag", "document node")?; + } + _ => {} + } + for child in children { + validate_document_node(child, source_len)?; + } + Ok(()) +} + +fn as_object<'a>(value: &'a Value, context: &str) -> Result<&'a Map, String> { + value + .as_object() + .ok_or_else(|| format!("{context} 必须是对象")) +} + +fn check_keys(object: &Map, allowed: &[&str], context: &str) -> Result<(), String> { + for key in object.keys() { + if !allowed.contains(&key.as_str()) { + return Err(format!("{context} 含未定义字段 {key}")); + } + } + Ok(()) +} + +fn require_str(object: &Map, field: &str, context: &str) -> Result { + object + .get(field) + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .map(ToString::to_string) + .ok_or_else(|| format!("{context} 缺少非空字符串 {field}")) +} + +fn span_from_value(value: &Value, context: &str) -> Result { + let object = as_object(value, context)?; + check_keys(object, &["start", "end"], context)?; + let start = object + .get("start") + .and_then(Value::as_u64) + .ok_or_else(|| format!("{context} 缺少 start"))?; + let end = object + .get("end") + .and_then(Value::as_u64) + .ok_or_else(|| format!("{context} 缺少 end"))?; + let start = usize::try_from(start).map_err(|_| format!("{context}.start 过大"))?; + let end = usize::try_from(end).map_err(|_| format!("{context}.end 过大"))?; + if start > end { + return Err(format!("{context} 是负区间")); + } + Ok(Span::new(start, end)) +} + +fn is_sha256(value: &str) -> bool { + value.strip_prefix("sha256:").is_some_and(is_lower_hex_64) +} + +fn is_lower_hex_64(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + pub(crate) fn statements(nodes: &[Value]) -> impl Iterator> { nodes .iter() @@ -292,29 +1901,29 @@ fn validate_source_condition_span(node: &Value, source: &SourceSnapshot) -> Lint /// Spans with external effects known from public bound targets or indexed writes. pub(crate) fn effect_sites<'a>( function: &'a AnalysisFunction, - calls: &'a [Value], + calls: &'a [AnalysisCall], ) -> impl Iterator + 'a { let writes = statements(&function.body).filter(|statement| { statement.kind == StatementKind::Assign && statement.value["target"]["kind"] == "index" }); let external = calls.iter().filter(|call| { - call["function"] == function.id.as_str() - && match call["state"].as_str() { - Some("plugin") => true, - Some("builtin") => call["target"].as_str().is_some_and(|target| { + call.function == function.id + && match call.state { + CallState::Plugin => true, + CallState::Builtin => call.target.as_deref().is_some_and(|target| { target.starts_with("resource.") || matches!(target, "foreign.call" | "foreign.run") }), - Some("function") => call["target"].as_str().is_some_and(|target| { + CallState::Function => call.target.as_deref().is_some_and(|target| { target.starts_with("std:marqdo-stdlib@") && (target.contains("::io.mq.md::io.") || target.contains("::io/stream.mq.md::stream.") || target.contains("::io/console.mq.md::console.")) }), - _ => false, + CallState::Unresolved => false, } }); writes .map(|statement| statement.span) - .chain(external.filter_map(node_span)) + .chain(external.map(|call| call.span)) } diff --git a/src/model/markdown.rs b/src/model/markdown.rs index 5a92907..a5dd817 100644 --- a/src/model/markdown.rs +++ b/src/model/markdown.rs @@ -1,18 +1,14 @@ +use std::collections::HashMap; + use serde::Deserialize; use serde_json::Value; use crate::error::{LintError, Result}; -use super::{SourceSnapshot, Span}; +use super::{AnalysisFunction, AnalysisUnit, HeadingMode, SourceSnapshot, Span, UnitKind}; pub type NodeId = usize; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum HeadingMode { - Knowledge, - Exec, -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CarrierKind { Code, @@ -39,6 +35,7 @@ pub struct MarkdownNode { #[derive(Debug, Clone)] pub struct HeadingSegment { pub node: NodeId, + pub unit_id: String, pub level: u8, pub mode: HeadingMode, pub name: String, @@ -74,6 +71,10 @@ pub struct MarkdownTree { node_functions: Vec>, node_headings: Vec>, node_modes: Vec, + function_headings: HashMap, + unit_headings: HashMap, + unit_functions: HashMap, + heading_units: HashMap, } #[derive(Debug, Deserialize)] @@ -101,20 +102,71 @@ struct RawNode { } impl MarkdownTree { - pub fn from_json(value: Value, source: &SourceSnapshot) -> Result { - let raw: RawNode = serde_json::from_value(value) - .map_err(|error| LintError::Protocol(format!("AST JSON 无效:{error}")))?; - Self::from_raw(raw, source) + /// Empty container used only for an honest `analysis_incomplete` report + /// after `check` failed. It contains no document AST and therefore runs no + /// document-dependent rules. + pub fn empty(source: &SourceSnapshot) -> Self { + let span = Span::new(0, source.bytes.len()); + Self { + nodes: vec![MarkdownNode { + kind: "document".into(), + span, + literal: None, + level: None, + setext: false, + ordered: None, + start: None, + tight: None, + task: None, + ticks: None, + parent: None, + children: Vec::new(), + }], + root: 0, + headings: Vec::new(), + carriers: Vec::new(), + node_functions: vec![None], + node_headings: vec![None], + node_modes: vec![HeadingMode::Knowledge], + function_headings: HashMap::new(), + unit_headings: HashMap::new(), + unit_functions: HashMap::new(), + heading_units: HashMap::new(), + } } - fn from_raw(raw: RawNode, source: &SourceSnapshot) -> Result { + /// Build the Markdown container and carrier index from the public + /// `modules[].document` projection plus the authoritative `units` list. + /// No declaration syntax is parsed here: modes, names, section ranges and + /// function ownership come only from Analysis. + pub fn from_analysis( + document: Value, + units: &[AnalysisUnit], + functions: &[AnalysisFunction], + source: &SourceSnapshot, + ) -> Result { + let raw: RawNode = serde_json::from_value(document).map_err(|error| { + LintError::Protocol(format!("modules[].document JSON 无效:{error}")) + })?; + Self::from_raw(raw, units, functions, source) + } + + fn from_raw( + raw: RawNode, + units: &[AnalysisUnit], + functions: &[AnalysisFunction], + source: &SourceSnapshot, + ) -> Result { if raw.kind != "document" { - return Err(LintError::Protocol("AST 根节点不是 document".into())); + return Err(LintError::Protocol( + "modules[].document 根节点不是 document".into(), + )); } let mut nodes = Vec::new(); let root = flatten(raw, None, &mut nodes); for node in &nodes { node.span.validate(source.bytes.len())?; + source.slice(node.span)?; } let count = nodes.len(); let mut tree = Self { @@ -125,62 +177,119 @@ impl MarkdownTree { node_functions: vec![None; count], node_headings: vec![None; count], node_modes: vec![HeadingMode::Knowledge; count], + function_headings: HashMap::new(), + unit_headings: HashMap::new(), + unit_functions: HashMap::new(), + heading_units: HashMap::new(), }; - tree.index_headings_and_carriers(source)?; + tree.index_units(units, functions)?; + tree.index_regions_and_carriers(units, source)?; Ok(tree) } - fn index_headings_and_carriers(&mut self, source: &SourceSnapshot) -> Result<()> { - struct Ancestor { - level: u8, - mode: HeadingMode, + fn index_units( + &mut self, + units: &[AnalysisUnit], + functions: &[AnalysisFunction], + ) -> Result<()> { + let function_unit_to_id: HashMap<&str, &str> = functions + .iter() + .map(|function| (function.unit_id.as_str(), function.id.as_str())) + .collect(); + let units_by_id: HashMap<&str, &AnalysisUnit> = + units.iter().map(|unit| (unit.id.as_str(), unit)).collect(); + for unit in units.iter().filter(|unit| unit.kind != UnitKind::Root) { + let mut cursor = Some(unit); + let mut owner = None; + while let Some(current) = cursor { + if current.kind == UnitKind::Function { + owner = function_unit_to_id.get(current.id.as_str()).copied(); + break; + } + cursor = current + .parent_id + .as_deref() + .and_then(|id| units_by_id.get(id).copied()); + } + if let Some(owner) = owner { + self.unit_functions + .insert(unit.id.clone(), owner.to_string()); + } } - let mut stack: Vec = Vec::new(); + for (index, unit) in units + .iter() + .enumerate() + .filter(|(_, unit)| unit.kind != UnitKind::Root) + { + let heading_span = unit.heading_span.ok_or_else(|| { + LintError::Protocol(format!("unit {} 缺少 heading_span", unit.id)) + })?; + let node = self.heading_node_at(heading_span).ok_or_else(|| { + LintError::Protocol(format!( + "unit {} 的 heading_span 无法唯一对应 document heading", + unit.id + )) + })?; + self.unit_headings.insert(unit.id.clone(), node); + self.heading_units.insert(node, index); + if unit.kind == UnitKind::Function { + let function_id = function_unit_to_id.get(unit.id.as_str()).ok_or_else(|| { + LintError::Protocol(format!("function unit {} 缺少 function 记录", unit.id)) + })?; + self.function_headings + .insert((*function_id).to_string(), node); + } + } + Ok(()) + } + + fn heading_node_at(&self, span: Span) -> Option { + let matches: Vec<_> = self + .nodes + .iter() + .enumerate() + .filter(|(_, node)| node.kind == "heading" && node.span == span) + .map(|(node, _)| node) + .collect(); + (matches.len() == 1).then_some(matches[0]) + } + + fn index_regions_and_carriers( + &mut self, + units: &[AnalysisUnit], + source: &SourceSnapshot, + ) -> Result<()> { let mut current_heading = None; let mut current_function = None; let mut current_mode = HeadingMode::Knowledge; let root_children = self.nodes[self.root].children.clone(); for child in root_children { if self.nodes[child].kind == "heading" { - let level = self.nodes[child].level.unwrap_or(0); - while stack.last().is_some_and(|entry| entry.level >= level) { - stack.pop(); - } - let inherited = stack - .last() - .map(|entry| entry.mode) - .unwrap_or(HeadingMode::Knowledge); - let declared = if self.nodes[child].setext { - None - } else { - heading_declaration(self, child) - }; - current_mode = declared - .as_ref() - .map(|(mode, _)| *mode) - .unwrap_or(inherited); + let unit_index = self.heading_units.get(&child).copied().ok_or_else(|| { + LintError::Protocol(format!( + "document heading 字节 [{}, {}) 没有对应 unit", + self.nodes[child].span.start, self.nodes[child].span.end + )) + })?; + let unit = &units[unit_index]; current_heading = Some(child); - match level { - 1 => current_function = None, - 2 => { - current_function = (current_mode == HeadingMode::Exec).then_some(child) - } - _ => {} - } - let name = declared - .map(|(_, name)| name) - .unwrap_or_else(|| plain_text(self, child)); + current_mode = unit.mode; + current_function = match unit.kind { + UnitKind::Function => Some(child), + UnitKind::Section => self + .unit_functions + .get(&unit.id) + .and_then(|id| self.function_headings.get(id).copied()), + _ => None, + }; self.headings.push(HeadingSegment { node: child, - level, - mode: current_mode, - name, + unit_id: unit.id.clone(), + level: unit.level, + mode: unit.mode, + name: unit.name.clone(), function: current_function, }); - stack.push(Ancestor { - level, - mode: current_mode, - }); self.node_headings[child] = current_heading; self.node_functions[child] = current_function; self.node_modes[child] = current_mode; @@ -253,7 +362,7 @@ impl MarkdownTree { }); let mut spans = children; let first = spans.next().unwrap_or(span); - let last = spans.last().unwrap_or(first); + let last = spans.next_back().unwrap_or(first); Span::new(first.start, last.end) }; source.slice(span)?; @@ -296,6 +405,19 @@ impl MarkdownTree { self.headings.iter().find(|heading| heading.node == node) } + pub fn heading_for_unit(&self, unit_id: &str) -> Option { + self.unit_headings.get(unit_id).copied() + } + + pub fn function_heading(&self, function_id: &str) -> Option { + self.function_headings.get(function_id).copied() + } + + pub fn function_segment(&self, function_id: &str) -> Option<&HeadingSegment> { + let node = self.function_heading(function_id)?; + self.heading(node) + } + pub fn ancestors(&self, mut node: NodeId) -> Vec { let mut result = Vec::new(); while let Some(parent) = self.nodes[node].parent { @@ -319,7 +441,9 @@ impl MarkdownTree { } pub fn first_carrier_in_item(&self, item: NodeId) -> Option<&Carrier> { - self.item_carriers(item).into_iter().min_by_key(|c| c.span.start) + self.item_carriers(item) + .into_iter() + .min_by_key(|c| c.span.start) } pub fn is_descendant(&self, node: NodeId, ancestor: NodeId) -> bool { @@ -352,7 +476,10 @@ impl MarkdownTree { fn has_carrier_ancestor(&self, node: NodeId) -> bool { self.ancestors(node).into_iter().any(|ancestor| { - matches!(self.nodes[ancestor].kind.as_str(), "strong" | "emph" | "code") + matches!( + self.nodes[ancestor].kind.as_str(), + "strong" | "emph" | "code" + ) }) } @@ -360,7 +487,13 @@ impl MarkdownTree { self.ancestors(node).into_iter().any(|ancestor| { matches!( self.nodes[ancestor].kind.as_str(), - "table" | "strikethrough" | "code_block" | "math" | "math_block" | "html_block" | "html_inline" + "table" + | "strikethrough" + | "code_block" + | "math" + | "math_block" + | "html_block" + | "html_inline" ) }) } @@ -394,83 +527,3 @@ fn flatten(raw: RawNode, parent: Option, nodes: &mut Vec) } id } - -fn heading_declaration(tree: &MarkdownTree, heading: NodeId) -> Option<(HeadingMode, String)> { - let first = tree.nodes[heading].children.first()?; - let first = &tree.nodes[*first]; - if first.kind != "text" { - return None; - } - let literal = first.literal.as_deref()?; - for (prefix, mode) in [ - ("@exec", HeadingMode::Exec), - ("@knowledge", HeadingMode::Knowledge), - ] { - if let Some(rest) = literal.strip_prefix(prefix) { - if rest.is_empty() || rest.starts_with(char::is_whitespace) { - let name = rest.trim(); - if !name.is_empty() { - return Some((mode, name.to_string())); - } - } - } - } - None -} - -pub fn plain_text(tree: &MarkdownTree, node: NodeId) -> String { - let node = &tree.nodes[node]; - if let Some(literal) = &node.literal { - if node.kind == "text" || node.kind == "code" { - return literal.clone(); - } - } - node.children - .iter() - .map(|child| plain_text(tree, *child)) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - use std::path::PathBuf; - - fn tree(markdown: &str) -> MarkdownTree { - let source = SourceSnapshot::new(PathBuf::from("test.mq.md"), markdown.as_bytes().to_vec()).unwrap(); - let ast = crate::input::fallback_ast(&source).unwrap(); - MarkdownTree::from_json(ast, &source).unwrap() - } - - #[test] - fn indexes_functions_carriers_and_list_ancestors() { - let tree = tree("# @knowledge 示例\n\n## @exec 判断\n\n说明。\n\n`params(x: Int)`\n\n1. `if x > 0`:正数。\n\n **结果 = 1**\n\n2. `else`:其他。\n\n **结果 = 0**\n\n`end`\n\n*return 结果*\n"); - assert_eq!(tree.headings.len(), 2); - assert_eq!(tree.carriers.len(), 7); - let if_carrier = tree.carriers.iter().find(|c| c.payload == "if x > 0").unwrap(); - let item = tree.nearest(if_carrier.node, "item").unwrap(); - assert_eq!(tree.first_carrier_in_item(item).unwrap().node, if_carrier.node); - let list = tree.nearest(item, "list").unwrap(); - assert_eq!(tree.nodes[list].ordered, Some(true)); - } - - #[test] - fn knowledge_carriers_are_not_executable() { - let tree = tree("## @knowledge 说明\n\n**重要** 和 `code`。\n"); - assert!(tree.carriers.is_empty()); - assert!(tree.prose_fragments(0).is_empty()); - } - - #[test] - fn exec_emphasis_is_a_carrier_not_prose_and_headings_are_excluded() { - let tree = tree("## @exec 标题不计量\n\n普通说明 **重要** 继续说明。\n\n### 小节也不计量\n\n*return 0*\n"); - let function = tree.headings[0].node; - let prose: Vec<_> = tree - .prose_fragments(function) - .into_iter() - .map(|fragment| fragment.text) - .collect(); - assert_eq!(prose, vec!["普通说明 ", " 继续说明。"]); - assert!(tree.carriers.iter().any(|carrier| carrier.payload == "重要")); - } -} diff --git a/src/model/mod.rs b/src/model/mod.rs index 53001fd..54fdf0a 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -4,11 +4,15 @@ mod source; mod span; pub use analysis::{ - semantic_nodes, AnalysisFunction, AnalysisModule, CoreDiagnostic, ExecutionProjection, + semantic_nodes, AnalysisAnchor, AnalysisCall, AnalysisDiagnostic, AnalysisFunction, + AnalysisImport, AnalysisModule, AnalysisParam, AnalysisProject, AnalysisReference, + AnalysisResource, AnalysisSignature, AnalysisUnit, CallReason, CallState, CallTargetKind, + CallTargetOwner, ExecutionProjection, ExtensionIdentity, HeadingMode, IdentityKind, ModeOrigin, + Producer, ReferenceState, ReferenceTargetKind, ResourceKind, SignatureKind, StdlibIdentity, + UnitKind, }; pub use markdown::{ - Carrier, CarrierKind, HeadingMode, HeadingSegment, MarkdownNode, MarkdownTree, NodeId, - ProseFragment, + Carrier, CarrierKind, HeadingSegment, MarkdownNode, MarkdownTree, NodeId, ProseFragment, }; pub use source::SourceSnapshot; pub use span::{LineColumn, Span}; diff --git a/src/model/source.rs b/src/model/source.rs index 6ad1dac..95a52d8 100644 --- a/src/model/source.rs +++ b/src/model/source.rs @@ -1,4 +1,7 @@ -use std::{fs, path::{Path, PathBuf}}; +use std::{ + fs, + path::{Path, PathBuf}, +}; use sha2::{Digest, Sha256}; @@ -52,7 +55,10 @@ impl SourceSnapshot { pub fn slice(&self, span: Span) -> Result<&str> { span.validate(self.bytes.len())?; self.text().get(span.start..span.end).ok_or_else(|| { - LintError::Protocol(format!("span [{}, {}) 不在 UTF-8 字符边界", span.start, span.end)) + LintError::Protocol(format!( + "span [{}, {}) 不在 UTF-8 字符边界", + span.start, span.end + )) }) } @@ -93,9 +99,18 @@ mod tests { ) .unwrap(); assert!(source.digest.starts_with("sha256:")); - assert_eq!(source.line_column(3).unwrap(), LineColumn { line: 1, column: 1 }); - assert_eq!(source.line_column(6).unwrap(), LineColumn { line: 1, column: 2 }); - assert_eq!(source.line_column(11).unwrap(), LineColumn { line: 2, column: 1 }); + assert_eq!( + source.line_column(3).unwrap(), + LineColumn { line: 1, column: 1 } + ); + assert_eq!( + source.line_column(6).unwrap(), + LineColumn { line: 1, column: 2 } + ); + assert_eq!( + source.line_column(11).unwrap(), + LineColumn { line: 2, column: 1 } + ); } #[test] diff --git a/src/rules/mod.rs b/src/rules/mod.rs index c217d0e..7ab71dd 100644 --- a/src/rules/mod.rs +++ b/src/rules/mod.rs @@ -206,6 +206,42 @@ pub const CATALOG: &[RuleSpec] = &[ "heading 模式序列及核心控制边界诊断。", Manual ), + rule!( + "MQD-LINK-001", + Error, + "引用目标缺失、歧义、无效或越界", + "读者无法到达所声明的目标,或目标不唯一。", + "修正引用地址或目标,歧义时不要任选第一个候选。", + "Analysis references[].state 为 missing/ambiguous/invalid/outside_scope。", + Manual + ), + rule!( + "MQD-LINK-002", + Info, + "本地引用未在当前范围核验", + "普通 Analysis 只验证已加载模块,未加载不等于断链。", + "需要核验时显式运行 check --refs 或加载对应模块。", + "Analysis references[].state 为 not_loaded。", + Manual + ), + rule!( + "MQD-LINK-003", + Info, + "外部引用未联网核验", + "Lint 不访问网络,外部 URI 只作信息提示。", + "如需确认外部目标,请在文档评审中人工检查。", + "Analysis references[].state 为 external。", + Manual + ), + rule!( + "MQD-CALL-001", + Info, + "调用目标未静态绑定", + "动态调用或无法静态绑定的目标不影响 Analysis 的有效性。", + "当调用是公开接口时,补充说明其目标和约束。", + "Analysis calls[].state 为 unresolved 及 reason。", + Manual + ), rule!( "MQD-SAFETY-001", Error, @@ -229,9 +265,11 @@ mod tests { #[test] fn catalog_has_stable_unique_ids() { let ids: BTreeSet<_> = CATALOG.iter().map(|rule| rule.id).collect(); - assert_eq!(CATALOG.len(), 18); + assert_eq!(CATALOG.len(), 22); assert_eq!(ids.len(), CATALOG.len()); assert!(ids.contains("MQD-BRANCH-001")); assert!(ids.contains("MQD-SAFETY-001")); + assert!(ids.contains("MQD-LINK-001")); + assert!(ids.contains("MQD-CALL-001")); } } diff --git a/src/rules/supplemental.rs b/src/rules/supplemental.rs index f2d385f..eac0256 100644 --- a/src/rules/supplemental.rs +++ b/src/rules/supplemental.rs @@ -1,15 +1,14 @@ use std::collections::{BTreeMap, BTreeSet}; -use serde_json::Value; - use crate::{ - alignment::{node_span, ReadableControlTree}, + alignment::ReadableControlTree, diagnostics::Diagnostic, input::{CheckDiagnostic, SourceDocument}, metrics::narrative_count, model::{ - effect_sites, statements, AnalysisFunction, Carrier, CarrierKind, HeadingMode, - HeadingSegment, MarkdownTree, ProseFragment, Span, StatementKind, + effect_sites, statements, AnalysisCall, AnalysisFunction, Carrier, CarrierKind, + HeadingMode, HeadingSegment, MarkdownTree, ProseFragment, ReferenceState, Span, + StatementKind, }, }; @@ -17,13 +16,105 @@ pub fn check_ast_document(document: &SourceDocument) -> Vec { let markdown = &document.markdown; let mut diagnostics = prose_rule(markdown); diagnostics.extend(knowledge_rule(markdown)); + diagnostics.extend(reference_rules(document)); + diagnostics.extend(call_rules(document)); + diagnostics +} + +fn reference_rules(document: &SourceDocument) -> Vec { + let Some(module) = &document.module else { + return Vec::new(); + }; + let mut diagnostics = Vec::new(); + for reference in &module.references { + let function = module + .units + .iter() + .find(|unit| unit.id == reference.source_unit) + .and_then(|unit| unit.function.as_deref()) + .and_then(|function_id| { + module + .functions + .iter() + .find(|function| function.id == function_id) + .map(|function| function.local_name.as_str()) + }); + let diagnostic = match reference.state { + ReferenceState::Missing => Some( + Diagnostic::new("MQD-LINK-001", reference.span) + .with_message(format!("引用目标缺失:{}", reference.url)), + ), + ReferenceState::Ambiguous => Some( + Diagnostic::new("MQD-LINK-001", reference.span).with_message(format!( + "引用目标有多个候选,不能任选其一:{}({})", + reference.url, + reference.candidates.join(", ") + )), + ), + ReferenceState::Invalid => Some( + Diagnostic::new("MQD-LINK-001", reference.span) + .with_message(format!("引用地址无效:{}", reference.url)), + ), + ReferenceState::OutsideScope => Some( + Diagnostic::new("MQD-LINK-001", reference.span) + .with_message(format!("引用目标越出项目范围:{}", reference.url)), + ), + ReferenceState::NotLoaded => Some( + Diagnostic::new("MQD-LINK-002", reference.span).with_message(format!( + "引用未在当前 Analysis 范围核验(未加载,不等于断链):{}", + reference.url + )), + ), + ReferenceState::External => Some( + Diagnostic::new("MQD-LINK-003", reference.span) + .with_message(format!("外部引用不联网核验:{}", reference.url)), + ), + ReferenceState::Resolved => None, + }; + let Some(mut diagnostic) = diagnostic else { + continue; + }; + if let Some(function) = function { + diagnostic = diagnostic.with_function(function); + } + diagnostics.push(diagnostic); + } + diagnostics +} + +fn call_rules(document: &SourceDocument) -> Vec { + let Some(module) = &document.module else { + return Vec::new(); + }; + let mut diagnostics = Vec::new(); + for call in &module.calls { + if call.state != crate::model::CallState::Unresolved { + continue; + } + let function = module + .functions + .iter() + .find(|function| function.id == call.function) + .map(|function| function.local_name.as_str()); + let reason = match call.reason { + Some(crate::model::CallReason::Dynamic) => "动态调用", + Some(crate::model::CallReason::Unbound) => "静态目标未绑定", + None => "未绑定", + }; + let mut diagnostic = Diagnostic::new("MQD-CALL-001", call.span) + .with_message(format!("调用目标未静态绑定({reason});这不是错误")); + if let Some(function) = function { + diagnostic = diagnostic.with_function(function); + } + diagnostics.push(diagnostic); + } diagnostics } pub(crate) fn check_supplemental_function( markdown: &MarkdownTree, function: &AnalysisFunction, - calls: &[Value], + calls: &[AnalysisCall], tree: &ReadableControlTree, ) -> Vec { let mut diagnostics = effect_rule(markdown, function, calls); @@ -222,13 +313,11 @@ fn knowledge_rule(markdown: &MarkdownTree) -> Vec { fn effect_rule( markdown: &MarkdownTree, analysis: &AnalysisFunction, - calls: &[Value], + calls: &[AnalysisCall], ) -> Vec { let carriers = function_carriers(markdown, analysis); let prose = markdown - .headings - .iter() - .find(|heading| markdown.nodes[heading.node].span == analysis.heading_span) + .function_segment(&analysis.id) .map(|heading| markdown.prose_fragments(heading.node)) .unwrap_or_default(); let anchors: BTreeSet<_> = effect_sites(analysis, calls) @@ -243,13 +332,10 @@ fn effect_rule( } fn parameter_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec { - if analysis.signature.get("kind").and_then(Value::as_str) != Some("explicit") { + if analysis.signature.kind != crate::model::SignatureKind::Explicit { return Vec::new(); } - let Some(params) = analysis.signature.get("params").and_then(Value::as_array) else { - return Vec::new(); - }; - if params.is_empty() { + if analysis.signature.params.is_empty() { return Vec::new(); } let carriers = function_carriers(markdown, analysis); @@ -263,9 +349,11 @@ fn parameter_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec( markdown: &'a MarkdownTree, analysis: &AnalysisFunction, ) -> Vec<&'a Carrier> { - let Some(function) = markdown - .headings - .iter() - .find(|heading| markdown.nodes[heading.node].span == analysis.heading_span) - .map(|heading| heading.node) - else { + let Some(function) = markdown.function_heading(&analysis.id) else { return Vec::new(); }; let mut carriers: Vec<_> = markdown diff --git a/tests/cli.rs b/tests/cli.rs index bb0f510..8c276f3 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -19,7 +19,7 @@ fn rule_commands_do_not_require_the_core() { .unwrap(); assert!(output.status.success()); let rules: Vec = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(rules.len(), 18); + assert_eq!(rules.len(), 22); let output = lint() .env("MARQDO_BIN", "no-such-core") @@ -95,11 +95,7 @@ reason = "Fixture for a deliberately short helper" .as_str() .unwrap() .contains("sem.unclosed_control")); - assert!(result["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|d| d["id"] == "MQD-KNOW-001")); + assert!(result["diagnostics"].as_array().unwrap().is_empty()); let invalid_signature = "## @exec x\n\n- `params(n: Int)`\n\n*return 1*"; fs::write(temp.path().join("index.mq.md"), invalid_signature).unwrap(); let (code, result) = report(&[]); @@ -349,3 +345,65 @@ fn t16_exec_emphasis_inside_prose_is_not_a_comment() { .iter() .any(|d| d["id"] == "MQD-PROSE-001")); } + +#[cfg(unix)] +#[test] +fn old_tool_manifest_is_rejected_and_new_manifest_requires_revision_one() { + let Some(core) = std::env::var_os("MARQDO_BIN") else { + return; + }; + let temp = tempfile::tempdir().unwrap(); + let bundle = temp.path().join("bundle"); + fs::create_dir_all(bundle.join("bin")).unwrap(); + fs::copy( + env!("CARGO_BIN_EXE_marqdo-lint"), + bundle.join("bin/marqdo-lint"), + ) + .unwrap(); + let manifest = bundle.join("tool.json"); + fs::write(&manifest, include_bytes!("../tool.json")).unwrap(); + let value: Value = serde_json::from_slice(&fs::read(&manifest).unwrap()).unwrap(); + assert_eq!(value["requires"]["api_revision"], 1); + assert_eq!(value["requires"]["analysis"], 3); + assert!(value.get("compatibility").is_none()); + let marqdo = || { + let mut command = Command::new(&core); + command + .env("MARQDO_TOOL_HOME", temp.path().join("registry")) + .env_remove("MARQDO_BIN"); + command + }; + assert!(marqdo() + .args(["tool", "install"]) + .arg(&manifest) + .output() + .unwrap() + .status + .success()); + assert!(marqdo() + .args(["tool", "remove", "lint"]) + .output() + .unwrap() + .status + .success()); + + let old = value; + let mut object = old.as_object().unwrap().clone(); + object.insert( + "compatibility".into(), + serde_json::json!({"marqdo": ">=3.0.0-rc.1,<4.0.0", "analysis": [2, 3]}), + ); + fs::write( + &manifest, + serde_json::to_vec(&Value::Object(object)).unwrap(), + ) + .unwrap(); + let output = marqdo() + .args(["tool", "install"]) + .arg(&manifest) + .output() + .unwrap(); + assert!(!output.status.success(), "{output:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("compatibility"), "{stderr}"); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..67cec56 --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,47 @@ +#![allow(dead_code)] + +use std::path::PathBuf; + +use marqdo_lint::{ + input::SourceDocument, + model::{ExecutionProjection, MarkdownTree}, +}; + +pub fn fixture_path(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/rc4") + .join(name) +} + +pub fn analysis_value(stem: &str) -> serde_json::Value { + serde_json::from_slice(&std::fs::read(fixture_path(&format!("{stem}.analysis.json"))).unwrap()) + .unwrap() +} + +pub fn projection(stem: &str) -> ExecutionProjection { + ExecutionProjection::from_json(analysis_value(stem)).unwrap() +} + +pub fn document(stem: &str) -> SourceDocument { + let projection = projection(stem); + let module = projection.entry_module().unwrap().clone(); + let source = module + .source_snapshot(fixture_path(&format!("{stem}.mq.md"))) + .unwrap(); + let markdown = MarkdownTree::from_analysis( + module.document.clone(), + &module.units, + &module.functions, + &source, + ) + .unwrap(); + SourceDocument { + source, + markdown, + module: Some(module), + } +} + +pub fn require_core() -> Option { + std::env::var_os("MARQDO_BIN").map(PathBuf::from) +} diff --git a/tests/control_alignment.rs b/tests/control_alignment.rs index c46e78d..35d44ef 100644 --- a/tests/control_alignment.rs +++ b/tests/control_alignment.rs @@ -1,24 +1,27 @@ +mod common; + use std::{fs, path::Path}; +use common::{document, require_core}; use marqdo_lint::{ alignment::{ align_function, statement_count, ArmRole, BodyOwner, JumpKind, ReadableControlTree, }, input::{AnalysisStatus, MarqdoRunner, ProjectInput}, - model::{AnalysisFunction, ExecutionProjection, MarkdownTree, SourceSnapshot}, + model::ExecutionProjection, }; -use serde_json::Value; +use serde_json::{json, Value}; -fn frozen(stem: &str) -> (MarkdownTree, AnalysisFunction) { - let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/rc2"); - let source = SourceSnapshot::load(dir.join(format!("{stem}.mq.md"))).unwrap(); - let read = |kind| -> Value { - serde_json::from_slice(&fs::read(dir.join(format!("{stem}.{kind}.json"))).unwrap()).unwrap() - }; - let markdown = MarkdownTree::from_json(read("ast")["ast"].clone(), &source).unwrap(); - let projection = ExecutionProjection::from_json(read("analysis")).unwrap(); - let analysis = projection.modules[0].functions[0].clone(); - (markdown, analysis) +fn frozen( + stem: &str, +) -> ( + marqdo_lint::model::MarkdownTree, + marqdo_lint::model::AnalysisFunction, +) { + let document = document(stem); + let module = document.module.as_ref().unwrap(); + let analysis = module.functions[0].clone(); + (document.markdown, analysis) } #[test] @@ -117,11 +120,11 @@ fn rejects_a_jump_projected_in_the_wrong_body() { assert!(tree.issues[0].contains("所属语句体"), "{:?}", tree.issues); } -fn live_alignment(runner: &MarqdoRunner, source: &str) -> (u64, ReadableControlTree) { +fn live_alignment(runner: &MarqdoRunner, source: &str) -> ReadableControlTree { let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("case.mq.md"); fs::write(&file, source).unwrap(); - let project = ProjectInput::load(file, runner).unwrap(); + let project = ProjectInput::load(file, runner, false).unwrap(); assert_eq!( project.analysis_status, AnalysisStatus::Complete, @@ -134,19 +137,18 @@ fn live_alignment(runner: &MarqdoRunner, source: &str) -> (u64, ReadableControlT &document.module.as_ref().unwrap().functions[0], ); assert!(tree.complete, "{:?}", tree.issues); - (project.analysis.unwrap().schema_version, tree) + tree } #[test] fn separate_else_and_if_payloads_open_nested_groups() { - let Ok(binary) = std::env::var("MARQDO_BIN") else { + let Some(binary) = require_core() else { return; }; let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); let source = "## @exec main\n\n`if false`\n\n`else` `if true`\n\n*return 1*\n\n`end`\n\n`end`\n"; - let (version, tree) = live_alignment(&runner, source); - assert_eq!(version, 2); + let tree = live_alignment(&runner, source); let [outer, inner] = tree.controls.as_slice() else { panic!("expected two groups") }; @@ -164,32 +166,13 @@ fn separate_else_and_if_payloads_open_nested_groups() { } #[test] -fn rc2_keeps_an_explicit_empty_else_without_inventing_one() { - let Ok(binary) = std::env::var("MARQDO_BIN") else { - return; - }; - let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); - if !std::process::Command::new(runner.binary()) - .arg("--version") - .output() - .unwrap() - .stdout - .ends_with(b"3.0.0-rc.2\n") - { - return; - } - for fallback in ["", "4. `else`:空回退。\n\n"] { - let source = format!("## @exec main\n\n1. `if false`\n *return 1*\n2. `else if true`\n *return 2*\n3. `else if false`\n *return 3*\n{fallback}\n`end`\n"); - let (version, tree) = live_alignment(&runner, &source); - assert_eq!(version, 2); - let arms = &tree.controls[0].arms; - if fallback.is_empty() { - assert_eq!(arms.len(), 3); - assert_eq!(arms[2].role, ArmRole::ElseIf); - } else { - assert_eq!(arms.len(), 4); - assert_eq!(arms[3].role, ArmRole::Else); - assert!(arms[3].analysis_index.is_none()); - } - } +fn saved_artifact_has_one_analysis_revision() { + let projection = ExecutionProjection::from_json(common::analysis_value("multi-arm")).unwrap(); + assert_eq!(projection.schema_version, 3); + assert_eq!(projection.modules[0].functions[0].effects, vec!["unknown"]); + assert_eq!( + projection.modules[0].units[0].kind, + marqdo_lint::model::UnitKind::Root + ); + let _ = json!(null); } diff --git a/tests/control_rules.rs b/tests/control_rules.rs index b4da46e..b2b18c2 100644 --- a/tests/control_rules.rs +++ b/tests/control_rules.rs @@ -1,3 +1,5 @@ +mod common; + use std::{fs, path::Path}; use marqdo_lint::{ @@ -14,7 +16,7 @@ fn load(source: &str) -> Option { let path = directory.path().join("case.mq.md"); fs::write(&path, source).unwrap(); let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); - Some(ProjectInput::load(path, &runner).unwrap()) + Some(ProjectInput::load(path, &runner, false).unwrap()) } fn load_example(path: &str) -> Option { @@ -23,14 +25,21 @@ fn load_example(path: &str) -> Option { None })?; let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); - Some(ProjectInput::load(Path::new(env!("CARGO_MANIFEST_DIR")).join(path), &runner).unwrap()) + Some( + ProjectInput::load( + Path::new(env!("CARGO_MANIFEST_DIR")).join(path), + &runner, + false, + ) + .unwrap(), + ) } fn ids(project: &ProjectInput) -> Vec { let mut ids: Vec<_> = project .documents .iter() - .flat_map(|document| check_document(document)) + .flat_map(check_document) .map(|diagnostic| diagnostic.id) .collect(); ids.sort(); @@ -61,40 +70,23 @@ fn assert_no_control_rules(project: &ProjectInput) { } #[test] -fn saved_core_analysis_golden_passes_without_running_core() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")); - let directory = root.join("tests/fixtures/golden"); - for (stem, input) in [ - ("branches", directory.join("branches.mq.md")), - ("inventory", root.join("examples/nested/inventory.mq.md")), - ] { - let source = marqdo_lint::model::SourceSnapshot::load(input).unwrap(); - let ast: serde_json::Value = - serde_json::from_slice(&fs::read(directory.join(format!("{stem}.ast.json"))).unwrap()) - .unwrap(); - let markdown = - marqdo_lint::model::MarkdownTree::from_json(ast["ast"].clone(), &source).unwrap(); - let raw = serde_json::from_slice( - &fs::read(directory.join(format!("{stem}.analysis.json"))).unwrap(), - ) - .unwrap(); - let analysis = marqdo_lint::model::ExecutionProjection::from_json(raw).unwrap(); - let module = analysis - .modules - .into_iter() - .find(|module| module.source_digest == source.digest_hex()) - .unwrap(); +fn saved_rc4_analysis_passes_without_running_core() { + for stem in ["branches", "inventory", "multi-arm", "loop-jumps"] { + let document = common::document(stem); + let module = document.module.as_ref().unwrap(); for function in &module.functions { - let tree = marqdo_lint::alignment::align_function(&markdown, function); + let tree = marqdo_lint::alignment::align_function(&document.markdown, function); assert!(tree.complete, "{stem}: {:?}", tree.issues); } - let document = marqdo_lint::input::SourceDocument { - source, - markdown, - markdown_origin: marqdo_lint::input::MarkdownOrigin::MarqdoInspect, - module: Some(module), - }; - assert!(check_document(&document).is_empty(), "{stem}"); + let diagnostics = check_document(&document); + assert!( + diagnostics + .iter() + .all(|diagnostic| !diagnostic.id.starts_with("MQD-BRANCH") + && !diagnostic.id.starts_with("MQD-LOOP") + && diagnostic.id != "MQD-CTRL-001"), + "{stem}: {diagnostics:?}" + ); } } @@ -292,23 +284,16 @@ fn a_branch_body_outside_its_item_is_a_layout_mismatch() { assert_has(&project, "MQD-LOOP-003"); } -fn rc2_available() -> bool { - std::env::var_os("MARQDO_BIN").is_some_and(|binary| { - std::process::Command::new(binary) - .arg("--version") - .output() - .unwrap() - .stdout - .ends_with(b"3.0.0-rc.2\n") - }) +fn core_available() -> bool { + std::env::var_os("MARQDO_BIN").is_some() } #[test] -fn rc2_branch_rules_anchor_each_affected_arm() { - if !rc2_available() { +fn current_branch_rules_anchor_each_affected_arm() { + if !core_available() { return; } - let good = include_str!("fixtures/rc2/multi-arm.mq.md"); + let good = include_str!("fixtures/control/multi-arm.mq.md"); assert_no_control_rules(&load(good).unwrap()); for (source, rule, anchor, related) in [ ( @@ -392,11 +377,11 @@ fn rc2_branch_rules_anchor_each_affected_arm() { } #[test] -fn rc2_jump_rules_check_the_arm_container_and_carrier_style() { - if !rc2_available() { +fn current_jump_rules_check_the_arm_container_and_carrier_style() { + if !core_available() { return; } - let good = include_str!("fixtures/rc2/loop-jumps.mq.md"); + let good = include_str!("fixtures/control/loop-jumps.mq.md"); assert_no_control_rules(&load(good).unwrap()); let styled = good .replace(" `continue`", " *continue*") diff --git a/tests/documentation_rules.rs b/tests/documentation_rules.rs index fa4f488..d1d1222 100644 --- a/tests/documentation_rules.rs +++ b/tests/documentation_rules.rs @@ -15,7 +15,7 @@ fn load(source: &str) -> Option { let path = directory.path().join("case.mq.md"); fs::write(&path, source).unwrap(); let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); - Some(ProjectInput::load(path, &runner).unwrap()) + Some(ProjectInput::load(path, &runner, false).unwrap()) } fn metrics(project: &ProjectInput) -> Vec { @@ -41,8 +41,11 @@ fn diagnostics(project: &ProjectInput) -> Vec 0", - "span": { - "end": 162, - "start": 152 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":正数返回一。", - "span": { - "end": 183, - "start": 162 - } - } - ], - "kind": "paragraph", - "span": { - "end": 183, - "start": 152 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "结果 = 1", - "span": { - "end": 200, - "start": 190 - } - } - ], - "kind": "strong", - "span": { - "end": 202, - "start": 188 - } - } - ], - "kind": "paragraph", - "span": { - "end": 202, - "start": 188 - } - } - ], - "kind": "item", - "span": { - "end": 202, - "start": 149 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "else", - "span": { - "end": 213, - "start": 207 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":零和负数返回零。", - "span": { - "end": 240, - "start": 213 - } - } - ], - "kind": "paragraph", - "span": { - "end": 240, - "start": 207 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "结果 = 0", - "span": { - "end": 257, - "start": 247 - } - } - ], - "kind": "strong", - "span": { - "end": 259, - "start": 245 - } - } - ], - "kind": "paragraph", - "span": { - "end": 259, - "start": 245 - } - } - ], - "kind": "item", - "span": { - "end": 259, - "start": 204 - } - } - ], - "kind": "list", - "ordered": true, - "span": { - "end": 259, - "start": 149 - }, - "start": 1, - "tight": false - }, - { - "children": [ - { - "kind": "code", - "literal": "end", - "span": { - "end": 266, - "start": 261 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 266, - "start": 261 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "返回整数结果。", - "span": { - "end": 289, - "start": 268 - } - } - ], - "kind": "paragraph", - "span": { - "end": 289, - "start": 268 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "return 结果", - "span": { - "end": 305, - "start": 292 - } - } - ], - "kind": "emph", - "span": { - "end": 306, - "start": 291 - } - } - ], - "kind": "paragraph", - "span": { - "end": 306, - "start": 291 - } - } - ], - "kind": "document", - "span": { - "end": 306, - "start": 0 - } - }, - "command": "inspect", - "module": "root:default::branches.mq.md" -} diff --git a/tests/fixtures/golden/invalid-control.ast.json b/tests/fixtures/golden/invalid-control.ast.json deleted file mode 100644 index c91a3a9..0000000 --- a/tests/fixtures/golden/invalid-control.ast.json +++ /dev/null @@ -1,237 +0,0 @@ -{ - "ast": { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "@exec 跨段控制", - "span": { - "end": 21, - "start": 3 - } - } - ], - "kind": "heading", - "level": 2, - "setext": false, - "span": { - "end": 21, - "start": 0 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "说明跨段控制的错误。", - "span": { - "end": 53, - "start": 23 - } - } - ], - "kind": "paragraph", - "span": { - "end": 53, - "start": 23 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "params(x: Int)", - "span": { - "end": 71, - "start": 55 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 71, - "start": 55 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "开始", - "span": { - "end": 83, - "start": 77 - } - } - ], - "kind": "heading", - "level": 3, - "setext": false, - "span": { - "end": 83, - "start": 73 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "if x > 0", - "span": { - "end": 95, - "start": 85 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 95, - "start": 85 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "结果 = 1", - "span": { - "end": 109, - "start": 99 - } - } - ], - "kind": "strong", - "span": { - "end": 111, - "start": 97 - } - } - ], - "kind": "paragraph", - "span": { - "end": 111, - "start": 97 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "结束", - "span": { - "end": 123, - "start": 117 - } - } - ], - "kind": "heading", - "level": 3, - "setext": false, - "span": { - "end": 123, - "start": 113 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "else", - "span": { - "end": 131, - "start": 125 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 131, - "start": 125 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "结果 = 0", - "span": { - "end": 145, - "start": 135 - } - } - ], - "kind": "strong", - "span": { - "end": 147, - "start": 133 - } - } - ], - "kind": "paragraph", - "span": { - "end": 147, - "start": 133 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "end", - "span": { - "end": 154, - "start": 149 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 154, - "start": 149 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "return 结果", - "span": { - "end": 170, - "start": 157 - } - } - ], - "kind": "emph", - "span": { - "end": 171, - "start": 156 - } - } - ], - "kind": "paragraph", - "span": { - "end": 171, - "start": 156 - } - } - ], - "kind": "document", - "span": { - "end": 171, - "start": 0 - } - }, - "command": "inspect", - "module": "root:default::invalid-control.mq.md" -} diff --git a/tests/fixtures/golden/invalid-control.check.txt b/tests/fixtures/golden/invalid-control.check.txt deleted file mode 100644 index d4706e4..0000000 --- a/tests/fixtures/golden/invalid-control.check.txt +++ /dev/null @@ -1,10 +0,0 @@ -error[sem.unclosed_control]: /home/cflmy/work/marqdo-lint/tests/fixtures/golden/invalid-control.mq.md:9:1: `if` is not closed by `end` - `if x > 0` - ^ -error[sem.unmatched_else]: /home/cflmy/work/marqdo-lint/tests/fixtures/golden/invalid-control.mq.md:15:1: `else` has no open `if` - `else` - ^ -error[sem.unmatched_end]: /home/cflmy/work/marqdo-lint/tests/fixtures/golden/invalid-control.mq.md:19:1: `end` has no open `if`/`while` in this heading segment - `end` - ^ -check failed: 3 error(s), 0 warning(s) diff --git a/tests/fixtures/golden/inventory.analysis.json b/tests/fixtures/golden/inventory.analysis.json deleted file mode 100644 index 0d777e0..0000000 --- a/tests/fixtures/golden/inventory.analysis.json +++ /dev/null @@ -1,368 +0,0 @@ -{ - "diagnostics": [], - "modules": [ - { - "calls": [ - { - "callee": { - "kind": "ident", - "name": "长度" - }, - "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", - "span": { - "end": 411, - "start": 391 - }, - "state": "builtin", - "target": "长度" - } - ], - "functions": [ - { - "body": [ - { - "kind": "assign", - "span": { - "end": 273, - "start": 259 - }, - "target": "总量", - "value": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "int", - "value": "0" - } - }, - { - "kind": "assign", - "span": { - "end": 289, - "start": 275 - }, - "target": "位置", - "value": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "int", - "value": "0" - } - }, - { - "arms": [ - { - "body": [ - { - "body": [ - { - "kind": "assign", - "span": { - "end": 630, - "start": 588 - }, - "target": "总量", - "value": { - "kind": "binary", - "left": { - "kind": "variable", - "name": "总量", - "span": { - "end": 605, - "start": 599 - } - }, - "op": "add", - "right": { - "base": { - "kind": "variable", - "name": "数量列表", - "span": { - "end": 620, - "start": 608 - } - }, - "index": { - "kind": "variable", - "name": "位置", - "span": { - "end": 627, - "start": 621 - } - }, - "kind": "index", - "span": { - "end": 628, - "start": 608 - } - }, - "span": { - "end": 628, - "start": 599 - } - } - }, - { - "kind": "assign", - "span": { - "end": 660, - "start": 637 - }, - "target": "位置", - "value": { - "kind": "binary", - "left": { - "kind": "variable", - "name": "位置", - "span": { - "end": 654, - "start": 648 - } - }, - "op": "add", - "right": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "int", - "value": "1" - }, - "span": { - "end": 658, - "start": 648 - } - } - } - ], - "condition": { - "kind": "binary", - "left": { - "kind": "variable", - "name": "位置", - "span": { - "end": 388, - "start": 382 - } - }, - "op": "lt", - "right": { - "args": [ - { - "name": null, - "span": { - "end": 410, - "start": 398 - }, - "value": { - "kind": "variable", - "name": "数量列表", - "span": { - "end": 410, - "start": 398 - } - } - } - ], - "callee": { - "kind": "variable", - "name": "长度", - "span": { - "end": 397, - "start": 391 - } - }, - "kind": "call", - "span": { - "end": 411, - "start": 391 - } - }, - "span": { - "end": 411, - "start": 382 - } - }, - "condition_span": { - "end": 412, - "start": 375 - }, - "kind": "loop", - "span": { - "end": 412, - "start": 375 - } - } - ], - "condition": { - "kind": "variable", - "name": "仓库启用", - "span": { - "end": 328, - "start": 316 - } - }, - "condition_span": { - "end": 329, - "start": 312 - }, - "span": { - "end": 329, - "start": 312 - } - } - ], - "kind": "branch", - "span": { - "end": 329, - "start": 312 - } - }, - { - "kind": "return", - "span": { - "end": 864, - "start": 849 - }, - "value": { - "kind": "variable", - "name": "总量", - "span": { - "end": 863, - "start": 857 - } - } - } - ], - "effects": [ - "unknown" - ], - "heading_span": { - "end": 66, - "start": 27 - }, - "id": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", - "local_name": "检查库存并累计可用量", - "namespace": "库存示例", - "signature": { - "kind": "explicit", - "params": [ - { - "default": null, - "name": "仓库启用", - "required": true, - "span": { - "end": 234, - "start": 216 - }, - "type": "Bool" - }, - { - "default": null, - "name": "数量列表", - "required": true, - "span": { - "end": 254, - "start": 235 - }, - "type": "List" - } - ] - }, - "span": { - "end": 864, - "start": 27 - }, - "unit_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量" - } - ], - "id": "root:default::inventory.mq.md", - "imports": [], - "package_instance_id": "root:default", - "references": [], - "relative_path": "inventory.mq.md", - "resources": [], - "source_digest": "34f0bdc21059a64d081f4db011ee1e259fd7d92686e1928f21374ec05a6bd065", - "units": [ - { - "function": null, - "id": "root:default::inventory.mq.md#", - "kind": "root", - "level": 0, - "name": "", - "span": { - "end": 864, - "start": 0 - } - }, - { - "function": null, - "id": "root:default::inventory.mq.md#库存示例", - "kind": "namespace", - "level": 1, - "name": "库存示例", - "span": { - "end": 25, - "start": 0 - } - }, - { - "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", - "id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量", - "kind": "function", - "level": 2, - "name": "检查库存并累计可用量", - "span": { - "end": 66, - "start": 27 - } - }, - { - "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", - "id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量/逐项汇总", - "kind": "section", - "level": 3, - "name": "逐项汇总", - "span": { - "end": 307, - "start": 291 - } - }, - { - "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", - "id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量/汇总结果", - "kind": "section", - "level": 3, - "name": "汇总结果", - "span": { - "end": 788, - "start": 772 - } - } - ] - } - ], - "producer": { - "markdown_profile": "marqdo.md.v1", - "name": "marqdo", - "version": "3.0.0-rc.1" - }, - "project": { - "identity_kind": "workspace_snapshot", - "lock_digest": "", - "root_id": "sha256:523cace2b93bc16e3cf77377d074456c27f8f4bee0e5ee5700b50d6d639945e8", - "stdlib": { - "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "version": "0.1.0" - } - }, - "schema": "marqdo.analysis", - "schema_version": 2 -} \ No newline at end of file diff --git a/tests/fixtures/golden/inventory.ast.json b/tests/fixtures/golden/inventory.ast.json deleted file mode 100644 index c518c3a..0000000 --- a/tests/fixtures/golden/inventory.ast.json +++ /dev/null @@ -1,484 +0,0 @@ -{ - "ast": { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "@knowledge 库存示例", - "span": { - "end": 25, - "start": 2 - } - } - ], - "kind": "heading", - "level": 1, - "setext": false, - "span": { - "end": 25, - "start": 0 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "@exec 检查库存并累计可用量", - "span": { - "end": 66, - "start": 30 - } - } - ], - "kind": "heading", - "level": 2, - "setext": false, - "span": { - "end": 66, - "start": 27 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "只在仓库启用时统计库存;对每个未统计条目进行累计。", - "span": { - "end": 143, - "start": 68 - } - }, - { - "kind": "soft_break", - "span": { - "end": 144, - "start": 143 - } - }, - { - "kind": "text", - "literal": "位置从零下标开始,返回最小计量单位的总量。", - "span": { - "end": 207, - "start": 144 - } - } - ], - "kind": "paragraph", - "span": { - "end": 207, - "start": 68 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "params(仓库启用: Bool, 数量列表: List)", - "span": { - "end": 257, - "start": 209 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 257, - "start": 209 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "总量 = 0", - "span": { - "end": 271, - "start": 261 - } - } - ], - "kind": "strong", - "span": { - "end": 273, - "start": 259 - } - } - ], - "kind": "paragraph", - "span": { - "end": 273, - "start": 259 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "位置 = 0", - "span": { - "end": 287, - "start": 277 - } - } - ], - "kind": "strong", - "span": { - "end": 289, - "start": 275 - } - } - ], - "kind": "paragraph", - "span": { - "end": 289, - "start": 275 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "逐项汇总", - "span": { - "end": 307, - "start": 295 - } - } - ], - "kind": "heading", - "level": 3, - "setext": false, - "span": { - "end": 307, - "start": 291 - } - }, - { - "children": [ - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "if 仓库启用", - "span": { - "end": 329, - "start": 312 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":仅在启用状态下统计库存。", - "span": { - "end": 368, - "start": 329 - } - } - ], - "kind": "paragraph", - "span": { - "end": 368, - "start": 312 - } - }, - { - "children": [ - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "while 位置 < 长度(数量列表)", - "span": { - "end": 412, - "start": 375 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":按位置依次统计,到达列表末尾时终止。", - "span": { - "end": 469, - "start": 412 - } - } - ], - "kind": "paragraph", - "span": { - "end": 469, - "start": 375 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "位置始终指向第一个尚未统计的条目,先读取当前位置再前进,避免漏计首项。", - "span": { - "end": 581, - "start": 476 - } - } - ], - "kind": "paragraph", - "span": { - "end": 581, - "start": 476 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "总量 = 总量 + 数量列表[位置]", - "span": { - "end": 628, - "start": 590 - } - } - ], - "kind": "strong", - "span": { - "end": 630, - "start": 588 - } - } - ], - "kind": "paragraph", - "span": { - "end": 630, - "start": 588 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "位置 = 位置 + 1", - "span": { - "end": 658, - "start": 639 - } - } - ], - "kind": "strong", - "span": { - "end": 660, - "start": 637 - } - } - ], - "kind": "paragraph", - "span": { - "end": 660, - "start": 637 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "end", - "span": { - "end": 672, - "start": 667 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 672, - "start": 667 - } - } - ], - "kind": "item", - "span": { - "end": 672, - "start": 373 - } - } - ], - "kind": "list", - "ordered": false, - "span": { - "end": 672, - "start": 373 - }, - "tight": false - } - ], - "kind": "item", - "span": { - "end": 672, - "start": 309 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "else", - "span": { - "end": 683, - "start": 677 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":仓库未启用时,总量保持为零。", - "span": { - "end": 728, - "start": 683 - } - } - ], - "kind": "paragraph", - "span": { - "end": 728, - "start": 677 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "不执行任何库存统计。", - "span": { - "end": 763, - "start": 733 - } - } - ], - "kind": "paragraph", - "span": { - "end": 763, - "start": 733 - } - } - ], - "kind": "item", - "span": { - "end": 763, - "start": 674 - } - } - ], - "kind": "list", - "ordered": true, - "span": { - "end": 763, - "start": 309 - }, - "start": 1, - "tight": false - }, - { - "children": [ - { - "kind": "code", - "literal": "end", - "span": { - "end": 770, - "start": 765 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 770, - "start": 765 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "汇总结果", - "span": { - "end": 788, - "start": 776 - } - } - ], - "kind": "heading", - "level": 3, - "setext": false, - "span": { - "end": 788, - "start": 772 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "返回累计总量;本函数不会修改库存来源。", - "span": { - "end": 847, - "start": 790 - } - } - ], - "kind": "paragraph", - "span": { - "end": 847, - "start": 790 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "return 总量", - "span": { - "end": 863, - "start": 850 - } - } - ], - "kind": "emph", - "span": { - "end": 864, - "start": 849 - } - } - ], - "kind": "paragraph", - "span": { - "end": 864, - "start": 849 - } - } - ], - "kind": "document", - "span": { - "end": 864, - "start": 0 - } - }, - "command": "inspect", - "module": "root:default::inventory.mq.md" -} diff --git a/tests/fixtures/golden/knowledge.analysis.json b/tests/fixtures/golden/knowledge.analysis.json deleted file mode 100644 index d33c28f..0000000 --- a/tests/fixtures/golden/knowledge.analysis.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "diagnostics": [], - "modules": [ - { - "calls": [], - "functions": [], - "id": "root:default::knowledge.mq.md", - "imports": [], - "package_instance_id": "root:default", - "references": [], - "relative_path": "knowledge.mq.md", - "resources": [], - "source_digest": "342f1937f86ae7b4bfd917ad45b1438b6a6756ecba499b45da5d40e34af3ce5c", - "units": [ - { - "function": null, - "id": "root:default::knowledge.mq.md#", - "kind": "root", - "level": 0, - "name": "", - "span": { - "end": 155, - "start": 0 - } - }, - { - "function": null, - "id": "root:default::knowledge.mq.md#富文本", - "kind": "knowledge", - "level": 2, - "name": "富文本", - "span": { - "end": 23, - "start": 0 - } - } - ] - } - ], - "producer": { - "markdown_profile": "marqdo.md.v1", - "name": "marqdo", - "version": "3.0.0-rc.1" - }, - "project": { - "identity_kind": "workspace_snapshot", - "lock_digest": "", - "root_id": "sha256:3cdb7daa24f2c7cda11ed43c931de8f27e3508519c66148759308012ae78930a", - "stdlib": { - "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "version": "0.1.0" - } - }, - "schema": "marqdo.analysis", - "schema_version": 2 -} \ No newline at end of file diff --git a/tests/fixtures/golden/knowledge.ast.json b/tests/fixtures/golden/knowledge.ast.json deleted file mode 100644 index 4b956e4..0000000 --- a/tests/fixtures/golden/knowledge.ast.json +++ /dev/null @@ -1,217 +0,0 @@ -{ - "ast": { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "@knowledge 富文本", - "span": { - "end": 23, - "start": 3 - } - } - ], - "kind": "heading", - "level": 2, - "setext": false, - "span": { - "end": 23, - "start": 0 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "这里的 ", - "span": { - "end": 35, - "start": 25 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "加粗", - "span": { - "end": 43, - "start": 37 - } - } - ], - "kind": "strong", - "span": { - "end": 45, - "start": 35 - } - }, - { - "kind": "text", - "literal": "、", - "span": { - "end": 48, - "start": 45 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "斜体", - "span": { - "end": 55, - "start": 49 - } - } - ], - "kind": "emph", - "span": { - "end": 56, - "start": 48 - } - }, - { - "kind": "text", - "literal": " 与 ", - "span": { - "end": 61, - "start": 56 - } - }, - { - "kind": "code", - "literal": "code", - "span": { - "end": 67, - "start": 61 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": " 都是惰性内容。", - "span": { - "end": 89, - "start": 67 - } - } - ], - "kind": "paragraph", - "span": { - "end": 89, - "start": 25 - } - }, - { - "alignments": [ - "none", - "none" - ], - "children": [ - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "名称", - "span": { - "end": 99, - "start": 93 - } - } - ], - "kind": "table_cell", - "span": { - "end": 100, - "start": 92 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "说明", - "span": { - "end": 108, - "start": 102 - } - } - ], - "kind": "table_cell", - "span": { - "end": 109, - "start": 101 - } - } - ], - "header": true, - "kind": "table_row", - "span": { - "end": 110, - "start": 91 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "表格", - "span": { - "end": 129, - "start": 123 - } - } - ], - "kind": "table_cell", - "span": { - "end": 130, - "start": 122 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "不参与叙述比例", - "span": { - "end": 153, - "start": 132 - } - } - ], - "kind": "table_cell", - "span": { - "end": 154, - "start": 131 - } - } - ], - "header": false, - "kind": "table_row", - "span": { - "end": 155, - "start": 121 - } - } - ], - "kind": "table", - "span": { - "end": 155, - "start": 91 - } - } - ], - "kind": "document", - "span": { - "end": 155, - "start": 0 - } - }, - "command": "inspect", - "module": "root:default::knowledge.mq.md" -} diff --git a/tests/fixtures/golden/unicode.analysis.json b/tests/fixtures/golden/unicode.analysis.json deleted file mode 100644 index d2f1d21..0000000 --- a/tests/fixtures/golden/unicode.analysis.json +++ /dev/null @@ -1,140 +0,0 @@ -{ - "diagnostics": [], - "modules": [ - { - "calls": [], - "functions": [ - { - "body": [ - { - "kind": "assign", - "span": { - "end": 116, - "start": 98 - }, - "target": "结果", - "value": { - "kind": "binary", - "left": { - "kind": "variable", - "name": "x", - "span": { - "end": 110, - "start": 109 - } - }, - "op": "add", - "right": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "int", - "value": "1" - }, - "span": { - "end": 114, - "start": 109 - } - } - }, - { - "kind": "return", - "span": { - "end": 156, - "start": 141 - }, - "value": { - "kind": "variable", - "name": "结果", - "span": { - "end": 155, - "start": 149 - } - } - } - ], - "effects": [ - "unknown" - ], - "heading_span": { - "end": 22, - "start": 0 - }, - "id": "root:default::unicode.mq.md::多字节😀", - "local_name": "多字节😀", - "namespace": null, - "signature": { - "kind": "explicit", - "params": [ - { - "default": null, - "name": "x", - "required": true, - "span": { - "end": 93, - "start": 87 - }, - "type": "Int" - } - ] - }, - "span": { - "end": 156, - "start": 0 - }, - "unit_id": "root:default::unicode.mq.md#多字节😀" - } - ], - "id": "root:default::unicode.mq.md", - "imports": [], - "package_instance_id": "root:default", - "references": [], - "relative_path": "unicode.mq.md", - "resources": [], - "source_digest": "07464d28973b2a7ed9e1d96ed689104239bb61863c90922d74a9f230e73b1bee", - "units": [ - { - "function": null, - "id": "root:default::unicode.mq.md#", - "kind": "root", - "level": 0, - "name": "", - "span": { - "end": 156, - "start": 0 - } - }, - { - "function": "root:default::unicode.mq.md::多字节😀", - "id": "root:default::unicode.mq.md#多字节😀", - "kind": "function", - "level": 2, - "name": "多字节😀", - "span": { - "end": 22, - "start": 0 - } - } - ] - } - ], - "producer": { - "markdown_profile": "marqdo.md.v1", - "name": "marqdo", - "version": "3.0.0-rc.1" - }, - "project": { - "identity_kind": "workspace_snapshot", - "lock_digest": "", - "root_id": "sha256:6bc3c991a61f2f39ae5c8a58f02c1d860b6bcc3d9df547a3b24ff61bcb47f072", - "stdlib": { - "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "version": "0.1.0" - } - }, - "schema": "marqdo.analysis", - "schema_version": 2 -} \ No newline at end of file diff --git a/tests/fixtures/golden/unicode.ast.json b/tests/fixtures/golden/unicode.ast.json deleted file mode 100644 index 565b020..0000000 --- a/tests/fixtures/golden/unicode.ast.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "ast": { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "@exec 多字节😀", - "span": { - "end": 22, - "start": 3 - } - } - ], - "kind": "heading", - "level": 2, - "setext": false, - "span": { - "end": 22, - "start": 0 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "中文说明与 emoji 😀 用于验证精确位置。", - "span": { - "end": 78, - "start": 24 - } - } - ], - "kind": "paragraph", - "span": { - "end": 78, - "start": 24 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "params(x: Int)", - "span": { - "end": 96, - "start": 80 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 96, - "start": 80 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "结果 = x + 1", - "span": { - "end": 114, - "start": 100 - } - } - ], - "kind": "strong", - "span": { - "end": 116, - "start": 98 - } - } - ], - "kind": "paragraph", - "span": { - "end": 116, - "start": 98 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "返回整数结果。", - "span": { - "end": 139, - "start": 118 - } - } - ], - "kind": "paragraph", - "span": { - "end": 139, - "start": 118 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "return 结果", - "span": { - "end": 155, - "start": 142 - } - } - ], - "kind": "emph", - "span": { - "end": 156, - "start": 141 - } - } - ], - "kind": "paragraph", - "span": { - "end": 156, - "start": 141 - } - } - ], - "kind": "document", - "span": { - "end": 156, - "start": 0 - } - }, - "command": "inspect", - "module": "root:default::unicode.mq.md" -} diff --git a/tests/fixtures/rc2/loop-jumps.analysis.json b/tests/fixtures/rc2/loop-jumps.analysis.json deleted file mode 100644 index 58969dd..0000000 --- a/tests/fixtures/rc2/loop-jumps.analysis.json +++ /dev/null @@ -1,263 +0,0 @@ -{ - "diagnostics": [], - "modules": [ - { - "calls": [], - "functions": [ - { - "body": [ - { - "body": [ - { - "arms": [ - { - "body": [ - { - "kind": "continue", - "span": { - "end": 183, - "start": 173 - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": false - }, - "condition_span": { - "end": 127, - "start": 117 - }, - "span": { - "end": 127, - "start": 117 - } - }, - { - "body": [ - { - "body": [ - { - "kind": "break", - "span": { - "end": 313, - "start": 306 - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": true - }, - "condition_span": { - "end": 264, - "start": 252 - }, - "kind": "loop", - "span": { - "end": 264, - "start": 252 - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": true - }, - "condition_span": { - "end": 204, - "start": 190 - }, - "span": { - "end": 204, - "start": 190 - } - }, - { - "body": [ - { - "body": [ - { - "kind": "continue", - "span": { - "end": 483, - "start": 473 - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": false - }, - "condition_span": { - "end": 428, - "start": 415 - }, - "kind": "loop", - "span": { - "end": 428, - "start": 415 - } - }, - { - "kind": "break", - "span": { - "end": 511, - "start": 504 - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": true - }, - "condition_span": { - "end": 340, - "start": 334 - }, - "span": { - "end": 340, - "start": 334 - } - } - ], - "kind": "branch", - "span": { - "end": 127, - "start": 117 - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": false - }, - "condition_span": { - "end": 83, - "start": 70 - }, - "kind": "loop", - "span": { - "end": 83, - "start": 70 - } - }, - { - "kind": "return", - "span": { - "end": 541, - "start": 531 - }, - "value": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "int", - "value": "0" - } - } - ], - "effects": [ - "unknown" - ], - "heading_span": { - "end": 13, - "start": 0 - }, - "id": "root:default::loop-jumps.mq.md::main", - "local_name": "main", - "namespace": null, - "signature": { - "kind": "inferred", - "params": [] - }, - "span": { - "end": 564, - "start": 0 - }, - "unit_id": "root:default::loop-jumps.mq.md#main" - } - ], - "id": "root:default::loop-jumps.mq.md", - "imports": [], - "package_instance_id": "root:default", - "references": [], - "relative_path": "loop-jumps.mq.md", - "resources": [], - "source_digest": "d80d0b20f64e49679204c4adff7829e14199645e0a4ea14fb72289aa30b4aa4e", - "units": [ - { - "function": null, - "id": "root:default::loop-jumps.mq.md#", - "kind": "root", - "level": 0, - "name": "", - "span": { - "end": 564, - "start": 0 - } - }, - { - "function": "root:default::loop-jumps.mq.md::main", - "id": "root:default::loop-jumps.mq.md#main", - "kind": "function", - "level": 2, - "name": "main", - "span": { - "end": 13, - "start": 0 - } - } - ] - } - ], - "producer": { - "markdown_profile": "marqdo.md.v1", - "name": "marqdo", - "version": "3.0.0-rc.2" - }, - "project": { - "identity_kind": "workspace_snapshot", - "lock_digest": "", - "root_id": "sha256:752dbbeecd08cab15611883971c53d36e4e0ed4346108c86d45a1028e065ee1e", - "stdlib": { - "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "version": "0.1.0" - } - }, - "schema": "marqdo.analysis", - "schema_version": 3 -} \ No newline at end of file diff --git a/tests/fixtures/rc2/loop-jumps.ast.json b/tests/fixtures/rc2/loop-jumps.ast.json deleted file mode 100644 index e1eddb4..0000000 --- a/tests/fixtures/rc2/loop-jumps.ast.json +++ /dev/null @@ -1,491 +0,0 @@ -{ - "ast": { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "@exec main", - "span": { - "end": 13, - "start": 3 - } - } - ], - "kind": "heading", - "level": 2, - "setext": false, - "span": { - "end": 13, - "start": 0 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "在内外两层循环中分别检查控制跳转。", - "span": { - "end": 66, - "start": 15 - } - } - ], - "kind": "paragraph", - "span": { - "end": 66, - "start": 15 - } - }, - { - "children": [ - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "while false", - "span": { - "end": 83, - "start": 70 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":先判定外层条件。", - "span": { - "end": 110, - "start": 83 - } - } - ], - "kind": "paragraph", - "span": { - "end": 110, - "start": 70 - } - }, - { - "children": [ - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "if false", - "span": { - "end": 127, - "start": 117 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":进入首臂时继续外层循环。", - "span": { - "end": 166, - "start": 127 - } - } - ], - "kind": "paragraph", - "span": { - "end": 166, - "start": 117 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "continue", - "span": { - "end": 183, - "start": 173 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 183, - "start": 173 - } - } - ], - "kind": "item", - "span": { - "end": 183, - "start": 114 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "else if true", - "span": { - "end": 204, - "start": 190 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":进入次臂时停止内层循环。", - "span": { - "end": 243, - "start": 204 - } - } - ], - "kind": "paragraph", - "span": { - "end": 243, - "start": 190 - } - }, - { - "children": [ - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "while true", - "span": { - "end": 264, - "start": 252 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":内层循环只读取一次。", - "span": { - "end": 297, - "start": 264 - } - } - ], - "kind": "paragraph", - "span": { - "end": 297, - "start": 252 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "break", - "span": { - "end": 313, - "start": 306 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 313, - "start": 306 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "end", - "span": { - "end": 327, - "start": 322 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 327, - "start": 322 - } - } - ], - "kind": "item", - "span": { - "end": 327, - "start": 250 - } - } - ], - "kind": "list", - "ordered": false, - "span": { - "end": 327, - "start": 250 - }, - "tight": false - } - ], - "kind": "item", - "span": { - "end": 327, - "start": 187 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "else", - "span": { - "end": 340, - "start": 334 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":进入末臂时先继续内层循环,再到外层关闭处。", - "span": { - "end": 406, - "start": 340 - } - } - ], - "kind": "paragraph", - "span": { - "end": 406, - "start": 334 - } - }, - { - "children": [ - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "while false", - "span": { - "end": 428, - "start": 415 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":内层条件成立时才跳转。", - "span": { - "end": 464, - "start": 428 - } - } - ], - "kind": "paragraph", - "span": { - "end": 464, - "start": 415 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "continue", - "span": { - "end": 483, - "start": 473 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 483, - "start": 473 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "end", - "span": { - "end": 497, - "start": 492 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 497, - "start": 492 - } - } - ], - "kind": "item", - "span": { - "end": 497, - "start": 413 - } - } - ], - "kind": "list", - "ordered": false, - "span": { - "end": 497, - "start": 413 - }, - "tight": false - }, - { - "children": [ - { - "kind": "code", - "literal": "break", - "span": { - "end": 511, - "start": 504 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 511, - "start": 504 - } - } - ], - "kind": "item", - "span": { - "end": 511, - "start": 331 - } - } - ], - "kind": "list", - "ordered": true, - "span": { - "end": 511, - "start": 114 - }, - "start": 1, - "tight": false - }, - { - "children": [ - { - "kind": "code", - "literal": "end", - "span": { - "end": 520, - "start": 515 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 520, - "start": 515 - } - }, - { - "children": [ - { - "kind": "code", - "literal": "end", - "span": { - "end": 529, - "start": 524 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 529, - "start": 524 - } - } - ], - "kind": "item", - "span": { - "end": 529, - "start": 68 - } - } - ], - "kind": "list", - "ordered": false, - "span": { - "end": 529, - "start": 68 - }, - "tight": false - }, - { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "return 0", - "span": { - "end": 540, - "start": 532 - } - } - ], - "kind": "emph", - "span": { - "end": 541, - "start": 531 - } - } - ], - "kind": "paragraph", - "span": { - "end": 541, - "start": 531 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "返回扫描结果。", - "span": { - "end": 564, - "start": 543 - } - } - ], - "kind": "paragraph", - "span": { - "end": 564, - "start": 543 - } - } - ], - "kind": "document", - "span": { - "end": 564, - "start": 0 - } - }, - "command": "inspect", - "module": "root:default::loop-jumps.mq.md" -} diff --git a/tests/fixtures/rc2/multi-arm.analysis.json b/tests/fixtures/rc2/multi-arm.analysis.json deleted file mode 100644 index 2a2d56b..0000000 --- a/tests/fixtures/rc2/multi-arm.analysis.json +++ /dev/null @@ -1,238 +0,0 @@ -{ - "diagnostics": [], - "modules": [ - { - "calls": [], - "functions": [ - { - "body": [ - { - "arms": [ - { - "body": [ - { - "kind": "return", - "span": { - "end": 107, - "start": 97 - }, - "value": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "int", - "value": "1" - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": false - }, - "condition_span": { - "end": 75, - "start": 65 - }, - "span": { - "end": 75, - "start": 65 - } - }, - { - "body": [ - { - "kind": "return", - "span": { - "end": 175, - "start": 165 - }, - "value": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "int", - "value": "2" - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": true - }, - "condition_span": { - "end": 125, - "start": 111 - }, - "span": { - "end": 125, - "start": 111 - } - }, - { - "body": [ - { - "kind": "return", - "span": { - "end": 232, - "start": 222 - }, - "value": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "int", - "value": "3" - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": false - }, - "condition_span": { - "end": 194, - "start": 179 - }, - "span": { - "end": 194, - "start": 179 - } - }, - { - "body": [ - { - "kind": "return", - "span": { - "end": 310, - "start": 300 - }, - "value": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "int", - "value": "4" - } - } - ], - "condition": { - "kind": "literal", - "span": { - "end": 0, - "start": 0 - }, - "type": "bool", - "value": true - }, - "condition_span": { - "end": 242, - "start": 236 - }, - "span": { - "end": 242, - "start": 236 - } - } - ], - "kind": "branch", - "span": { - "end": 75, - "start": 65 - } - } - ], - "effects": [ - "unknown" - ], - "heading_span": { - "end": 13, - "start": 0 - }, - "id": "root:default::multi-arm.mq.md::main", - "local_name": "main", - "namespace": null, - "signature": { - "kind": "inferred", - "params": [] - }, - "span": { - "end": 317, - "start": 0 - }, - "unit_id": "root:default::multi-arm.mq.md#main" - } - ], - "id": "root:default::multi-arm.mq.md", - "imports": [], - "package_instance_id": "root:default", - "references": [], - "relative_path": "multi-arm.mq.md", - "resources": [], - "source_digest": "92485c1da250e6658de4908bf4b49156b2094188d0aa02cb133c8388a116f3e0", - "units": [ - { - "function": null, - "id": "root:default::multi-arm.mq.md#", - "kind": "root", - "level": 0, - "name": "", - "span": { - "end": 317, - "start": 0 - } - }, - { - "function": "root:default::multi-arm.mq.md::main", - "id": "root:default::multi-arm.mq.md#main", - "kind": "function", - "level": 2, - "name": "main", - "span": { - "end": 13, - "start": 0 - } - } - ] - } - ], - "producer": { - "markdown_profile": "marqdo.md.v1", - "name": "marqdo", - "version": "3.0.0-rc.2" - }, - "project": { - "identity_kind": "workspace_snapshot", - "lock_digest": "", - "root_id": "sha256:cceb51765cdfc58898339ca161c0d61b93d2218dd4505dcfee0779c87ef1d303", - "stdlib": { - "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", - "version": "0.1.0" - } - }, - "schema": "marqdo.analysis", - "schema_version": 2 -} \ No newline at end of file diff --git a/tests/fixtures/rc2/multi-arm.ast.json b/tests/fixtures/rc2/multi-arm.ast.json deleted file mode 100644 index 65b8023..0000000 --- a/tests/fixtures/rc2/multi-arm.ast.json +++ /dev/null @@ -1,315 +0,0 @@ -{ - "ast": { - "children": [ - { - "children": [ - { - "kind": "text", - "literal": "@exec main", - "span": { - "end": 13, - "start": 3 - } - } - ], - "kind": "heading", - "level": 2, - "setext": false, - "span": { - "end": 13, - "start": 0 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "根据输入条件依次选择一个结果。", - "span": { - "end": 60, - "start": 15 - } - } - ], - "kind": "paragraph", - "span": { - "end": 60, - "start": 15 - } - }, - { - "children": [ - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "if false", - "span": { - "end": 75, - "start": 65 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":首个条件。", - "span": { - "end": 93, - "start": 75 - } - }, - { - "kind": "soft_break", - "span": { - "end": 94, - "start": 93 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "return 1", - "span": { - "end": 106, - "start": 98 - } - } - ], - "kind": "emph", - "span": { - "end": 107, - "start": 97 - } - } - ], - "kind": "paragraph", - "span": { - "end": 107, - "start": 65 - } - } - ], - "kind": "item", - "span": { - "end": 107, - "start": 62 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "else if true", - "span": { - "end": 125, - "start": 111 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":后续条件可以是字面量。", - "span": { - "end": 161, - "start": 125 - } - }, - { - "kind": "soft_break", - "span": { - "end": 162, - "start": 161 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "return 2", - "span": { - "end": 174, - "start": 166 - } - } - ], - "kind": "emph", - "span": { - "end": 175, - "start": 165 - } - } - ], - "kind": "paragraph", - "span": { - "end": 175, - "start": 111 - } - } - ], - "kind": "item", - "span": { - "end": 175, - "start": 108 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "else if false", - "span": { - "end": 194, - "start": 179 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":最后一个条件。", - "span": { - "end": 218, - "start": 194 - } - }, - { - "kind": "soft_break", - "span": { - "end": 219, - "start": 218 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "return 3", - "span": { - "end": 231, - "start": 223 - } - } - ], - "kind": "emph", - "span": { - "end": 232, - "start": 222 - } - } - ], - "kind": "paragraph", - "span": { - "end": 232, - "start": 179 - } - } - ], - "kind": "item", - "span": { - "end": 232, - "start": 176 - } - }, - { - "children": [ - { - "children": [ - { - "kind": "code", - "literal": "else", - "span": { - "end": 242, - "start": 236 - }, - "ticks": 1 - }, - { - "kind": "text", - "literal": ":前面的条件全部不成立时返回默认值。", - "span": { - "end": 296, - "start": 242 - } - }, - { - "kind": "soft_break", - "span": { - "end": 297, - "start": 296 - } - }, - { - "children": [ - { - "kind": "text", - "literal": "return 4", - "span": { - "end": 309, - "start": 301 - } - } - ], - "kind": "emph", - "span": { - "end": 310, - "start": 300 - } - } - ], - "kind": "paragraph", - "span": { - "end": 310, - "start": 236 - } - } - ], - "kind": "item", - "span": { - "end": 310, - "start": 233 - } - } - ], - "kind": "list", - "ordered": true, - "span": { - "end": 310, - "start": 62 - }, - "start": 1, - "tight": true - }, - { - "children": [ - { - "kind": "code", - "literal": "end", - "span": { - "end": 317, - "start": 312 - }, - "ticks": 1 - } - ], - "kind": "paragraph", - "span": { - "end": 317, - "start": 312 - } - } - ], - "kind": "document", - "span": { - "end": 317, - "start": 0 - } - }, - "command": "inspect", - "module": "root:default::multi-arm.mq.md" -} diff --git a/tests/fixtures/rc4/bom.analysis.json b/tests/fixtures/rc4/bom.analysis.json new file mode 100644 index 0000000..fb6d792 --- /dev/null +++ b/tests/fixtures/rc4/bom.analysis.json @@ -0,0 +1,227 @@ +{ + "schema": "marqdo.analysis", + "schema_version": 3, + "producer": { + "name": "marqdo", + "version": "3.0.0-rc.4", + "markdown_profile": "marqdo.md.v1" + }, + "project": { + "root_id": "sha256:09c24ef9d9b03ffcb4fcf8ff3d40306d47c7c6cbcfb151837edad217d1e70921", + "identity_kind": "workspace_snapshot", + "entry_module_id": "root:default::bom.mq.md", + "lock_digest": "", + "manifest_digest": "", + "stdlib": { + "version": "0.1.0", + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713" + }, + "extensions": [] + }, + "modules": [ + { + "id": "root:default::bom.mq.md", + "package_instance_id": "root:default", + "relative_path": "bom.mq.md", + "source_digest": "b7973730c6130d1f555e78d0685b495fdc70d9a5e76755dd1700a74c761bc802", + "source": "## @exec BOM位置\n\nBOM 后的中文 span 仍相对原始字节。\n\n`params(x: Int)`\n\n*return x*\n", + "document": { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@exec BOM位置", + "span": { + "end": 21, + "start": 6 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 21, + "start": 3 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "BOM 后的中文 span 仍相对原始字节。", + "span": { + "end": 69, + "start": 23 + } + } + ], + "kind": "paragraph", + "span": { + "end": 69, + "start": 23 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "params(x: Int)", + "span": { + "end": 87, + "start": 71 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 87, + "start": 71 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "return x", + "span": { + "end": 98, + "start": 90 + } + } + ], + "kind": "emph", + "span": { + "end": 99, + "start": 89 + } + } + ], + "kind": "paragraph", + "span": { + "end": 99, + "start": 89 + } + } + ], + "kind": "document", + "span": { + "end": 100, + "start": 0 + } + }, + "units": [ + { + "id": "root:default::bom.mq.md#", + "path": [], + "parent_id": null, + "kind": "root", + "name": "", + "level": 0, + "mode": "knowledge", + "mode_origin": "default", + "mode_source_unit_id": "root:default::bom.mq.md#", + "heading_span": null, + "span": { + "start": 0, + "end": 100 + }, + "function": null + }, + { + "id": "root:default::bom.mq.md#BOM位置", + "path": [ + "BOM位置" + ], + "parent_id": "root:default::bom.mq.md#", + "kind": "function", + "name": "BOM位置", + "level": 2, + "mode": "exec", + "mode_origin": "explicit", + "mode_source_unit_id": "root:default::bom.mq.md#BOM位置", + "heading_span": { + "start": 3, + "end": 21 + }, + "span": { + "start": 3, + "end": 100 + }, + "function": "root:default::bom.mq.md::BOM位置" + } + ], + "anchors": [ + { + "anchor": "bom位置", + "unit_id": "root:default::bom.mq.md#BOM位置" + } + ], + "functions": [ + { + "id": "root:default::bom.mq.md::BOM位置", + "unit_id": "root:default::bom.mq.md#BOM位置", + "local_name": "BOM位置", + "namespace": null, + "span": { + "start": 3, + "end": 99 + }, + "heading_span": { + "start": 3, + "end": 21 + }, + "signature": { + "kind": "explicit", + "params": [ + { + "name": "x", + "required": true, + "type": "Int", + "default": null, + "span": { + "start": 78, + "end": 84 + } + } + ] + }, + "effects": [ + "unknown" + ], + "body": [ + { + "kind": "return", + "span": { + "end": 99, + "start": 89 + }, + "value": { + "kind": "variable", + "name": "x", + "span": { + "end": 98, + "start": 97 + } + } + } + ] + } + ], + "imports": [], + "references": [], + "calls": [], + "resources": [] + } + ], + "diagnostics": [] +} \ No newline at end of file diff --git a/tests/fixtures/rc4/branches.analysis.json b/tests/fixtures/rc4/branches.analysis.json new file mode 100644 index 0000000..03d875a --- /dev/null +++ b/tests/fixtures/rc4/branches.analysis.json @@ -0,0 +1,598 @@ +{ + "schema": "marqdo.analysis", + "schema_version": 3, + "producer": { + "name": "marqdo", + "version": "3.0.0-rc.4", + "markdown_profile": "marqdo.md.v1" + }, + "project": { + "root_id": "sha256:9dbd8404c6a0bf58390c673052d0076cfcb787646c0ffdb27a30837ef142273d", + "identity_kind": "workspace_snapshot", + "entry_module_id": "root:default::branches.mq.md", + "lock_digest": "", + "manifest_digest": "", + "stdlib": { + "version": "0.1.0", + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713" + }, + "extensions": [] + }, + "modules": [ + { + "id": "root:default::branches.mq.md", + "package_instance_id": "root:default", + "relative_path": "branches.mq.md", + "source_digest": "dcc2c9869c5f2a53cff5a2c479e67143b9b0617ffe0b605bf920a7322d85aa3f", + "source": "# @knowledge 协议样例\n\n## @exec 判断正负\n\n根据整数是否为正返回一或零,结果没有单位。\n\n`params(x: Int)`\n\n**结果 = 0**\n\n1. `if x > 0`:正数返回一。\n\n **结果 = 1**\n\n2. `else`:零和负数返回零。\n\n **结果 = 0**\n\n`end`\n\n返回整数结果。\n\n*return 结果*\n", + "document": { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@knowledge 协议样例", + "span": { + "end": 25, + "start": 2 + } + } + ], + "kind": "heading", + "level": 1, + "setext": false, + "span": { + "end": 25, + "start": 0 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@exec 判断正负", + "span": { + "end": 48, + "start": 30 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 48, + "start": 27 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "根据整数是否为正返回一或零,结果没有单位。", + "span": { + "end": 113, + "start": 50 + } + } + ], + "kind": "paragraph", + "span": { + "end": 113, + "start": 50 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "params(x: Int)", + "span": { + "end": 131, + "start": 115 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 131, + "start": 115 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "结果 = 0", + "span": { + "end": 145, + "start": 135 + } + } + ], + "kind": "strong", + "span": { + "end": 147, + "start": 133 + } + } + ], + "kind": "paragraph", + "span": { + "end": 147, + "start": 133 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "if x > 0", + "span": { + "end": 162, + "start": 152 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":正数返回一。", + "span": { + "end": 183, + "start": 162 + } + } + ], + "kind": "paragraph", + "span": { + "end": 183, + "start": 152 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "结果 = 1", + "span": { + "end": 200, + "start": 190 + } + } + ], + "kind": "strong", + "span": { + "end": 202, + "start": 188 + } + } + ], + "kind": "paragraph", + "span": { + "end": 202, + "start": 188 + } + } + ], + "kind": "item", + "span": { + "end": 202, + "start": 149 + }, + "task": null + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "else", + "span": { + "end": 213, + "start": 207 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":零和负数返回零。", + "span": { + "end": 240, + "start": 213 + } + } + ], + "kind": "paragraph", + "span": { + "end": 240, + "start": 207 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "结果 = 0", + "span": { + "end": 257, + "start": 247 + } + } + ], + "kind": "strong", + "span": { + "end": 259, + "start": 245 + } + } + ], + "kind": "paragraph", + "span": { + "end": 259, + "start": 245 + } + } + ], + "kind": "item", + "span": { + "end": 259, + "start": 204 + }, + "task": null + } + ], + "kind": "list", + "ordered": true, + "span": { + "end": 259, + "start": 149 + }, + "start": 1, + "tight": false + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "end", + "span": { + "end": 266, + "start": 261 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 266, + "start": 261 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "返回整数结果。", + "span": { + "end": 289, + "start": 268 + } + } + ], + "kind": "paragraph", + "span": { + "end": 289, + "start": 268 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "return 结果", + "span": { + "end": 305, + "start": 292 + } + } + ], + "kind": "emph", + "span": { + "end": 306, + "start": 291 + } + } + ], + "kind": "paragraph", + "span": { + "end": 306, + "start": 291 + } + } + ], + "kind": "document", + "span": { + "end": 307, + "start": 0 + } + }, + "units": [ + { + "id": "root:default::branches.mq.md#", + "path": [], + "parent_id": null, + "kind": "root", + "name": "", + "level": 0, + "mode": "knowledge", + "mode_origin": "default", + "mode_source_unit_id": "root:default::branches.mq.md#", + "heading_span": null, + "span": { + "start": 0, + "end": 307 + }, + "function": null + }, + { + "id": "root:default::branches.mq.md#协议样例", + "path": [ + "协议样例" + ], + "parent_id": "root:default::branches.mq.md#", + "kind": "namespace", + "name": "协议样例", + "level": 1, + "mode": "knowledge", + "mode_origin": "explicit", + "mode_source_unit_id": "root:default::branches.mq.md#协议样例", + "heading_span": { + "start": 0, + "end": 25 + }, + "span": { + "start": 0, + "end": 307 + }, + "function": null + }, + { + "id": "root:default::branches.mq.md#协议样例/判断正负", + "path": [ + "协议样例", + "判断正负" + ], + "parent_id": "root:default::branches.mq.md#协议样例", + "kind": "function", + "name": "判断正负", + "level": 2, + "mode": "exec", + "mode_origin": "explicit", + "mode_source_unit_id": "root:default::branches.mq.md#协议样例/判断正负", + "heading_span": { + "start": 27, + "end": 48 + }, + "span": { + "start": 27, + "end": 307 + }, + "function": "root:default::branches.mq.md::协议样例.判断正负" + } + ], + "anchors": [ + { + "anchor": "判断正负", + "unit_id": "root:default::branches.mq.md#协议样例/判断正负" + }, + { + "anchor": "协议样例", + "unit_id": "root:default::branches.mq.md#协议样例" + } + ], + "functions": [ + { + "id": "root:default::branches.mq.md::协议样例.判断正负", + "unit_id": "root:default::branches.mq.md#协议样例/判断正负", + "local_name": "判断正负", + "namespace": "协议样例", + "span": { + "start": 27, + "end": 306 + }, + "heading_span": { + "start": 27, + "end": 48 + }, + "signature": { + "kind": "explicit", + "params": [ + { + "name": "x", + "required": true, + "type": "Int", + "default": null, + "span": { + "start": 122, + "end": 128 + } + } + ] + }, + "effects": [ + "unknown" + ], + "body": [ + { + "kind": "assign", + "span": { + "end": 147, + "start": 133 + }, + "target": "结果", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + } + }, + { + "arms": [ + { + "body": [ + { + "kind": "assign", + "span": { + "end": 202, + "start": 188 + }, + "target": "结果", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "1" + } + } + ], + "condition": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "x", + "span": { + "end": 157, + "start": 156 + } + }, + "op": "gt", + "right": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + }, + "span": { + "end": 161, + "start": 156 + } + }, + "condition_span": { + "end": 162, + "start": 152 + }, + "span": { + "end": 162, + "start": 152 + } + }, + { + "body": [ + { + "kind": "assign", + "span": { + "end": 259, + "start": 245 + }, + "target": "结果", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": true + }, + "condition_span": { + "end": 213, + "start": 207 + }, + "span": { + "end": 213, + "start": 207 + } + } + ], + "kind": "branch", + "span": { + "end": 162, + "start": 152 + } + }, + { + "kind": "return", + "span": { + "end": 306, + "start": 291 + }, + "value": { + "kind": "variable", + "name": "结果", + "span": { + "end": 305, + "start": 299 + } + } + } + ] + } + ], + "imports": [], + "references": [], + "calls": [], + "resources": [] + } + ], + "diagnostics": [] +} \ No newline at end of file diff --git a/tests/fixtures/rc4/inventory.analysis.json b/tests/fixtures/rc4/inventory.analysis.json new file mode 100644 index 0000000..2c7e5f7 --- /dev/null +++ b/tests/fixtures/rc4/inventory.analysis.json @@ -0,0 +1,956 @@ +{ + "schema": "marqdo.analysis", + "schema_version": 3, + "producer": { + "name": "marqdo", + "version": "3.0.0-rc.4", + "markdown_profile": "marqdo.md.v1" + }, + "project": { + "root_id": "sha256:523cace2b93bc16e3cf77377d074456c27f8f4bee0e5ee5700b50d6d639945e8", + "identity_kind": "workspace_snapshot", + "entry_module_id": "root:default::inventory.mq.md", + "lock_digest": "", + "manifest_digest": "", + "stdlib": { + "version": "0.1.0", + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713" + }, + "extensions": [] + }, + "modules": [ + { + "id": "root:default::inventory.mq.md", + "package_instance_id": "root:default", + "relative_path": "inventory.mq.md", + "source_digest": "34f0bdc21059a64d081f4db011ee1e259fd7d92686e1928f21374ec05a6bd065", + "source": "# @knowledge 库存示例\n\n## @exec 检查库存并累计可用量\n\n只在仓库启用时统计库存;对每个未统计条目进行累计。\n位置从零下标开始,返回最小计量单位的总量。\n\n`params(仓库启用: Bool, 数量列表: List)`\n\n**总量 = 0**\n\n**位置 = 0**\n\n### 逐项汇总\n\n1. `if 仓库启用`:仅在启用状态下统计库存。\n\n - `while 位置 < 长度(数量列表)`:按位置依次统计,到达列表末尾时终止。\n\n 位置始终指向第一个尚未统计的条目,先读取当前位置再前进,避免漏计首项。\n\n **总量 = 总量 + 数量列表[位置]**\n\n **位置 = 位置 + 1**\n\n `end`\n\n2. `else`:仓库未启用时,总量保持为零。\n\n 不执行任何库存统计。\n\n`end`\n\n### 汇总结果\n\n返回累计总量;本函数不会修改库存来源。\n\n*return 总量*\n", + "document": { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@knowledge 库存示例", + "span": { + "end": 25, + "start": 2 + } + } + ], + "kind": "heading", + "level": 1, + "setext": false, + "span": { + "end": 25, + "start": 0 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@exec 检查库存并累计可用量", + "span": { + "end": 66, + "start": 30 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 66, + "start": 27 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "只在仓库启用时统计库存;对每个未统计条目进行累计。", + "span": { + "end": 143, + "start": 68 + } + }, + { + "children": [], + "kind": "soft_break", + "span": { + "end": 144, + "start": 143 + } + }, + { + "children": [], + "kind": "text", + "literal": "位置从零下标开始,返回最小计量单位的总量。", + "span": { + "end": 207, + "start": 144 + } + } + ], + "kind": "paragraph", + "span": { + "end": 207, + "start": 68 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "params(仓库启用: Bool, 数量列表: List)", + "span": { + "end": 257, + "start": 209 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 257, + "start": 209 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "总量 = 0", + "span": { + "end": 271, + "start": 261 + } + } + ], + "kind": "strong", + "span": { + "end": 273, + "start": 259 + } + } + ], + "kind": "paragraph", + "span": { + "end": 273, + "start": 259 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "位置 = 0", + "span": { + "end": 287, + "start": 277 + } + } + ], + "kind": "strong", + "span": { + "end": 289, + "start": 275 + } + } + ], + "kind": "paragraph", + "span": { + "end": 289, + "start": 275 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "逐项汇总", + "span": { + "end": 307, + "start": 295 + } + } + ], + "kind": "heading", + "level": 3, + "setext": false, + "span": { + "end": 307, + "start": 291 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "if 仓库启用", + "span": { + "end": 329, + "start": 312 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":仅在启用状态下统计库存。", + "span": { + "end": 368, + "start": 329 + } + } + ], + "kind": "paragraph", + "span": { + "end": 368, + "start": 312 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "while 位置 < 长度(数量列表)", + "span": { + "end": 412, + "start": 375 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":按位置依次统计,到达列表末尾时终止。", + "span": { + "end": 469, + "start": 412 + } + } + ], + "kind": "paragraph", + "span": { + "end": 469, + "start": 375 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "位置始终指向第一个尚未统计的条目,先读取当前位置再前进,避免漏计首项。", + "span": { + "end": 581, + "start": 476 + } + } + ], + "kind": "paragraph", + "span": { + "end": 581, + "start": 476 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "总量 = 总量 + 数量列表[位置]", + "span": { + "end": 628, + "start": 590 + } + } + ], + "kind": "strong", + "span": { + "end": 630, + "start": 588 + } + } + ], + "kind": "paragraph", + "span": { + "end": 630, + "start": 588 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "位置 = 位置 + 1", + "span": { + "end": 658, + "start": 639 + } + } + ], + "kind": "strong", + "span": { + "end": 660, + "start": 637 + } + } + ], + "kind": "paragraph", + "span": { + "end": 660, + "start": 637 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "end", + "span": { + "end": 672, + "start": 667 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 672, + "start": 667 + } + } + ], + "kind": "item", + "span": { + "end": 672, + "start": 373 + }, + "task": null + } + ], + "kind": "list", + "ordered": false, + "span": { + "end": 672, + "start": 373 + }, + "start": null, + "tight": false + } + ], + "kind": "item", + "span": { + "end": 672, + "start": 309 + }, + "task": null + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "else", + "span": { + "end": 683, + "start": 677 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":仓库未启用时,总量保持为零。", + "span": { + "end": 728, + "start": 683 + } + } + ], + "kind": "paragraph", + "span": { + "end": 728, + "start": 677 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "不执行任何库存统计。", + "span": { + "end": 763, + "start": 733 + } + } + ], + "kind": "paragraph", + "span": { + "end": 763, + "start": 733 + } + } + ], + "kind": "item", + "span": { + "end": 763, + "start": 674 + }, + "task": null + } + ], + "kind": "list", + "ordered": true, + "span": { + "end": 763, + "start": 309 + }, + "start": 1, + "tight": false + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "end", + "span": { + "end": 770, + "start": 765 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 770, + "start": 765 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "汇总结果", + "span": { + "end": 788, + "start": 776 + } + } + ], + "kind": "heading", + "level": 3, + "setext": false, + "span": { + "end": 788, + "start": 772 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "返回累计总量;本函数不会修改库存来源。", + "span": { + "end": 847, + "start": 790 + } + } + ], + "kind": "paragraph", + "span": { + "end": 847, + "start": 790 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "return 总量", + "span": { + "end": 863, + "start": 850 + } + } + ], + "kind": "emph", + "span": { + "end": 864, + "start": 849 + } + } + ], + "kind": "paragraph", + "span": { + "end": 864, + "start": 849 + } + } + ], + "kind": "document", + "span": { + "end": 865, + "start": 0 + } + }, + "units": [ + { + "id": "root:default::inventory.mq.md#", + "path": [], + "parent_id": null, + "kind": "root", + "name": "", + "level": 0, + "mode": "knowledge", + "mode_origin": "default", + "mode_source_unit_id": "root:default::inventory.mq.md#", + "heading_span": null, + "span": { + "start": 0, + "end": 865 + }, + "function": null + }, + { + "id": "root:default::inventory.mq.md#库存示例", + "path": [ + "库存示例" + ], + "parent_id": "root:default::inventory.mq.md#", + "kind": "namespace", + "name": "库存示例", + "level": 1, + "mode": "knowledge", + "mode_origin": "explicit", + "mode_source_unit_id": "root:default::inventory.mq.md#库存示例", + "heading_span": { + "start": 0, + "end": 25 + }, + "span": { + "start": 0, + "end": 865 + }, + "function": null + }, + { + "id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量", + "path": [ + "库存示例", + "检查库存并累计可用量" + ], + "parent_id": "root:default::inventory.mq.md#库存示例", + "kind": "function", + "name": "检查库存并累计可用量", + "level": 2, + "mode": "exec", + "mode_origin": "explicit", + "mode_source_unit_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量", + "heading_span": { + "start": 27, + "end": 66 + }, + "span": { + "start": 27, + "end": 865 + }, + "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量" + }, + { + "id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量/逐项汇总", + "path": [ + "库存示例", + "检查库存并累计可用量", + "逐项汇总" + ], + "parent_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量", + "kind": "section", + "name": "逐项汇总", + "level": 3, + "mode": "exec", + "mode_origin": "inherited", + "mode_source_unit_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量", + "heading_span": { + "start": 291, + "end": 307 + }, + "span": { + "start": 291, + "end": 772 + }, + "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量" + }, + { + "id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量/汇总结果", + "path": [ + "库存示例", + "检查库存并累计可用量", + "汇总结果" + ], + "parent_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量", + "kind": "section", + "name": "汇总结果", + "level": 3, + "mode": "exec", + "mode_origin": "inherited", + "mode_source_unit_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量", + "heading_span": { + "start": 772, + "end": 788 + }, + "span": { + "start": 772, + "end": 865 + }, + "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量" + } + ], + "anchors": [ + { + "anchor": "库存示例", + "unit_id": "root:default::inventory.mq.md#库存示例" + }, + { + "anchor": "检查库存并累计可用量", + "unit_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量" + }, + { + "anchor": "汇总结果", + "unit_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量/汇总结果" + }, + { + "anchor": "逐项汇总", + "unit_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量/逐项汇总" + } + ], + "functions": [ + { + "id": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", + "unit_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量", + "local_name": "检查库存并累计可用量", + "namespace": "库存示例", + "span": { + "start": 27, + "end": 864 + }, + "heading_span": { + "start": 27, + "end": 66 + }, + "signature": { + "kind": "explicit", + "params": [ + { + "name": "仓库启用", + "required": true, + "type": "Bool", + "default": null, + "span": { + "start": 216, + "end": 234 + } + }, + { + "name": "数量列表", + "required": true, + "type": "List", + "default": null, + "span": { + "start": 235, + "end": 254 + } + } + ] + }, + "effects": [ + "unknown" + ], + "body": [ + { + "kind": "assign", + "span": { + "end": 273, + "start": 259 + }, + "target": "总量", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + } + }, + { + "kind": "assign", + "span": { + "end": 289, + "start": 275 + }, + "target": "位置", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + } + }, + { + "arms": [ + { + "body": [ + { + "body": [ + { + "kind": "assign", + "span": { + "end": 630, + "start": 588 + }, + "target": "总量", + "value": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "总量", + "span": { + "end": 605, + "start": 599 + } + }, + "op": "add", + "right": { + "base": { + "kind": "variable", + "name": "数量列表", + "span": { + "end": 620, + "start": 608 + } + }, + "index": { + "kind": "variable", + "name": "位置", + "span": { + "end": 627, + "start": 621 + } + }, + "kind": "index", + "span": { + "end": 628, + "start": 608 + } + }, + "span": { + "end": 628, + "start": 599 + } + } + }, + { + "kind": "assign", + "span": { + "end": 660, + "start": 637 + }, + "target": "位置", + "value": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "位置", + "span": { + "end": 654, + "start": 648 + } + }, + "op": "add", + "right": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "1" + }, + "span": { + "end": 658, + "start": 648 + } + } + } + ], + "condition": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "位置", + "span": { + "end": 388, + "start": 382 + } + }, + "op": "lt", + "right": { + "args": [ + { + "name": null, + "span": { + "end": 410, + "start": 398 + }, + "value": { + "kind": "variable", + "name": "数量列表", + "span": { + "end": 410, + "start": 398 + } + } + } + ], + "callee": { + "kind": "variable", + "name": "长度", + "span": { + "end": 397, + "start": 391 + } + }, + "kind": "call", + "span": { + "end": 411, + "start": 391 + } + }, + "span": { + "end": 411, + "start": 382 + } + }, + "condition_span": { + "end": 412, + "start": 375 + }, + "kind": "loop", + "span": { + "end": 412, + "start": 375 + } + } + ], + "condition": { + "kind": "variable", + "name": "仓库启用", + "span": { + "end": 328, + "start": 316 + } + }, + "condition_span": { + "end": 329, + "start": 312 + }, + "span": { + "end": 329, + "start": 312 + } + } + ], + "kind": "branch", + "span": { + "end": 329, + "start": 312 + } + }, + { + "kind": "return", + "span": { + "end": 864, + "start": 849 + }, + "value": { + "kind": "variable", + "name": "总量", + "span": { + "end": 863, + "start": 857 + } + } + } + ] + } + ], + "imports": [], + "references": [], + "calls": [ + { + "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", + "span": { + "start": 391, + "end": 411 + }, + "callee": { + "kind": "ident", + "name": "长度" + }, + "state": "builtin", + "target": "长度", + "target_kind": "builtin", + "target_owner": null, + "reason": null + } + ], + "resources": [] + } + ], + "diagnostics": [] +} \ No newline at end of file diff --git a/tests/fixtures/rc4/knowledge.analysis.json b/tests/fixtures/rc4/knowledge.analysis.json new file mode 100644 index 0000000..f37668b --- /dev/null +++ b/tests/fixtures/rc4/knowledge.analysis.json @@ -0,0 +1,309 @@ +{ + "schema": "marqdo.analysis", + "schema_version": 3, + "producer": { + "name": "marqdo", + "version": "3.0.0-rc.4", + "markdown_profile": "marqdo.md.v1" + }, + "project": { + "root_id": "sha256:3cdb7daa24f2c7cda11ed43c931de8f27e3508519c66148759308012ae78930a", + "identity_kind": "workspace_snapshot", + "entry_module_id": "root:default::knowledge.mq.md", + "lock_digest": "", + "manifest_digest": "", + "stdlib": { + "version": "0.1.0", + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713" + }, + "extensions": [] + }, + "modules": [ + { + "id": "root:default::knowledge.mq.md", + "package_instance_id": "root:default", + "relative_path": "knowledge.mq.md", + "source_digest": "342f1937f86ae7b4bfd917ad45b1438b6a6756ecba499b45da5d40e34af3ce5c", + "source": "## @knowledge 富文本\n\n这里的 **加粗**、*斜体* 与 `code` 都是惰性内容。\n\n| 名称 | 说明 |\n|---|---|\n| 表格 | 不参与叙述比例 |\n", + "document": { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@knowledge 富文本", + "span": { + "end": 23, + "start": 3 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 23, + "start": 0 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "这里的 ", + "span": { + "end": 35, + "start": 25 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "加粗", + "span": { + "end": 43, + "start": 37 + } + } + ], + "kind": "strong", + "span": { + "end": 45, + "start": 35 + } + }, + { + "children": [], + "kind": "text", + "literal": "、", + "span": { + "end": 48, + "start": 45 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "斜体", + "span": { + "end": 55, + "start": 49 + } + } + ], + "kind": "emph", + "span": { + "end": 56, + "start": 48 + } + }, + { + "children": [], + "kind": "text", + "literal": " 与 ", + "span": { + "end": 61, + "start": 56 + } + }, + { + "children": [], + "kind": "code", + "literal": "code", + "span": { + "end": 67, + "start": 61 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": " 都是惰性内容。", + "span": { + "end": 89, + "start": 67 + } + } + ], + "kind": "paragraph", + "span": { + "end": 89, + "start": 25 + } + }, + { + "alignments": [ + "none", + "none" + ], + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "名称", + "span": { + "end": 99, + "start": 93 + } + } + ], + "kind": "table_cell", + "span": { + "end": 100, + "start": 92 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "说明", + "span": { + "end": 108, + "start": 102 + } + } + ], + "kind": "table_cell", + "span": { + "end": 109, + "start": 101 + } + } + ], + "header": true, + "kind": "table_row", + "span": { + "end": 110, + "start": 91 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "表格", + "span": { + "end": 129, + "start": 123 + } + } + ], + "kind": "table_cell", + "span": { + "end": 130, + "start": 122 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "不参与叙述比例", + "span": { + "end": 153, + "start": 132 + } + } + ], + "kind": "table_cell", + "span": { + "end": 154, + "start": 131 + } + } + ], + "header": false, + "kind": "table_row", + "span": { + "end": 155, + "start": 121 + } + } + ], + "kind": "table", + "span": { + "end": 155, + "start": 91 + } + } + ], + "kind": "document", + "span": { + "end": 156, + "start": 0 + } + }, + "units": [ + { + "id": "root:default::knowledge.mq.md#", + "path": [], + "parent_id": null, + "kind": "root", + "name": "", + "level": 0, + "mode": "knowledge", + "mode_origin": "default", + "mode_source_unit_id": "root:default::knowledge.mq.md#", + "heading_span": null, + "span": { + "start": 0, + "end": 156 + }, + "function": null + }, + { + "id": "root:default::knowledge.mq.md#富文本", + "path": [ + "富文本" + ], + "parent_id": "root:default::knowledge.mq.md#", + "kind": "knowledge", + "name": "富文本", + "level": 2, + "mode": "knowledge", + "mode_origin": "explicit", + "mode_source_unit_id": "root:default::knowledge.mq.md#富文本", + "heading_span": { + "start": 0, + "end": 23 + }, + "span": { + "start": 0, + "end": 156 + }, + "function": null + } + ], + "anchors": [ + { + "anchor": "富文本", + "unit_id": "root:default::knowledge.mq.md#富文本" + } + ], + "functions": [], + "imports": [], + "references": [], + "calls": [], + "resources": [] + } + ], + "diagnostics": [] +} \ No newline at end of file diff --git a/tests/fixtures/rc4/loop-jumps.analysis.json b/tests/fixtures/rc4/loop-jumps.analysis.json new file mode 100644 index 0000000..cf50069 --- /dev/null +++ b/tests/fixtures/rc4/loop-jumps.analysis.json @@ -0,0 +1,810 @@ +{ + "schema": "marqdo.analysis", + "schema_version": 3, + "producer": { + "name": "marqdo", + "version": "3.0.0-rc.4", + "markdown_profile": "marqdo.md.v1" + }, + "project": { + "root_id": "sha256:752dbbeecd08cab15611883971c53d36e4e0ed4346108c86d45a1028e065ee1e", + "identity_kind": "workspace_snapshot", + "entry_module_id": "root:default::loop-jumps.mq.md", + "lock_digest": "", + "manifest_digest": "", + "stdlib": { + "version": "0.1.0", + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713" + }, + "extensions": [] + }, + "modules": [ + { + "id": "root:default::loop-jumps.mq.md", + "package_instance_id": "root:default", + "relative_path": "loop-jumps.mq.md", + "source_digest": "d80d0b20f64e49679204c4adff7829e14199645e0a4ea14fb72289aa30b4aa4e", + "source": "## @exec main\n\n在内外两层循环中分别检查控制跳转。\n\n- `while false`:先判定外层条件。\n\n 1. `if false`:进入首臂时继续外层循环。\n\n `continue`\n\n 2. `else if true`:进入次臂时停止内层循环。\n\n - `while true`:内层循环只读取一次。\n\n `break`\n\n `end`\n\n 3. `else`:进入末臂时先继续内层循环,再到外层关闭处。\n\n - `while false`:内层条件成立时才跳转。\n\n `continue`\n\n `end`\n\n `break`\n\n `end`\n\n `end`\n\n*return 0*\n\n返回扫描结果。\n", + "document": { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@exec main", + "span": { + "end": 13, + "start": 3 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 13, + "start": 0 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "在内外两层循环中分别检查控制跳转。", + "span": { + "end": 66, + "start": 15 + } + } + ], + "kind": "paragraph", + "span": { + "end": 66, + "start": 15 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "while false", + "span": { + "end": 83, + "start": 70 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":先判定外层条件。", + "span": { + "end": 110, + "start": 83 + } + } + ], + "kind": "paragraph", + "span": { + "end": 110, + "start": 70 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "if false", + "span": { + "end": 127, + "start": 117 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":进入首臂时继续外层循环。", + "span": { + "end": 166, + "start": 127 + } + } + ], + "kind": "paragraph", + "span": { + "end": 166, + "start": 117 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "continue", + "span": { + "end": 183, + "start": 173 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 183, + "start": 173 + } + } + ], + "kind": "item", + "span": { + "end": 183, + "start": 114 + }, + "task": null + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "else if true", + "span": { + "end": 204, + "start": 190 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":进入次臂时停止内层循环。", + "span": { + "end": 243, + "start": 204 + } + } + ], + "kind": "paragraph", + "span": { + "end": 243, + "start": 190 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "while true", + "span": { + "end": 264, + "start": 252 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":内层循环只读取一次。", + "span": { + "end": 297, + "start": 264 + } + } + ], + "kind": "paragraph", + "span": { + "end": 297, + "start": 252 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "break", + "span": { + "end": 313, + "start": 306 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 313, + "start": 306 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "end", + "span": { + "end": 327, + "start": 322 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 327, + "start": 322 + } + } + ], + "kind": "item", + "span": { + "end": 327, + "start": 250 + }, + "task": null + } + ], + "kind": "list", + "ordered": false, + "span": { + "end": 327, + "start": 250 + }, + "start": null, + "tight": false + } + ], + "kind": "item", + "span": { + "end": 327, + "start": 187 + }, + "task": null + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "else", + "span": { + "end": 340, + "start": 334 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":进入末臂时先继续内层循环,再到外层关闭处。", + "span": { + "end": 406, + "start": 340 + } + } + ], + "kind": "paragraph", + "span": { + "end": 406, + "start": 334 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "while false", + "span": { + "end": 428, + "start": 415 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":内层条件成立时才跳转。", + "span": { + "end": 464, + "start": 428 + } + } + ], + "kind": "paragraph", + "span": { + "end": 464, + "start": 415 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "continue", + "span": { + "end": 483, + "start": 473 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 483, + "start": 473 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "end", + "span": { + "end": 497, + "start": 492 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 497, + "start": 492 + } + } + ], + "kind": "item", + "span": { + "end": 497, + "start": 413 + }, + "task": null + } + ], + "kind": "list", + "ordered": false, + "span": { + "end": 497, + "start": 413 + }, + "start": null, + "tight": false + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "break", + "span": { + "end": 511, + "start": 504 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 511, + "start": 504 + } + } + ], + "kind": "item", + "span": { + "end": 511, + "start": 331 + }, + "task": null + } + ], + "kind": "list", + "ordered": true, + "span": { + "end": 511, + "start": 114 + }, + "start": 1, + "tight": false + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "end", + "span": { + "end": 520, + "start": 515 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 520, + "start": 515 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "end", + "span": { + "end": 529, + "start": 524 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 529, + "start": 524 + } + } + ], + "kind": "item", + "span": { + "end": 529, + "start": 68 + }, + "task": null + } + ], + "kind": "list", + "ordered": false, + "span": { + "end": 529, + "start": 68 + }, + "start": null, + "tight": false + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "return 0", + "span": { + "end": 540, + "start": 532 + } + } + ], + "kind": "emph", + "span": { + "end": 541, + "start": 531 + } + } + ], + "kind": "paragraph", + "span": { + "end": 541, + "start": 531 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "返回扫描结果。", + "span": { + "end": 564, + "start": 543 + } + } + ], + "kind": "paragraph", + "span": { + "end": 564, + "start": 543 + } + } + ], + "kind": "document", + "span": { + "end": 565, + "start": 0 + } + }, + "units": [ + { + "id": "root:default::loop-jumps.mq.md#", + "path": [], + "parent_id": null, + "kind": "root", + "name": "", + "level": 0, + "mode": "knowledge", + "mode_origin": "default", + "mode_source_unit_id": "root:default::loop-jumps.mq.md#", + "heading_span": null, + "span": { + "start": 0, + "end": 565 + }, + "function": null + }, + { + "id": "root:default::loop-jumps.mq.md#main", + "path": [ + "main" + ], + "parent_id": "root:default::loop-jumps.mq.md#", + "kind": "function", + "name": "main", + "level": 2, + "mode": "exec", + "mode_origin": "explicit", + "mode_source_unit_id": "root:default::loop-jumps.mq.md#main", + "heading_span": { + "start": 0, + "end": 13 + }, + "span": { + "start": 0, + "end": 565 + }, + "function": "root:default::loop-jumps.mq.md::main" + } + ], + "anchors": [ + { + "anchor": "main", + "unit_id": "root:default::loop-jumps.mq.md#main" + } + ], + "functions": [ + { + "id": "root:default::loop-jumps.mq.md::main", + "unit_id": "root:default::loop-jumps.mq.md#main", + "local_name": "main", + "namespace": null, + "span": { + "start": 0, + "end": 564 + }, + "heading_span": { + "start": 0, + "end": 13 + }, + "signature": { + "kind": "inferred", + "params": [] + }, + "effects": [ + "unknown" + ], + "body": [ + { + "body": [ + { + "arms": [ + { + "body": [ + { + "kind": "continue", + "span": { + "end": 183, + "start": 173 + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": false + }, + "condition_span": { + "end": 127, + "start": 117 + }, + "span": { + "end": 127, + "start": 117 + } + }, + { + "body": [ + { + "body": [ + { + "kind": "break", + "span": { + "end": 313, + "start": 306 + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": true + }, + "condition_span": { + "end": 264, + "start": 252 + }, + "kind": "loop", + "span": { + "end": 264, + "start": 252 + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": true + }, + "condition_span": { + "end": 204, + "start": 190 + }, + "span": { + "end": 204, + "start": 190 + } + }, + { + "body": [ + { + "body": [ + { + "kind": "continue", + "span": { + "end": 483, + "start": 473 + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": false + }, + "condition_span": { + "end": 428, + "start": 415 + }, + "kind": "loop", + "span": { + "end": 428, + "start": 415 + } + }, + { + "kind": "break", + "span": { + "end": 511, + "start": 504 + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": true + }, + "condition_span": { + "end": 340, + "start": 334 + }, + "span": { + "end": 340, + "start": 334 + } + } + ], + "kind": "branch", + "span": { + "end": 127, + "start": 117 + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": false + }, + "condition_span": { + "end": 83, + "start": 70 + }, + "kind": "loop", + "span": { + "end": 83, + "start": 70 + } + }, + { + "kind": "return", + "span": { + "end": 541, + "start": 531 + }, + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + } + } + ] + } + ], + "imports": [], + "references": [], + "calls": [], + "resources": [] + } + ], + "diagnostics": [] +} \ No newline at end of file diff --git a/tests/fixtures/rc4/multi-arm.analysis.json b/tests/fixtures/rc4/multi-arm.analysis.json new file mode 100644 index 0000000..25413ae --- /dev/null +++ b/tests/fixtures/rc4/multi-arm.analysis.json @@ -0,0 +1,599 @@ +{ + "schema": "marqdo.analysis", + "schema_version": 3, + "producer": { + "name": "marqdo", + "version": "3.0.0-rc.4", + "markdown_profile": "marqdo.md.v1" + }, + "project": { + "root_id": "sha256:cceb51765cdfc58898339ca161c0d61b93d2218dd4505dcfee0779c87ef1d303", + "identity_kind": "workspace_snapshot", + "entry_module_id": "root:default::multi-arm.mq.md", + "lock_digest": "", + "manifest_digest": "", + "stdlib": { + "version": "0.1.0", + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713" + }, + "extensions": [] + }, + "modules": [ + { + "id": "root:default::multi-arm.mq.md", + "package_instance_id": "root:default", + "relative_path": "multi-arm.mq.md", + "source_digest": "92485c1da250e6658de4908bf4b49156b2094188d0aa02cb133c8388a116f3e0", + "source": "## @exec main\n\n根据输入条件依次选择一个结果。\n\n1. `if false`:首个条件。\n *return 1*\n2. `else if true`:后续条件可以是字面量。\n *return 2*\n3. `else if false`:最后一个条件。\n *return 3*\n4. `else`:前面的条件全部不成立时返回默认值。\n *return 4*\n\n`end`\n", + "document": { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@exec main", + "span": { + "end": 13, + "start": 3 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 13, + "start": 0 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "根据输入条件依次选择一个结果。", + "span": { + "end": 60, + "start": 15 + } + } + ], + "kind": "paragraph", + "span": { + "end": 60, + "start": 15 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "if false", + "span": { + "end": 75, + "start": 65 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":首个条件。", + "span": { + "end": 93, + "start": 75 + } + }, + { + "children": [], + "kind": "soft_break", + "span": { + "end": 94, + "start": 93 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "return 1", + "span": { + "end": 106, + "start": 98 + } + } + ], + "kind": "emph", + "span": { + "end": 107, + "start": 97 + } + } + ], + "kind": "paragraph", + "span": { + "end": 107, + "start": 65 + } + } + ], + "kind": "item", + "span": { + "end": 107, + "start": 62 + }, + "task": null + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "else if true", + "span": { + "end": 125, + "start": 111 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":后续条件可以是字面量。", + "span": { + "end": 161, + "start": 125 + } + }, + { + "children": [], + "kind": "soft_break", + "span": { + "end": 162, + "start": 161 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "return 2", + "span": { + "end": 174, + "start": 166 + } + } + ], + "kind": "emph", + "span": { + "end": 175, + "start": 165 + } + } + ], + "kind": "paragraph", + "span": { + "end": 175, + "start": 111 + } + } + ], + "kind": "item", + "span": { + "end": 175, + "start": 108 + }, + "task": null + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "else if false", + "span": { + "end": 194, + "start": 179 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":最后一个条件。", + "span": { + "end": 218, + "start": 194 + } + }, + { + "children": [], + "kind": "soft_break", + "span": { + "end": 219, + "start": 218 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "return 3", + "span": { + "end": 231, + "start": 223 + } + } + ], + "kind": "emph", + "span": { + "end": 232, + "start": 222 + } + } + ], + "kind": "paragraph", + "span": { + "end": 232, + "start": 179 + } + } + ], + "kind": "item", + "span": { + "end": 232, + "start": 176 + }, + "task": null + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "else", + "span": { + "end": 242, + "start": 236 + }, + "ticks": 1 + }, + { + "children": [], + "kind": "text", + "literal": ":前面的条件全部不成立时返回默认值。", + "span": { + "end": 296, + "start": 242 + } + }, + { + "children": [], + "kind": "soft_break", + "span": { + "end": 297, + "start": 296 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "return 4", + "span": { + "end": 309, + "start": 301 + } + } + ], + "kind": "emph", + "span": { + "end": 310, + "start": 300 + } + } + ], + "kind": "paragraph", + "span": { + "end": 310, + "start": 236 + } + } + ], + "kind": "item", + "span": { + "end": 310, + "start": 233 + }, + "task": null + } + ], + "kind": "list", + "ordered": true, + "span": { + "end": 310, + "start": 62 + }, + "start": 1, + "tight": true + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "end", + "span": { + "end": 317, + "start": 312 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 317, + "start": 312 + } + } + ], + "kind": "document", + "span": { + "end": 318, + "start": 0 + } + }, + "units": [ + { + "id": "root:default::multi-arm.mq.md#", + "path": [], + "parent_id": null, + "kind": "root", + "name": "", + "level": 0, + "mode": "knowledge", + "mode_origin": "default", + "mode_source_unit_id": "root:default::multi-arm.mq.md#", + "heading_span": null, + "span": { + "start": 0, + "end": 318 + }, + "function": null + }, + { + "id": "root:default::multi-arm.mq.md#main", + "path": [ + "main" + ], + "parent_id": "root:default::multi-arm.mq.md#", + "kind": "function", + "name": "main", + "level": 2, + "mode": "exec", + "mode_origin": "explicit", + "mode_source_unit_id": "root:default::multi-arm.mq.md#main", + "heading_span": { + "start": 0, + "end": 13 + }, + "span": { + "start": 0, + "end": 318 + }, + "function": "root:default::multi-arm.mq.md::main" + } + ], + "anchors": [ + { + "anchor": "main", + "unit_id": "root:default::multi-arm.mq.md#main" + } + ], + "functions": [ + { + "id": "root:default::multi-arm.mq.md::main", + "unit_id": "root:default::multi-arm.mq.md#main", + "local_name": "main", + "namespace": null, + "span": { + "start": 0, + "end": 317 + }, + "heading_span": { + "start": 0, + "end": 13 + }, + "signature": { + "kind": "inferred", + "params": [] + }, + "effects": [ + "unknown" + ], + "body": [ + { + "arms": [ + { + "body": [ + { + "kind": "return", + "span": { + "end": 107, + "start": 97 + }, + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "1" + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": false + }, + "condition_span": { + "end": 75, + "start": 65 + }, + "span": { + "end": 75, + "start": 65 + } + }, + { + "body": [ + { + "kind": "return", + "span": { + "end": 175, + "start": 165 + }, + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "2" + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": true + }, + "condition_span": { + "end": 125, + "start": 111 + }, + "span": { + "end": 125, + "start": 111 + } + }, + { + "body": [ + { + "kind": "return", + "span": { + "end": 232, + "start": 222 + }, + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "3" + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": false + }, + "condition_span": { + "end": 194, + "start": 179 + }, + "span": { + "end": 194, + "start": 179 + } + }, + { + "body": [ + { + "kind": "return", + "span": { + "end": 310, + "start": 300 + }, + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "4" + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": true + }, + "condition_span": { + "end": 242, + "start": 236 + }, + "span": { + "end": 242, + "start": 236 + } + } + ], + "kind": "branch", + "span": { + "end": 75, + "start": 65 + } + } + ] + } + ], + "imports": [], + "references": [], + "calls": [], + "resources": [] + } + ], + "diagnostics": [] +} \ No newline at end of file diff --git a/tests/fixtures/rc4/unicode.analysis.json b/tests/fixtures/rc4/unicode.analysis.json new file mode 100644 index 0000000..536ba50 --- /dev/null +++ b/tests/fixtures/rc4/unicode.analysis.json @@ -0,0 +1,305 @@ +{ + "schema": "marqdo.analysis", + "schema_version": 3, + "producer": { + "name": "marqdo", + "version": "3.0.0-rc.4", + "markdown_profile": "marqdo.md.v1" + }, + "project": { + "root_id": "sha256:6bc3c991a61f2f39ae5c8a58f02c1d860b6bcc3d9df547a3b24ff61bcb47f072", + "identity_kind": "workspace_snapshot", + "entry_module_id": "root:default::unicode.mq.md", + "lock_digest": "", + "manifest_digest": "", + "stdlib": { + "version": "0.1.0", + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713" + }, + "extensions": [] + }, + "modules": [ + { + "id": "root:default::unicode.mq.md", + "package_instance_id": "root:default", + "relative_path": "unicode.mq.md", + "source_digest": "07464d28973b2a7ed9e1d96ed689104239bb61863c90922d74a9f230e73b1bee", + "source": "## @exec 多字节😀\n\n中文说明与 emoji 😀 用于验证精确位置。\n\n`params(x: Int)`\n\n**结果 = x + 1**\n\n返回整数结果。\n\n*return 结果*\n", + "document": { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@exec 多字节😀", + "span": { + "end": 22, + "start": 3 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 22, + "start": 0 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "中文说明与 emoji 😀 用于验证精确位置。", + "span": { + "end": 78, + "start": 24 + } + } + ], + "kind": "paragraph", + "span": { + "end": 78, + "start": 24 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "params(x: Int)", + "span": { + "end": 96, + "start": 80 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 96, + "start": 80 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "结果 = x + 1", + "span": { + "end": 114, + "start": 100 + } + } + ], + "kind": "strong", + "span": { + "end": 116, + "start": 98 + } + } + ], + "kind": "paragraph", + "span": { + "end": 116, + "start": 98 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "返回整数结果。", + "span": { + "end": 139, + "start": 118 + } + } + ], + "kind": "paragraph", + "span": { + "end": 139, + "start": 118 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "return 结果", + "span": { + "end": 155, + "start": 142 + } + } + ], + "kind": "emph", + "span": { + "end": 156, + "start": 141 + } + } + ], + "kind": "paragraph", + "span": { + "end": 156, + "start": 141 + } + } + ], + "kind": "document", + "span": { + "end": 157, + "start": 0 + } + }, + "units": [ + { + "id": "root:default::unicode.mq.md#", + "path": [], + "parent_id": null, + "kind": "root", + "name": "", + "level": 0, + "mode": "knowledge", + "mode_origin": "default", + "mode_source_unit_id": "root:default::unicode.mq.md#", + "heading_span": null, + "span": { + "start": 0, + "end": 157 + }, + "function": null + }, + { + "id": "root:default::unicode.mq.md#多字节😀", + "path": [ + "多字节😀" + ], + "parent_id": "root:default::unicode.mq.md#", + "kind": "function", + "name": "多字节😀", + "level": 2, + "mode": "exec", + "mode_origin": "explicit", + "mode_source_unit_id": "root:default::unicode.mq.md#多字节😀", + "heading_span": { + "start": 0, + "end": 22 + }, + "span": { + "start": 0, + "end": 157 + }, + "function": "root:default::unicode.mq.md::多字节😀" + } + ], + "anchors": [ + { + "anchor": "多字节", + "unit_id": "root:default::unicode.mq.md#多字节😀" + } + ], + "functions": [ + { + "id": "root:default::unicode.mq.md::多字节😀", + "unit_id": "root:default::unicode.mq.md#多字节😀", + "local_name": "多字节😀", + "namespace": null, + "span": { + "start": 0, + "end": 156 + }, + "heading_span": { + "start": 0, + "end": 22 + }, + "signature": { + "kind": "explicit", + "params": [ + { + "name": "x", + "required": true, + "type": "Int", + "default": null, + "span": { + "start": 87, + "end": 93 + } + } + ] + }, + "effects": [ + "unknown" + ], + "body": [ + { + "kind": "assign", + "span": { + "end": 116, + "start": 98 + }, + "target": "结果", + "value": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "x", + "span": { + "end": 110, + "start": 109 + } + }, + "op": "add", + "right": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "1" + }, + "span": { + "end": 114, + "start": 109 + } + } + }, + { + "kind": "return", + "span": { + "end": 156, + "start": 141 + }, + "value": { + "kind": "variable", + "name": "结果", + "span": { + "end": 155, + "start": 149 + } + } + } + ] + } + ], + "imports": [], + "references": [], + "calls": [], + "resources": [] + } + ], + "diagnostics": [] +} \ No newline at end of file diff --git a/tests/fixtures/rejecting-core.sh b/tests/fixtures/rejecting-core.sh deleted file mode 100755 index 2f0d98a..0000000 --- a/tests/fixtures/rejecting-core.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh -case "$1" in - --version) echo 'marqdo 3.0.0-rc.1'; exit 0 ;; - inspect) exit 2 ;; - check) echo 'invalid document'; exit 1 ;; -esac diff --git a/tests/input_pipeline.rs b/tests/input_pipeline.rs index de1d35b..5c58aa9 100644 --- a/tests/input_pipeline.rs +++ b/tests/input_pipeline.rs @@ -1,163 +1,228 @@ -use std::path::{Path, PathBuf}; +mod common; +use std::path::Path; + +use common::{analysis_value, document, fixture_path, projection, require_core}; use marqdo_lint::{ - input::{fallback_ast, AnalysisStatus, MarqdoRunner, ProjectInput}, - model::{semantic_nodes, ExecutionProjection, SourceSnapshot}, + input::{AnalysisStatus, MarqdoRunner, ProjectInput}, + model::ExecutionProjection, }; -use serde_json::{json, Value}; - -fn fixture(name: &str) -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("tests/fixtures/golden") - .join(name) -} +use serde_json::json; #[test] -fn fallback_ast_matches_frozen_core_goldens() { - for stem in ["branches", "unicode", "bom", "knowledge", "invalid-control"] { - let source = SourceSnapshot::load(fixture(&format!("{stem}.mq.md"))).unwrap(); - let actual = fallback_ast(&source).unwrap(); - let expected: Value = - serde_json::from_slice(&std::fs::read(fixture(&format!("{stem}.ast.json"))).unwrap()) - .unwrap(); - assert_eq!(actual, expected["ast"], "AST 不一致:{stem}"); +fn saved_revision_three_artifact_is_typed_and_self_contained() { + for stem in [ + "branches", + "unicode", + "bom", + "knowledge", + "inventory", + "multi-arm", + "loop-jumps", + ] { + let projection = projection(stem); + assert_eq!(projection.schema_version, 3); + assert_eq!(projection.producer.markdown_profile, "marqdo.md.v1"); + let module = projection.entry_module().expect("entry module"); + assert_eq!( + module + .source_snapshot(fixture_path(&format!("{stem}.mq.md"))) + .unwrap() + .digest_hex(), + module.source_digest + ); + let document = document(stem); + let module = document.module.as_ref().unwrap(); + assert_eq!(module.source_digest, document.source.digest_hex()); + assert!(!document.markdown.headings.is_empty()); } } -fn rc2_analysis(stem: &str) -> Value { - serde_json::from_slice( - &std::fs::read(fixture(&format!("../rc2/{stem}.analysis.json"))).unwrap(), - ) - .unwrap() +#[test] +fn retired_same_revision_shape_is_rejected_with_regeneration_hint() { + for field in ["source", "document", "anchors"] { + let mut raw = analysis_value("branches"); + raw["modules"][0].as_object_mut().unwrap().remove(field); + let error = ExecutionProjection::from_json(raw).unwrap_err(); + assert!(error.contains("旧 revision 3"), "{error}"); + assert!(error.contains("重新生成"), "{error}"); + } } #[test] -fn analysis_rejects_unknown_major() { - for version in [4, 999] { - let mut raw = rc2_analysis("multi-arm"); +fn schema_revision_unknown_or_v2_is_rejected_without_decoding() { + for version in [2, 4, 999] { + let mut raw = analysis_value("branches"); raw["schema_version"] = json!(version); let error = ExecutionProjection::from_json(raw).unwrap_err(); - assert!(error.contains("schema_version") && error.contains(&version.to_string())); + assert!(error.contains("revision 3"), "{error}"); + assert!(error.contains(&version.to_string()), "{error}"); } -} - -#[test] -fn frozen_rc2_shapes_share_the_statement_view() { - for (stem, version, expected) in [ - ( - "multi-arm", - 2, - vec!["branch", "return", "return", "return", "return"], - ), - ( - "loop-jumps", - 3, - vec![ - "loop", "branch", "continue", "loop", "break", "loop", "continue", "break", - "return", - ], - ), - ] { - let mut raw = rc2_analysis(stem); - raw["modules"][0]["functions"][0]["body"][0]["extension"] = - json!({"kind": "break", "span": {"start": 0, "end": 0}}); - let projection = ExecutionProjection::from_json(raw.clone()).unwrap(); - assert_eq!(projection.raw, raw); - assert_eq!(projection.schema_version, version); - let module = &projection.modules[0]; - let source = SourceSnapshot::load(fixture(&format!("../rc2/{stem}.mq.md"))).unwrap(); - assert_eq!(module.source_digest, source.digest_hex()); - let actual: Vec<_> = semantic_nodes(&module.functions[0].body) - .map(|statement| statement["kind"].as_str().unwrap()) - .collect(); - assert_eq!(actual, expected); - let ast: Value = serde_json::from_slice( - &std::fs::read(fixture(&format!("../rc2/{stem}.ast.json"))).unwrap(), - ) - .unwrap(); - assert_eq!(fallback_ast(&source).unwrap(), ast["ast"]); - } -} - -#[test] -fn analysis_rejects_invalid_statement_structure() { - let mut old_version = rc2_analysis("loop-jumps"); - old_version["schema_version"] = json!(2); - assert!(ExecutionProjection::from_json(old_version) + let mut raw = analysis_value("branches"); + raw["schema"] = json!("marqdo.analysis.old"); + assert!(ExecutionProjection::from_json(raw) .unwrap_err() - .contains("v2")); + .contains("marqdo.analysis")); +} - let mut unknown = rc2_analysis("multi-arm"); - unknown["modules"][0]["functions"][0]["body"][0]["kind"] = json!("goto"); - assert!(ExecutionProjection::from_json(unknown) +#[test] +fn source_digest_and_span_invariants_fail_closed() { + let mut digest = analysis_value("branches"); + digest["modules"][0]["source_digest"] = json!("0".repeat(64)); + let error = ExecutionProjection::from_json(digest).unwrap_err(); + assert!(error.contains("sha256(source)"), "{error}"); + + let mut short = analysis_value("branches"); + short["modules"][0]["source_digest"] = json!("abc"); + assert!(ExecutionProjection::from_json(short) + .unwrap_err() + .contains("source_digest")); + + let mut out_of_bounds = analysis_value("branches"); + out_of_bounds["modules"][0]["units"][0]["span"]["end"] = json!(999_999); + assert!(ExecutionProjection::from_json(out_of_bounds) + .unwrap_err() + .contains("超出源码长度")); + + let mut utf8 = analysis_value("unicode"); + let source = utf8["modules"][0]["source"].as_str().unwrap().to_string(); + let emoji = source.find('😀').unwrap(); + utf8["modules"][0]["functions"][0]["span"]["start"] = json!(emoji + 1); + let error = ExecutionProjection::from_json(utf8).unwrap_err(); + assert!( + error.contains("UTF-8") || error.contains("字符边界"), + "{error}" + ); +} + +#[test] +fn malformed_statement_or_reference_state_is_rejected() { + let mut raw = analysis_value("multi-arm"); + raw["modules"][0]["functions"][0]["body"][0]["kind"] = json!("goto"); + assert!(ExecutionProjection::from_json(raw) .unwrap_err() .contains("goto")); - let mut malformed = rc2_analysis("multi-arm"); - malformed["modules"][0]["functions"][0]["body"][0]["arms"][1]["body"] = json!({}); - assert!(ExecutionProjection::from_json(malformed) + let mut raw = analysis_value("multi-arm"); + raw["modules"][0]["functions"][0]["body"][0]["arms"][1]["body"] = json!({}); + assert!(ExecutionProjection::from_json(raw) .unwrap_err() .contains("body")); + + let mut raw = analysis_value("branches"); + raw["modules"][0]["references"] = json!([{ + "source": raw["modules"][0]["id"], + "source_unit": raw["modules"][0]["units"][1]["id"], + "url": "./missing.mq.md", + "span": {"start": 0, "end": 1}, + "state": "ambiguous", + "target_kind": null, + "target_module": null, + "target_unit": null, + "candidate_package_instance_id": null, + "candidate_path": "missing.mq.md", + "fragment": null, + "candidates": [] + }]); + let error = ExecutionProjection::from_json(raw).unwrap_err(); + assert!(error.contains("ambiguous"), "{error}"); } #[test] -fn frozen_core_binds_source_ast_and_analysis() { - let Ok(binary) = std::env::var("MARQDO_BIN") else { - eprintln!("MARQDO_BIN 未设置,跳过冻结核心集成测试"); - return; - }; - let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); - let project = ProjectInput::load(fixture("branches.mq.md"), &runner).unwrap(); - assert_eq!(project.analysis_status, AnalysisStatus::Complete); - assert_eq!(project.documents.len(), 1); - let document = &project.documents[0]; - assert_eq!(document.module.as_ref().unwrap().functions.len(), 1); - assert_eq!(document.markdown.carriers.len(), 8); -} - -#[test] -fn failed_check_is_analysis_incomplete_not_clean() { - let Ok(binary) = std::env::var("MARQDO_BIN") else { - eprintln!("MARQDO_BIN 未设置,跳过冻结核心集成测试"); - return; - }; - let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); - let project = ProjectInput::load(fixture("invalid-control.mq.md"), &runner).unwrap(); - assert_eq!(project.analysis_status, AnalysisStatus::AnalysisIncomplete); - assert!(project.analysis.is_none()); - assert!(project.core_output.contains("sem.unclosed_control")); -} - -#[cfg(unix)] -#[test] -fn inspect_failure_uses_document_only_fallback() { - let binary = fixture("../rejecting-core.sh"); - let runner = MarqdoRunner::discover(Some(&binary)).unwrap(); - let project = ProjectInput::load(fixture("branches.mq.md"), &runner).unwrap(); - assert_eq!(project.analysis_status, AnalysisStatus::AnalysisIncomplete); - assert_eq!( - project.documents[0].markdown_origin, - marqdo_lint::input::MarkdownOrigin::ComrakFallback - ); - assert_eq!(project.notices.len(), 1); -} - -#[test] -fn multi_module_documents_keep_their_own_digest_and_spans() { - let Ok(binary) = std::env::var("MARQDO_BIN") else { - eprintln!("MARQDO_BIN 未设置,跳过冻结核心集成测试"); +fn live_core_uses_one_check_and_artifact_source_without_reopening_modules() { + let Some(binary) = require_core() else { return; }; let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); let entry = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/multi/index.mq.md"); - let project = ProjectInput::load(entry, &runner).unwrap(); + let project = ProjectInput::load(&entry, &runner, false).unwrap(); assert_eq!(project.analysis_status, AnalysisStatus::Complete); assert_eq!(project.documents.len(), 2); - for document in project.documents { - let module = document.module.unwrap(); + assert!(project.artifact_digest.unwrap().starts_with("sha256:")); + for document in &project.documents { + let module = document.module.as_ref().unwrap(); + assert_eq!(module.source, document.source.text()); assert_eq!(module.source_digest, document.source.digest_hex()); - for function in module.functions { - assert!(function.span.end <= document.source.bytes.len()); - } } } + +#[test] +fn failed_check_is_analysis_incomplete_and_never_a_clean_result() { + let Some(binary) = require_core() else { + return; + }; + let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); + let project = ProjectInput::load( + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/golden/invalid-control.mq.md"), + &runner, + false, + ) + .unwrap(); + assert_eq!(project.analysis_status, AnalysisStatus::AnalysisIncomplete); + assert!(project.analysis.is_none()); + assert!(project.core_output.contains("sem.unclosed_control")); + assert!(project.documents[0].module.is_none()); +} + +#[test] +fn module_and_entry_identity_must_be_unique_and_safe() { + let mut duplicate = analysis_value("branches"); + let first = duplicate["modules"][0].clone(); + duplicate["modules"].as_array_mut().unwrap().push(first); + assert!(ExecutionProjection::from_json(duplicate) + .unwrap_err() + .contains("重复")); + + let mut entry = analysis_value("branches"); + entry["project"]["entry_module_id"] = json!("root:default::other.mq.md"); + assert!(ExecutionProjection::from_json(entry) + .unwrap_err() + .contains("entry_module_id")); + + let mut path = analysis_value("branches"); + path["modules"][0]["relative_path"] = json!("../escape.mq.md"); + assert!(ExecutionProjection::from_json(path) + .unwrap_err() + .contains("relative_path")); +} + +#[cfg(unix)] +#[test] +fn failed_check_never_reads_a_stale_artifact_left_at_the_emit_path() { + use std::os::unix::fs::PermissionsExt; + + let Some(binary) = require_core() else { + return; + }; + let work = tempfile::tempdir().unwrap(); + let source = work.path().join("branches.mq.md"); + std::fs::copy( + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/golden/branches.mq.md"), + &source, + ) + .unwrap(); + let projection = std::fs::read(fixture_path("branches.analysis.json")).unwrap(); + std::fs::write(work.path().join("stale.json"), projection).unwrap(); + let proxy = work.path().join("stale-core"); + std::fs::write( + &proxy, + "#!/bin/sh\nset -eu\ncase \"$1\" in\n --version) echo 'marqdo 3.0.0-rc.4' ;;\n check) case \"$4\" in --emit) cp \"$0.json\" \"$5\" ;; esac; exit 2 ;;\n *) exit 2 ;;\nesac\n", + ) + .unwrap(); + std::fs::set_permissions(&proxy, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::copy( + work.path().join("stale.json"), + work.path().join("stale-core.json"), + ) + .unwrap(); + let runner = MarqdoRunner::discover(Some(&proxy)).unwrap(); + let project = ProjectInput::load(&source, &runner, false).unwrap(); + assert_eq!( + project.analysis_status, + AnalysisStatus::AnalysisIncomplete, + "a successful decode of the stale artifact would be a protocol violation" + ); + assert!(project.analysis.is_none()); + assert!(project.documents[0].module.is_none()); + let _ = binary; +} diff --git a/tests/rc2_pipeline.rs b/tests/rc2_pipeline.rs deleted file mode 100644 index 10e5c43..0000000 --- a/tests/rc2_pipeline.rs +++ /dev/null @@ -1,267 +0,0 @@ -use std::{ - fs, - path::{Path, PathBuf}, - process::Command, -}; - -use marqdo_lint::{ - alignment::{align_function, JumpKind}, - input::{AnalysisStatus, MarqdoRunner, ProjectInput}, - model::SourceSnapshot, -}; -use serde_json::Value; - -fn core(required: &str) -> Option { - let path = std::env::var_os("MARQDO_BIN").map(PathBuf::from)?; - let output = Command::new(&path).arg("--version").output().unwrap(); - (String::from_utf8(output.stdout).unwrap().trim() == required).then_some(path) -} - -fn lint(core: &Path, source: &Path) -> (i32, Vec, String) { - let output = Command::new(env!("CARGO_BIN_EXE_marqdo-lint")) - .env("MARQDO_BIN", core) - .arg(source) - .args(["--format", "json", "--fail-on", "never"]) - .output() - .unwrap(); - ( - output.status.code().unwrap(), - output.stdout, - String::from_utf8(output.stderr).unwrap(), - ) -} - -#[test] -fn rc1_bare_identifiers_remain_ordinary_expressions() { - let Some(core) = core("marqdo 3.0.0-rc.1") else { - return; - }; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("legacy.mq.md"); - fs::write( - &path, - "## @exec main\n\n**break = 1**\n\n`break`\n\n*return break*\n", - ) - .unwrap(); - let (status, output, stderr) = lint(&core, &path); - assert_eq!(status, 0, "{stderr}"); - let report: Value = serde_json::from_slice(&output).unwrap(); - assert_eq!(report["analysis_status"], "complete"); - assert_eq!(report["metrics"]["functions"][0]["statement_count"], 3); -} - -#[test] -fn rc2_offsets_use_utf8_bytes_and_only_standalone_jumps_are_control() { - let Some(core) = core("marqdo 3.0.0-rc.2") else { - return; - }; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("unicode.mq.md"); - let source = "\u{feff}## @exec main\n\n正文讨论跳转与读数 😀。\n\n**continue = 1**\n\n**call_result = break(1)**\n\n> **while false**:引用中的循环。\n>\n> *continue*\n>\n> `end`\n\n*return continue + continue_work(call_result)*\n\n[惰性链接 `break`](https://example.invalid)\n\n```text\n`break`\n```\n\n### @knowledge 惰性说明\n\n`continue` 与 **break**\n\n## @exec break\n\n`params(x: Int)`\n\n*return x*\n\n## @exec continue_work\n\n`params(x: Int)`\n\n*return x*\n".replace('\n', "\r\n"); - fs::write(&path, &source).unwrap(); - let runner = MarqdoRunner::discover(Some(&core)).unwrap(); - let project = ProjectInput::load(&path, &runner).unwrap(); - assert_eq!( - project.analysis_status, - AnalysisStatus::Complete, - "{}", - project.core_output - ); - assert_eq!(project.analysis.as_ref().unwrap().schema_version, 3); - let document = &project.documents[0]; - let module = document.module.as_ref().unwrap(); - let function = module - .functions - .iter() - .find(|f| f.local_name == "main") - .unwrap(); - let tree = align_function(&document.markdown, function); - assert!(tree.complete, "{:?}", tree.issues); - let [jump] = tree.jumps.as_slice() else { - panic!("expected one jump") - }; - assert_eq!(jump.kind, JumpKind::Continue); - assert_eq!(jump.carrier.span.start, source.find("*continue*").unwrap()); - assert_eq!( - document.source.slice(jump.carrier.span).unwrap(), - "*continue*" - ); - assert!(module.calls.iter().any(|call| call["target"] - .as_str() - .is_some_and(|id| id.ends_with("::break")))); - assert!(module.calls.iter().any(|call| call["target"] - .as_str() - .is_some_and(|id| id.ends_with("::continue_work")))); -} - -#[test] -fn rc2_imported_jump_promotes_the_project_and_offsets_remain_module_local() { - let Some(core) = core("marqdo 3.0.0-rc.2") else { - return; - }; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("index.mq.md"); - let left = directory.path().join("left.mq.md"); - let right = directory.path().join("right.mq.md"); - fs::write(&path, "---\nimport:\n left: './left.mq.md'\n right: './right.mq.md'\n---\n\n## @exec main\n\n计算两个模块的返回值。\n\n*return left.helper() + right.helper()*\n").unwrap(); - fs::write( - &left, - "## @exec helper\n\n`while false`\n\n*break*\n\n`end`\n\n*return 1*\n", - ) - .unwrap(); - fs::write(&right, "## @exec helper\n\n*return 2*\n").unwrap(); - let runner = MarqdoRunner::discover(Some(&core)).unwrap(); - let project = ProjectInput::load(&path, &runner).unwrap(); - assert_eq!( - project.analysis_status, - AnalysisStatus::Complete, - "{}", - project.core_output - ); - assert_eq!(project.analysis.as_ref().unwrap().schema_version, 3); - assert_eq!(project.documents.len(), 3); - let report_for = |path: &Path| { - project - .documents - .iter() - .find(|document| document.source.path == path) - .unwrap() - }; - let left_id = &report_for(&left).module.as_ref().unwrap().functions[0]; - let right_id = &report_for(&right).module.as_ref().unwrap().functions[0]; - assert_ne!(left_id.id, right_id.id); - assert_eq!(left_id.heading_span, right_id.heading_span); - assert_eq!( - left_id.body[0]["span"]["start"], - right_id.body[0]["span"]["start"] - ); - let (status, output, stderr) = lint(&core, &path); - assert_eq!(status, 0, "{stderr}"); - let report: Value = serde_json::from_slice(&output).unwrap(); - let documents = report["reports"].as_array().unwrap(); - for source in [&path, &left, &right] { - let snapshot = SourceSnapshot::load(source).unwrap(); - let document = documents - .iter() - .find(|doc| doc["source"]["digest"] == snapshot.digest) - .unwrap(); - assert_eq!(document["analysis_status"], "complete"); - let jump = document["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|d| d["id"] == "MQD-STYLE-001"); - assert_eq!(jump, source == &left); - } -} - -#[test] -fn rc2_core_errors_keep_locations_and_exit_two_even_at_never_threshold() { - let Some(core) = core("marqdo 3.0.0-rc.2") else { - return; - }; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("invalid.mq.md"); - for (source, code, point) in [ - ("`else if true`\n", "sem.unmatched_else_if", ":3:1:"), - ("`break`\n", "sem.break_outside_loop", ":3:1:"), - ( - "`while true`\n\n### 下一段\n\n`continue`\n\n`end`\n", - "sem.continue_outside_loop", - ":7:1:", - ), - ] { - fs::write(&path, format!("## @exec main\n\n{source}")).unwrap(); - let (status, output, stderr) = lint(&core, &path); - assert_eq!(status, 2, "{stderr}"); - let report: Value = serde_json::from_slice(&output).unwrap(); - assert_eq!(report["analysis_status"], "analysis_incomplete"); - let core_output = report["core_output"].as_str().unwrap(); - assert!( - core_output - .lines() - .any(|line| line.contains(code) && line.contains(point)), - "{core_output}" - ); - assert!(report["metrics"]["functions"] - .as_array() - .unwrap() - .is_empty()); - assert!(report["diagnostics"] - .as_array() - .unwrap() - .iter() - .all(|d| !d["id"].as_str().unwrap().starts_with("MQD-BRANCH") - && !d["id"].as_str().unwrap().starts_with("MQD-LOOP"))); - } -} - -#[cfg(unix)] -#[test] -fn public_protocol_failures_cannot_be_hidden_by_never_threshold() { - use std::os::unix::fs::PermissionsExt; - - let Some(core) = std::env::var_os("MARQDO_BIN") else { - return; - }; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("multi-arm.mq.md"); - let proxy = directory.path().join("core-proxy"); - let source = include_str!("fixtures/rc2/multi-arm.mq.md"); - fs::write(&path, source).unwrap(); - fs::write( - directory.path().join("core-path"), - PathBuf::from(core) - .canonicalize() - .unwrap() - .as_os_str() - .as_encoded_bytes(), - ) - .unwrap(); - fs::write(&proxy, "#!/bin/sh\nset -eu\nbase=$(dirname \"$0\")\ncase \"$1\" in\n check) cp \"$base/projection.json\" \"$5\" ;;\n *) exec \"$(cat \"$base/core-path\")\" \"$@\" ;;\nesac\n").unwrap(); - fs::set_permissions(&proxy, fs::Permissions::from_mode(0o755)).unwrap(); - let raw: Value = - serde_json::from_str(include_str!("fixtures/rc2/multi-arm.analysis.json")).unwrap(); - let mut major = raw.clone(); - major["schema_version"] = 999.into(); - let mut digest = raw.clone(); - digest["modules"][0]["source_digest"] = "0".repeat(64).into(); - let mut utf8 = raw.clone(); - utf8["modules"][0]["functions"][0]["body"][0]["arms"][1]["span"]["start"] = - (source.find('首').unwrap() + 1).into(); - let mut v2_jump = raw.clone(); - v2_jump["modules"][0]["functions"][0]["body"][0]["arms"][1]["body"][0]["kind"] = "break".into(); - for (artifact, error) in [ - (major, "999"), - (digest, "源码摘要"), - (utf8, "UTF-8"), - (v2_jump, "Analysis v2"), - ] { - fs::write( - directory.path().join("projection.json"), - serde_json::to_vec(&artifact).unwrap(), - ) - .unwrap(); - let (status, output, stderr) = lint(&proxy, &path); - assert_eq!(status, 2, "{stderr}"); - assert!(output.is_empty()); - assert!(stderr.contains(error), "{stderr}"); - } - let mut duplicate = raw; - duplicate["modules"][0]["functions"][0]["body"][0]["arms"][2]["condition_span"] = - duplicate["modules"][0]["functions"][0]["body"][0]["arms"][1]["condition_span"].clone(); - fs::write( - directory.path().join("projection.json"), - serde_json::to_vec(&duplicate).unwrap(), - ) - .unwrap(); - let (status, output, _) = lint(&proxy, &path); - assert_eq!(status, 2); - let report: Value = serde_json::from_slice(&output).unwrap(); - assert_eq!(report["analysis_status"], "analysis_incomplete"); - assert!(report["notices"][0].as_str().unwrap().contains("span 重复")); - assert!(report["metrics"]["functions"] - .as_array() - .unwrap() - .is_empty()); -} diff --git a/tests/rules_rc4.rs b/tests/rules_rc4.rs new file mode 100644 index 0000000..d44dee8 --- /dev/null +++ b/tests/rules_rc4.rs @@ -0,0 +1,165 @@ +mod common; + +use marqdo_lint::{ + input::SourceDocument, + model::{ExecutionProjection, MarkdownTree}, + rules::check_ast_document, +}; +use serde_json::{json, Value}; + +fn document_with(raw: Value) -> SourceDocument { + let projection = ExecutionProjection::from_json(raw).unwrap(); + let module = projection.entry_module().unwrap().clone(); + let source = module + .source_snapshot(std::path::PathBuf::from("index.mq.md")) + .unwrap(); + let markdown = MarkdownTree::from_analysis( + module.document.clone(), + &module.units, + &module.functions, + &source, + ) + .unwrap(); + SourceDocument { + source, + markdown, + module: Some(module), + } +} + +fn reference(source_unit: &str, id: &str, state: &str) -> Value { + let mut value = json!({ + "source": id, + "source_unit": source_unit, + "url": format!("./{state}.mq.md"), + "span": {"start": 0, "end": 0}, + "state": state, + "target_kind": null, + "target_module": null, + "target_unit": null, + "candidate_package_instance_id": null, + "candidate_path": null, + "fragment": null, + "candidates": [] + }); + match state { + "resolved" => { + value["target_kind"] = json!("module"); + value["target_module"] = json!(id); + } + "ambiguous" => { + value["candidates"] = json!(["a#one", "a#two"]); + } + _ => {} + } + value +} + +#[test] +fn reference_states_map_to_distinct_rule_ids_and_messages() { + let mut raw = common::analysis_value("branches"); + let module_id = raw["modules"][0]["id"].as_str().unwrap().to_string(); + let unit_id = raw["modules"][0]["units"][1]["id"] + .as_str() + .unwrap() + .to_string(); + let mut refs = Vec::new(); + for state in [ + "resolved", + "missing", + "not_loaded", + "ambiguous", + "external", + "outside_scope", + "invalid", + ] { + let mut value = reference(&unit_id, &module_id, state); + if state != "missing" { + value["url"] = json!(format!("./{state}")); + } + refs.push(value); + } + raw["modules"][0]["references"] = Value::Array(refs); + let document = document_with(raw); + let diagnostics = check_ast_document(&document); + let ids = diagnostics + .iter() + .map(|diagnostic| diagnostic.id.as_str()) + .collect::>(); + assert_eq!( + ids.iter().filter(|id| **id == "MQD-LINK-001").count(), + 4, + "{diagnostics:?}" + ); + assert_eq!(ids.iter().filter(|id| **id == "MQD-LINK-002").count(), 1); + assert_eq!(ids.iter().filter(|id| **id == "MQD-LINK-003").count(), 1); + let ambiguity = diagnostics + .iter() + .find(|diagnostic| { + diagnostic.id == "MQD-LINK-001" && diagnostic.message.contains("多个候选") + }) + .unwrap(); + assert!(ambiguity.message.contains("a#one")); + assert!(ambiguity.message.contains("a#two")); + let unverified = diagnostics + .iter() + .find(|diagnostic| diagnostic.id == "MQD-LINK-002") + .unwrap(); + assert!(unverified.message.contains("不等于断链")); +} + +#[test] +fn unresolved_calls_are_informational_not_errors() { + let mut raw = common::analysis_value("branches"); + let module_id = raw["modules"][0]["id"].as_str().unwrap().to_string(); + let function_id = raw["modules"][0]["functions"][0]["id"] + .as_str() + .unwrap() + .to_string(); + raw["modules"][0]["calls"] = json!([{ + "function": function_id, + "span": {"start": 0, "end": 0}, + "callee": {"kind": "ident", "name": "动态目标"}, + "state": "unresolved", + "target": null, + "target_kind": null, + "target_owner": null, + "reason": "dynamic" + }]); + let document = document_with(raw); + let diagnostics = check_ast_document(&document); + let call = diagnostics + .iter() + .find(|diagnostic| diagnostic.id == "MQD-CALL-001") + .unwrap(); + assert_eq!(call.severity, marqdo_lint::rules::Severity::Info); + assert!(call.message.contains("不是错误")); + assert_eq!(module_id, document.module.as_ref().unwrap().id); +} + +#[test] +fn resource_digest_is_checked_against_the_ast_literal() { + let mut raw = common::analysis_value("branches"); + let source_len = raw["modules"][0]["source"].as_str().unwrap().len(); + let module_id = raw["modules"][0]["id"].as_str().unwrap().to_string(); + let unit_id = raw["modules"][0]["units"][1]["id"] + .as_str() + .unwrap() + .to_string(); + raw["modules"][0]["resources"] = json!([{ + "id": format!("{module_id}#resource:code-1"), + "module_id": module_id, + "unit_id": unit_id, + "kind": "code", + "span": {"start": 0, "end": 0}, + "content_digest": "0".repeat(64), + "language": null, + "display": null + }]); + let error = ExecutionProjection::from_json(raw).unwrap_err(); + assert!( + error.contains("content_digest") || error.contains("AST literal"), + "{error}" + ); + let _ = source_len; +} diff --git a/tool.json b/tool.json index b6e7029..e337397 100644 --- a/tool.json +++ b/tool.json @@ -2,11 +2,11 @@ "schema": "marqdo.cli-tool", "schema_version": 1, "name": "cflmy.marqdo-lint", - "version": "0.1.0-rc.1", + "version": "0.2.0", "command": "lint", "entrypoint": "bin/marqdo-lint", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2, 3] + "requires": { + "api_revision": 1, + "analysis": 3 } }