From a11b3476592a652852838c7dcaa398ab09c7cc18 Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 13 Nov 2026 16:06:30 +0800 Subject: [PATCH] prove: add marqdo prove (P0 emit/audit + P1 claim tables & check --proof) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Language layer (ADR 0010): - claim tables (定理|结论|前提|策略) parsed before first executable statement, extracted into Function.claims, removed from body - check --proof (default off): proof.claim_malformed / claim_ambiguous / claim_misplaced / claim_duplicate / claim_unknown_symbol / claim_unsupported / name_shadow Runtime layer (src/prove/): - ir.rs: Plan IR with stable hand-rolled JSON (schema 1) - lower.rs: subset acceptance (proof.while / proof.recursion / proof.dynamic_call), inlining for straight-line pure callees, opaque ops with effect labels, --allow-opaque whole-function downgrade - types.rs: literal-driven inference + branch confluence (proof.type_mismatch, exit 1) - emit.rs: deterministic Lean emission (Val × List Op, continuation style, -- mq: line:col anchors, «…» for dotted idents, theorem scaffolds from claims with unfold/split script) - mod.rs: prove/emit/audit/clean commands, Verdict taxonomy (error > unproved > rejected > unverified > checked > proved), exit codes 0/1/2 per design §3.3 Tests: tests/prove.rs 19 integration cases (no Lean required) + module unit tests; full suite stays green except the 3 documented env-limited failures. Docs: doc/design/prove-cli.md (§12 records deviations: result.ok/error vs drafted success/failure, Val-based run at P1, op arity, opaque effect label), doc/roadmap/prove.md, doc/adr/0010. Env fixes carried in: scratch dirs in test helpers honor CARGO_TARGET_DIR (needed on this machine's read-only target/debug). --- doc/README.md | 3 + doc/adr/0010-skill-proof-boundary.md | 79 ++ doc/design/prove-cli.md | 776 ++++++++++++++++ doc/roadmap/prove.md | 409 +++++++++ src/ast.rs | 16 + src/check.rs | 15 +- src/contract.rs | 162 ++++ src/frontend_elaboration_tests.rs | 8 +- src/lib.rs | 1 + src/main.rs | 169 +++- src/parse/mod.rs | 22 +- src/prove/emit.rs | 684 ++++++++++++++ src/prove/ir.rs | 296 ++++++ src/prove/lower.rs | 1241 ++++++++++++++++++++++++++ src/prove/mod.rs | 382 ++++++++ src/prove/proof_check.rs | 842 +++++++++++++++++ src/prove/types.rs | 251 ++++++ src/source_map_tests.rs | 8 +- tests/prove.rs | 670 ++++++++++++++ 19 files changed, 6021 insertions(+), 13 deletions(-) create mode 100644 doc/adr/0010-skill-proof-boundary.md create mode 100644 doc/design/prove-cli.md create mode 100644 doc/roadmap/prove.md create mode 100644 src/prove/emit.rs create mode 100644 src/prove/ir.rs create mode 100644 src/prove/lower.rs create mode 100644 src/prove/mod.rs create mode 100644 src/prove/proof_check.rs create mode 100644 src/prove/types.rs create mode 100644 tests/prove.rs diff --git a/doc/README.md b/doc/README.md index 9dfcacb..4d81fda 100644 --- a/doc/README.md +++ b/doc/README.md @@ -19,6 +19,9 @@ | 文档 | 摘要 | |------|------| +| [design/prove-cli.md](design/prove-cli.md) | **Proposed:`marqdo prove` 设计**;SKILL 控制平面 → Lean 4、函数级定理表与语言习惯审查、离线判定片段、`proved`/`checked` 诚实性契约、无公理 TCB | +| [roadmap/prove.md](roadmap/prove.md) | **Proposed:`marqdo prove` 实施路线**;P0–P3 周计划、8 类测试矩阵(单调性/一致性/不执行/子集/定理表/CLI/缓存/编码)、CI 与验收证据 | +| [adr/0010-skill-proof-boundary.md](adr/0010-skill-proof-boundary.md) | **ADR 0010**:定理表作为契约表第四角色、可证子集封闭、Lean 为唯一 `proved` 来源、顾问式不强制 | | [roadmap/agent-reliability-crossrepo-2026-10-27.md](roadmap/agent-reliability-crossrepo-2026-10-27.md) | **Proposed:跨仓 Agent 可靠性开发计划**;M-A0–M-A6 ∥ Q-A0–Q-A7 排期、依赖图、F01–F20 映射、MA-T*/QA-* 验收与第一刀切片;协议真源仍见下方设计文档 | | [design/agent-reliability-tools-resources-2026-10-27.md](design/agent-reliability-tools-resources-2026-10-27.md) | **Proposed:智能体能力补足**;基于 `16f26d7`,增量设计错误恢复、检查点/效应账本、结构化工具、输出通道、上下文与只读资源视图;含跨仓边界、阶段计划和故障验收 | | [research/agent-capabilities-2026-10-27.md](research/agent-capabilities-2026-10-27.md) | **官方能力调研与源码复核**;OpenAI/Claude/Gemini/LangGraph/Deep Agents/MCP,求道当前问题 F01–F20;区分现有能力、设计推导与待实测项 | diff --git a/doc/adr/0010-skill-proof-boundary.md b/doc/adr/0010-skill-proof-boundary.md new file mode 100644 index 0000000..ed7a93b --- /dev/null +++ b/doc/adr/0010-skill-proof-boundary.md @@ -0,0 +1,79 @@ +# ADR 0010: SKILL 证明边界:定理表、可证子集与顾问式判定 + +| 项目 | 约定 | +|---|---| +| 状态 | **Accepted(决策已定)**;实现未开始,路线见 [roadmap/prove.md](../roadmap/prove.md) | +| 日期 | 2026-11-13 | +| 设计 | [design/prove-cli.md](../design/prove-cli.md) | +| 相关 | [core-surface.md](../design/core-surface.md)(不新增标记)· [layers.md](../design/layers.md)(Language 层扩表角色)· [contract.rs](../../src/contract.rs)(既有契约表提取)· [replay-policy](../../verification/replay-policy/README.md)(Lean 伴随判定先例) | + +## 背景 + +Agent 改写 SKILL 后,人需要逐行确认"分支是否绕开审核、失败是否被吞掉"。这类**控制平面**性质适合形式化:编排是带条件的有限 DAG,没有死循环、没有指针。同时,把整个 Marqdo 当通用语言编译到 Lean 会立刻撞上字符串/JSON/浮点/IO 的语义鸿沟,收益被稀释。 + +项目已有一条 Lean 纪律:`verification/replay-policy` 用 Lean 做唯一判定,Rust 不保留第二份实现,缺伴随进程时失败关闭。本 ADR 决定把同样的纪律用于 SKILL 编排,但**降级为顾问式**:证明用于减少审核量,不作为发布门禁。 + +## 决策 + +1. **定理是契约表的第四种角色**,不是新标记。 + 函数体首条可执行语句之前可放一张「定理表」(`定理 | 结论 | 前提 | 策略`),与 `参数`/`返回`/`字段` 表同槽位;解析期提取进 `Function.claims`,从 body 移除,不参与运行。核心标记计数不变,`CORE_CONSTRUCTS` 不增行;`layers.md` 的 Language 清单补记该角色。 + +2. **可证子集显式封闭**:无 `while`、无递归、无动态派发(插件、变量函数名、`code` 值调用)。越界函数被跳过(`rejected`),不降级成不透明块。外部操作是 `Env := Op → Val` 参数,不是公理;后置条件只能来自 `假设` 表并成为定理前提。 + +3. **Lean 是唯一能产生 `proved` 的判定器**。离线判定只到 `checked`,且被限制在一个极小的片段(路径枚举、轨迹、字面结果、命题组合、单变量区间),凡是离线判定为真的定理都必须同时生成 Lean 脚本。运行期若 Lean 可用则复核;离线 `checked` 而 Lean 未关闭视为内部错误(`proof.divergence`),以 Lean 为准并退出非零。 + +4. **顾问式,不强制**。默认退出码只对"作者写下的定理未被关闭"(`unproved`)与工具错误非零;缺工具链、`rejected`、`unverified` 默认 0。需要严格覆盖的调用方显式传 `--require-lean`。规范与技能手册**推荐**在发布 SKILL 前运行,但不设为门禁。 + +5. **`prove` 不执行被证程序**。只读源码、写缓存与 `--emit` 目录;这一点由测试夹具(带 `fs.write` 的函数)守住。 + +## 备选与取舍 + +| 备选 | 否决理由 | +|---|---| +| frontmatter `proof:` 块 | 丢函数作用域与行级锚点;多函数文件无法分派;诊断指不回具体行 | +| `# 证明` 标题 | `#` 是对象、`##` 是函数;新增"标题=命题"破坏"标题即可调用单元"的既有习惯,还会进命名空间 | +| ` ```proof ` 围栏 | 代码围栏必须跟在空赋值后,为写定理先造死变量,比表更别扭;且会被当作可执行值 | +| 普通注释承载定理 | 注释不参与语义,无法可靠区分说明与定理,拿不到行锚点 | +| 旁挂 `.proof.md` | 把真理拆成两份,违背"文档与代码同一份"的项目前提 | +| 细化类型(refinement types) | 语义增量过大,且与既有契约表形成两份作者真相 | +| 强制门禁(proved 才能发布) | 与"降低审核难度"的目标冲突;无 Lean 的团队会绕过工具 | + +## 后果 + +**正面** + +- 作者在一个地方写清"这条编排保证什么",机器可判定、行号可定位; +- 定理表与契约表同一提取路径,`check` / `view` / `catalog` 可逐步接入,不产生第二套声明; +- 外部依赖以假设形式显式化,证书是本项目一贯的"可复核证据"; +- 不新增核心标记,守卫测试与文档计数不膨胀。 + +**负面 / 代价** + +- 新增一个语言层语义角色与一个 CLI 命令,需要 ADR + 测试 + 文档(本 ADR 即准入材料); +- 离线判定器是新代码,必须长期用 Lean 语料护栏,防止"过度自信"; +- 作者可能误以为定理会在运行时生效——需要文档、`view` 与 `check` 三处反复澄清; +- `proved` 容易被读成"整份 SKILL 安全"——README 必须写死"只对陈述负责"。 + +## 语义增量清单 + +| 新增 | 是否进运行时 | 说明 | +|---|---|---| +| `Function.claims` | 否 | 与 `Function.contract` 同类的声明元数据 | +| `结果` / `轨迹` 与 `包含` / `长度` / `下标` | 否 | 仅定理作用域;与普通表达式作用域隔离 | +| `check --proof` | 否 | 静态校验,默认关 | + +不新增:求值规则、作用域规则、调用约定、核心标记、类型系统扩展。同名遮蔽(参数或局部变量叫 `结果`/`轨迹`)一律报 `proof.name_shadow`,不做隐式优先。 + +## 验收(摘要) + +- 核心表面:`cargo test --test core_surface` 不变红;`CORE_CONSTRUCTS` 计数不变。 +- 单调性:语料中每条离线 `checked` 的定理,Lean 均 `proved`;分歧为 0。 +- 不执行:带 `fs.write` 的夹具在 `prove` 后无副作用。 +- 确定性:同输入两次 `emit` 字节一致。 +- 诚实性:文本、JSON、证书三处对 `checked`/`proved` 的措辞一致。 + +## 未决(不阻塞实现) + +- `假设` 表是否需要扩展列(`来源`、`责任方`)。 +- `--all` 的聚合粒度(按文件/按函数)。 +- 证书是否需要签名,以及签名由谁持有。 diff --git a/doc/design/prove-cli.md b/doc/design/prove-cli.md new file mode 100644 index 0000000..333a6f7 --- /dev/null +++ b/doc/design/prove-cli.md @@ -0,0 +1,776 @@ +# `marqdo prove`:SKILL 编排的 Lean 编译与顾问式证明 + +| | | +|---|---| +| 状态 | **计划(Proposed)· 未实现**;决策已定(§10),实施见 [roadmap/prove.md](../roadmap/prove.md) | +| 日期 | 2026-11-13 | +| 层归属 | **Language**:定理表角色 + `check --proof`(§7,[ADR 0010](../adr/0010-skill-proof-boundary.md))· **Runtime**:`prove` 管线(§4–§6、§8)· **Document**:`verification/skill-proof` 证据 | +| 相关 | [core-surface.md](core-surface.md)(复用 `table` 构造,不新增标记)· [layers.md](layers.md)(准入)· [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [ADR 0010](../adr/0010-skill-proof-boundary.md) · [verification/replay-policy](../../verification/replay-policy/README.md)(Lean 伴随判定的先例) | +| 目标版本 | CLI **2.8.0**(wasm / ext 不随动:`prove` 不进 wasm) | + +--- + +## 0. 一句话与三条契约 + +`prove` 把一份 `.mq.md` 的**控制平面**(参数 → 分支 → 外部操作 → 返回值)降级成 Lean 4 定义,把作者声明的**定理**变成 Lean 定理,并尽最大努力自动关闭它们;同时输出一份可供人复核的证据(证书、假设、被拒清单)。它**不**是发布门禁,也**不**声称"过了 Lean 就绝对正确"。 + +三条契约,按优先级排列: + +1. **诚实**:`proved` 只表示"Lean 内核接受了这条形式化陈述"。它不表示陈述写对了意图、不表示外部 API 会守约、更不表示整份 SKILL 安全。反过来,`unproved` 只表示"这次没有关闭它"——可能是定理不成立,也可能只是策略不够。 +2. **单调**:离线判定(没有 Lean 时)**只能**给出 Lean 也能给出的结论。若两者分歧,以 Lean 为准并报内部错误,绝不放绿。`checked` 永远弱于 `proved`。 +3. **不执行**:`prove` 从头到尾不运行被证程序,不产生任何效应;它只读源码、写缓存与 `--emit` 目录。 + +> 一句话给论文:*给编排文档配一张可复核的证明收据*,而不是给整个语言发一张正确性证书。 + +--- + +## 1. 定位:降低审核量,不取代审核 + +### 1.1 为什么是顾问而不是门禁 + +Agent 改写 SKILL 后,人要看的是"这一步会不会绕开审核""失败分支会不会吞掉错误"。这些恰好是控制平面命题,Lean 能帮我们把"逐行读代码"压缩成"读几条定理 + 看一眼反例"。但: + +- 真实 SKILL 里有字符串、JSON、外部服务;把这些都形式化,成本远高于收益; +- 形式化陈述与业务意图之间永远隔着"作者写得对不对"; +- 大多数团队没有 Lean,强制门禁只会让人绕过工具。 + +所以 `prove` 的默认行为是**报告**,不是**拦截**。规范与手册**推荐**在发布 SKILL 前跑一次,但不强求;要不要把某个状态当失败,由调用方用 `--require-lean` / `--report-only` 自己决定。 + +### 1.2 三种"绿"和两种"红" + +| 状态 | 含义 | 由谁产生 | 能不能当"已证明" | +|---|---|---|---| +| `proved` | 全部定理被 Lean 内核接受 | Lean | **能**(且仅限陈述本身) | +| `checked` | 全部定理在离线片段(§5)内判定为真,已生成对应 Lean 脚本但未运行 | 离线判定 | **不能**,只能说"离线判定通过" | +| `unverified` | 有定理超出离线片段,且没有跑 Lean | 离线判定 | 不能 | +| `unproved` | 至少一条定理未被关闭;若能给出反例则附见证 | Lean / 离线 | 不能;这是红灯 | +| `rejected` | 有函数不在可证子集(`while`/递归/动态派发),已跳过 | 降级器 | 不能;这是"未覆盖",不是"错误" | + +`rejected` 与 `unproved` 的区别很重要:前者是**工具够不着**,后者是**命题没过**。把它们混成一个红,会让"文件里有个循环"看起来像"业务逻辑错了"。 + +此外还有 `error`(编码/类型/效应/IO/超时):它不是判定结果,而是**工具或程序本身出错**,退出 1。五种判定(proved/checked/unverified/unproved/rejected)与 `error` 在 JSON 里共用 `status` 字段,但语义分组不同,报告会分开统计。 + +### 1.3 诚实性词汇表(写进 README 与 `--json`) + +- `proved` ≠ 正确:它只对**写下来的陈述**负责,且假设 `Env` 的返回值任意、`假设` 表成立。 +- `unproved` ≠ 错误:策略失败、超时、片段外都可能;只有带 `counterexample` 字段时才是"确实不成立"。 +- `rejected` ≠ 不安全:只表示这部分没被形式化覆盖。 +- 证书不替代代码评审:它是**缩小**评审范围的工具,`audit` 会明确列出"哪些外部操作完全未知"。 + +### 1.4 非目标 + +- 不形式化解释器、字符串库、JSON、浮点、`formula`。 +- 不证明外部服务与网络;这些由 `假设` 表显式承担。 +- 不在 Agent 每次运行时跑 Lean;运行期只读证书。 +- 不自动安装 Lean;只探测并给出可执行提示。 +- 不追求"零人工":目标是让人从"读 200 行"变成"读 5 条定理 + 1 张假设表"。 + +--- + +## 2. 证明范围 + +### 2.1 义务分级 + +| 级别 | 义务 | 作者要写什么 | 谁保证 | 离线可做 | +|---|---|---|---|---| +| **T0 类型** | 生成的 Lean 通过内核;字段、元数、分支同型 | 无 | Lean | 部分(Rust 类型检查) | +| **T1 结构** | 终止(无 `while`/递归 ⇒ 结构递归)、分支出口完整、返回类型符合 `返回` 契约、效应不越权(给了 `--effects` 时) | 无 | 降级器 + Lean | 是 | +| **T2 声明** | 定理表里的业务命题 | 定理表 | Lean / 离线片段 | 是(F1–F5) | +| **T3 契约** | 外部操作前置/后置假设下的组合推理 | `假设` 表 | Lean | 部分 | +| **T4 一致性** | 生成语义与解释器在纯片段上同值 | 测试语料 | 差分测试 | 是 | + +### 2.2 三条硬边界(拒绝,不降级) + +| 构造 | 处理 | 诊断码 | +|---|---|---| +| `while`(`-` + 条件行) | 跳过该函数 | `proof.while` | +| 直接/间接递归(调用图有环) | 跳过该环 | `proof.recursion` | +| 动态派发(插件调用、变量函数名、`code` 值调用) | 跳过该调用点 | `proof.dynamic_call` | + +被跳过的函数不参与定理,其余函数照常出证。整体状态按固定优先级合成(差者胜):`error` > `unproved` > `rejected` > `unverified` > `checked` > `proved`。`--allow-opaque ` 可把某个被跳过的函数**整体**降级为不透明操作,让调用它的编排仍可证——此时它的行为完全未知,`audit` 必须列出来。 + +--- + +## 3. 命令面 + +### 3.1 命令与别名 + +```bash +marqdo prove [PATH] # 降级 → 生成 → 离线判定 →(有 Lean 时)Lean 判定 +marqdo prove emit [PATH] -o DIR # 只生成 Lean,不判定(离线/论文/AI 取用) +marqdo prove audit [PATH] # 只报降级结论:内联了什么、不透明了什么、拒了什么、假设了什么 +marqdo prove clean # 清 .marqdo/prove 缓存 +``` + +`prove` 带 `visible_alias = "lean"`;文档与 CI 统一写 `prove`。它与既有 `verify` 不重叠:`verify` 查知识一致性,`prove` 查控制平面命题。 + +### 3.2 参数 + +| 参数 | 默认 | 含义 | +|---|---|---| +| `PATH` | `index.mq.md` | 单个 `.mq.md`;目录需 `--all` | +| `--all` | off | 目录递归(跳过 `target`/`dist`/`node_modules`/`.git`/`.marqdo`);`--max-files ` 默认 200 | +| `--entry ` | `main` | 入口与报告分组;不限制文件内全量证明 | +| `--only ` | — | 只证这些函数(可重复),用于增量 | +| `--emit ` | `.marqdo/prove//Generated` | 保留生成的 Lean | +| `--json` | off | stdout 一个 JSON 对象(§3.5);诊断走 stderr | +| `--lean ` / `--lake ` | 探测 | 显式工具链 | +| `--library ` | 探测 | `MarqdoProof` 库目录 | +| `--timeout ` | 120 | 单次 Lean 调用上限 | +| `--heartbeats ` | 400000 | `maxHeartbeats` | +| `--no-cache` | off | 绕过证书与 olean 缓存 | +| `--no-offline` | off | 跳过离线判定,只用 Lean(CI 复现/调试用) | +| `--require-lean` | off | 严格模式:`checked`/`unverified`/`rejected` 一律返回 2 | +| `--report-only` | off | 除工具错误外恒返回 0 | +| `--allow-opaque ` | — | 把被跳过的函数降级为不透明操作 | +| `--effects ` | — | 与 `marqdo call --effects` 同格式;给出时检查实际调用是否越权 | +| `--strict-types` | on | 类型无法推断即报错;`--no-strict-types` 落 `Val`(证明力下降,报告标注) | +| `--tactic ` | `auto` | 定理表未写 `策略` 时的默认策略 | + +### 3.3 状态与退出码 + +| 状态 | 退出码 | `--require-lean` | `--report-only` | +|---|---|---|---| +| `proved` | 0 | 0 | 0 | +| `checked` | 0 | **2** | 0 | +| `unverified` | 0 | **2** | 0 | +| `rejected` | 0 | **2** | 0 | +| `unproved` | 1 | 1 | 0 | +| `error` / `timeout` | 1 | 1 | 1 | + +设计理由: + +- 缺工具链、有循环、定理在片段外,都**不是**程序的错,默认不返回非零——否则没装 Lean 的机器上 `prove` 等于不可用。 +- 默认情况下只有两种非零来源:**你写下的定理未被关闭**(1),或**工具出错**(1)。不写定理就不会有第一类失败。 +- 想要严格覆盖的团队用 `--require-lean`,把"未判定"升级成 2;CI 里加这一个参数即可。 +- 全局开关 `--report-only` 让 Agent 在探索期只看报告。 + +### 3.4 文本输出 + +```text +$ marqdo prove skills/marqdo-release/index.mq.md +审批 2/2 定理 proved Lean 0.8s +plan 1/1 定理 checked 离线判定 12ms(附 Lean 脚本,未运行) +预检 — rejected 离线 3ms proof.while L88 +prove: proved 1 · checked 1 · rejected 1 + 说明: checked 不代表 Lean 已验证;安装 Lean 或传 --lean 可交由 Lean 判定。 + 提示: `marqdo prove audit …` 查看降级细节与假设清单。 +``` + +失败时: + +```text +error[proof.claim_failed]: 定理「不该自动放行」未被关闭 + --> examples/approval.mq.md:31:3 + = 目标: (run env p).1.ok = false + = 上下文: h : p.amount > 10000 + = 反例: 金额 = 10001 时走「人工审核」分支,结果 ok = true + = 说明: 可能是命题不成立,也可能是策略不够;补 `策略` 或改判据后重跑。 +``` + +### 3.5 JSON(面向智能体的稳定契约) + +一个对象,`schema` 版本化;永不交互、stdout 只有结果、诊断在 stderr、路径为相对工作目录: + +```json +{ + "schema": 1, + "status": "checked", + "file": "skills/example/index.mq.md", + "source_sha256": "…", + "artifact_id": "mq://…", + "functions": [{ + "name": "审批", + "status": "checked", + "tier": "offline", + "claims": [ + {"id": "大额必经人工", "status": "checked", "decided_by": "trace", "ms": 3}, + {"id": "退款必须留痕", "status": "unverified", "reason": "out_of_fragment"} + ], + "obligations": [{"id": "terminates", "status": "passed"}, + {"id": "effects_subset", "status": "skipped", "reason": "no --effects"}] + }], + "lean": null, + "assumptions": [], + "diagnostics": [], + "emitted": [".marqdo/prove/ab12…/Generated/Approval.lean"], + "duration_ms": 15 +} +``` + +`lean` 为 `null` 表示没跑;跑了则是 `{"toolchain": "...", "library_sha256": "...", "module_sha256": "...", "cache": "hit|miss"}`。`tier` ∈ `{lean, offline, none}`,标明该函数的结论来自哪一层。`status` 的取值集合固定(§1.2),Agent 可按它分支,不需要解析自然语言。 + +### 3.6 面向智能体的使用契约 + +`prove` 的主要调用者不是人,是 Agent 的循环。因此: + +- **一次调用一个结论**:不做交互式提问,不读 TTY,不依赖环境变量之外的隐藏状态。 +- **只解析 JSON**:`--json` 的键与状态词是稳定契约(`schema` 升级才变);stdout 不混入程序输出或进度条。 +- **失败即数据**:每条诊断都有 `code` / `file` / `line` / `column` / `message`,能定位的还带 `goal`、`context`、`counterexample`、`hint`。Agent 不需要从自然语言里猜。 +- **可增量**:`--only ` 只证受影响函数;证书命中让第二轮降到毫秒级。 +- **先审计再证明**:Agent 应先 `prove audit --json` 看"有多少内联、多少不透明、多少被跳过",再决定是否值得为该文件写定理。 +- **推荐循环**:写 SKILL → `check` → `prove --json` → 读 `claims[].status` → 改代码/定理/策略 → 重跑 → 把证书附进交付说明。 + +### 3.7 选择规则 + +- **文件**:显式路径;目录必须 `--all`(否则 `proof.need_all`)。 +- **函数**:文件内全部 `##` 函数默认参与;`# main` 只作分组。 +- **导入**:默认内联可判定的纯函数(§4.5),其余成为不透明操作;不递归证明被导入文件。 +- **`--all` 聚合**:逐文件出状态,整体取最差;`--json` 输出 `files: [...]`。 + +--- + +## 4. 管线 + +### 4.1 六段 + +```text +.mq.md + ① 装载 load_module(只读,不执行) + ② 降级 AST → Plan IR:子集验收、拒绝码、span + ③ 定型 contract::Ty 驱动;未定 ⇒ 报错或 Val + ④ 生成 IR → Lean(确定性:稳定排序、无时间戳、相对路径) + ⑤ 离线判定 符号执行 + 片段判定(§5),产出 checked / 反例 / unverified + ⑥ Lean 判定 有工具链时运行;以它为准,与 ⑤ 分歧即 error +``` + +⑤ 永远在 ⑥ 之前:离线先给快速反馈,Lean 随后确认。`--no-offline` 可只跑 ⑥。 + +### 4.2 Plan IR + +`src/prove/ir.rs`,`serde` 序列化为 `plan.json`(版本化,缓存键的一部分,论文工具可直接消费): + +```jsonc +{ + "schema": 1, + "module": "skills/example/index.mq.md", + "source_sha256": "…", + "functions": [{ + "name": "审批", + "params": [{"name": "金额", "ty": {"kind": "int"}}], + "result_ty": {"kind": "map", "fields": [["ok","bool"],["value","any"],["error","any"]]}, + "ops": [{"id": "人工审核", "effect": "network.read", "params": [["金额","int"]]}], + "steps": [ + {"kind": "if", "cond": {"op": "gt", "args": [{"var": "金额"}, {"int": 10000}]}, + "then": [{"kind": "bind", "var": "审核", "expr": {"call": "人工审核", "args": [{"var": "金额"}]}}, + {"kind": "return", "expr": {"ctor": "result.ok", "args": [{"var": "审核"}]}}], + "else": [{"kind": "return", "expr": {"ctor": "result.ok", "args": [{"text": "auto"}]}}], + "span": {"line": 21, "col": 1}}], + "claims": [{"id": "大额必经人工", "premise": null, "conclusion": "…", "tactic": null}], + "effects": ["network.read"], + "assumptions": [] + }] +} +``` + +表达式分两层:`PureExpr`(字面量、变量、算术/比较/布尔、字符串拼接与插值、列表/映射字面量、`access`、`len`、类型转换)可翻译成 Lean 项;其余一律 `Call`(不透明操作),或按 §4.3 拒绝。**没有"猜"的回退。** + +### 4.3 接受 / 拒绝矩阵 + +| Marqdo | 处理 | 备注 | +|---|---|---| +| `**x = 纯表达式**` | `bind` | 类型由右值推断 | +| `**x = [标签](调用)**` | `bind` + `Op` + `trace` | 效应来自 sema | +| `**x**`(粗体无赋值) | `return` | 纯表达式或已内联构造器 | +| `*语句*` / `> 调用` | 语句形式,值丢弃 | 丢弃的调用仍进 trace | +| `1. 条件 / 2. *` | `if/else` | 条件必须是纯布尔表达式 | +| `- [项](遍历 列表 为 项)` | `foreach`(P3) | 只接受有限列表;此前 `proof.foreach_pending` | +| `-` + 条件 | **跳过** `proof.while` | | +| 递归 | **跳过** `proof.recursion` | 调用图环检测 | +| 方法调用 `` `recv`.方法 `` | 不透明操作 | 接收者不展开 | +| `code` 值 / 插件调用 | **跳过** `proof.dynamic_call` | 不在纯片段 | +| GFM 表绑定 | `list`/`map` 字面量 | 列长不一致已在解析期拒绝 | +| `$$` 公式 | 不透明值(`Formula`) | 不翻译 TeX,不做推理 | + +### 4.4 类型推断 + +起点:`参数` 表 + `返回` 表(`contract::Ty`)。合一规则: + +- 字面量给最具体类型;`+ - * /` 要求两侧 `int`;`and/or/not` 要求 `bool`。 +- 分支合流:两臂同名变量类型必须相容,否则 `proof.type_mismatch`(带两处行号)。 +- 映射字段:返回表达式是映射字面量时得到 `structure`;是内联的 `result.ok/error`(lib/result 真实 API)时沿用 Result 形状;否则落 `Val`,此时 `结果.ok` 报 `proof.result_untyped`(提示:返回映射字面量或包成 Result)。 +- `--no-strict-types` 时未知类型落 `Val`;定理里只能做等式/成员判断,报告标注"弱类型"。 + +### 4.5 内联与不透明化 + +1. 建调用图(本文件 + 导入文件);有环即跳过该环。 +2. **内联**:被调函数(含 `lib/result` 一类纯库)满足 ①契约 `Effects: pure` ②语句数 ≤ 24 ③不含被跳过构造 ④非递归 → 展开函数体。这样 `result.ok(...)` 在 Lean 里就是 Val 映射构造(`mqResultOk`),`结果.ok` 变成可判定字段。 +3. **不透明化**:其余调用生成 `Op` 构造器 + 效应,由 `Env` 参数处理;`--allow-opaque` 可强制。 +4. `audit` 逐条列出:内联 / 不透明 / 跳过,以及每个不透明操作的效应与参数类型。 + +--- + +## 5. 离线判定(没有 Lean 也能给结论) + +### 5.1 为什么需要 + +- 大多数开发机与 CI 没有 Lean;没有离线路径,`prove` 就只是"生成器"。 +- Agent 迭代需要毫秒级反馈,Lean 一次数百毫秒到数十秒。 +- 反例("金额 = 10001 时轨迹里没有人工审核")比 tactic 失败更有用。 + +但离线**绝不能**比 Lean 强。做法不是"相信我们的判定器",而是把它关进一个**极小的片段**,并让每条离线结论都附带 Lean 脚本。 + +### 5.2 片段 F1–F5(保守,超出即 `unverified`) + +| 片段 | 能判定什么 | 为什么安全 | +|---|---|---| +| **F1 路径枚举** | 控制流是有限树(无循环/递归)⇒ 返回路径有限 | 由 §2.2 的拒绝保证 | +| **F2 轨迹** | 每条路径的 `Op` 序列由分支决定;`包含/长度/下标` 逐路径求值 | 轨迹是语法产物,不依赖 `env` 返回值 | +| **F3 字面结果** | 返回表达式只由字面量、参数、内联构造器组成时按结构求值 | 与 Lean 的 `mqResultOk` 形状一一对应 | +| **F4 命题** | `and/or/not`、`=/≠` 作用于 F2/F3 的布尔结果;外部返回值上的**布尔判定**(如 `access(回执,"ok") == False`)视为自由原子,可分叉 | 自由原子只做二分、不假设原子间关系;两条分支都关闭才 `checked`,因此证明是对任意 `env` 成立的 | +| **F5 单变量区间** | 原子 `x ⋈ c`(`c` 为整数字面量,`⋈ ∈ {<,≤,>,≥,=,≠}`);用路径条件 + 前提的上下界判定蕴含 | 单变量区间推理是线性整数算术的子集,`omega` 必然也能证 | + +明确**不**离线判定(直接 `unverified`,不猜):多变量线性组合、非线性算术、字符串比较、外部返回值的非布尔字段(`.value` 之类)、任何需要归纳的命题。 + +### 5.3 判定过程 + +1. 符号执行函数体:状态 `Var → SymVal`(`Const` / `Param` / `OpResult` / `Unknown`),路径条件为原子列表,轨迹为 `Op` 列表。 +2. 每个 `if` 分叉两支(条件 / 其否定);每个 `Op` 调用产生一个 `OpResult` 符号(值未知,但**出现**已知)。 +3. 每个 `return` 收集 `(路径条件, 结果 SymVal, 轨迹)`。 +4. 对每条路径检查 `前提 ∧ 路径条件 ⊢ 结论`:把 `结果/轨迹` 代入后按 F2–F5 求值或判定。 +5. 全部路径关闭 ⇒ 该定理 `checked`;任一原子超出片段 ⇒ `unverified`;某条路径可满足且结论为假 ⇒ `unproved` + 反例。 + +### 5.4 证书与"单调性" + +每条 `checked` 定理同时产出: + +- **情形证书**:`(路径 id, 路径条件, 规范化目标, 关闭理由 ∈ {literal, hypothesis, interval, atom})`,写进 `certificate.json`; +- **Lean 脚本**:`unfold run` 后按同一棵 `if` 树 `split_ifs`,每个叶子 `simp_all <;> omega`。离线情形树与 Lean 的 `if` 树来自同一份 IR,叶子一一对应;某个叶子离线关闭而 Lean 关不掉,就是 `proof.divergence`。 + +因此"离线判定 ⊂ Lean 判定"不是口头承诺,而是三件事: + +1. **构造上**:F5 的推理是 `omega` 的子集,F1–F4 是 `simp`/`decide` 的子集; +2. **运行期**:只要有 Lean,就在 ⑥ 复核;`checked` 但 Lean 未关闭 ⇒ `error[proof.divergence]`,退出 1,永不落绿; +3. **测试上**:语料库强制 `offline_checked ⊆ lean_proved`(roadmap 测试矩阵 A1)。 + +**不夸大**:我们不说"离线判定器已被证明正确"。我们说它片段极小、保守、每条结论都带 Lean 脚本,且有运行期复核与 CI 语料强制。 + +### 5.5 反例 + +当某条路径可满足、且结论在该路径上求值为假时,从区间端点取一组参数值作为见证: + +```text +反例: 金额 = 10001 +路径: 金额 > 10000 → 人工审核 +结论: 结果.ok = False +实际: 结果.ok = True(人工审核的返回值被包进 result.ok) +``` + +反例只承认**确定性否定**:结论必须是字面 `false`,路径必须由区间证明可满足,且路径条件里**不含自由布尔原子**(否则可能凑出真实语义下不存在的组合)。任何一条不满足就退回 `unproved`(无见证)或 `unverified`,不编故事。 + +--- + +## 6. Lean 编码 + +### 6.1 产物布局 + +```text +verification/skill-proof/ # 入仓:语义库 + 论文样例(人工评审) + lean-toolchain # 与 replay-policy 同钉(v4.35.0) + lakefile.lean + MarqdoProof.lean + MarqdoProof/{Basic,Result,Tactic}.lean + examples/{approval,false-claim}.lean + README.md # TCB 与"证了什么"的边界声明 + LIBRARY-SHA256 # 由构建脚本写入 + +.marqdo/prove/ # 生成物(.marqdo/ 已 gitignore) + pkg/ # 一次性 Lake 包(库副本 + Generated/) + /plan.json module.lean certificate.json lean.log + index.json # key → 指纹/状态/耗时 +``` + +### 6.2 无公理:操作是参数,假设是前提 + +```lean +-- 库提供(MarqdoProof/Basic.lean,节选) +inductive Val | none | int : Int → Val | str : String → Val | bool : Bool → Val + | list : List Val → Val | map : List (String × Val) → Val + +structure Err where code : String; message : String; operation : String +structure Result where ok : Bool; value : Val := .none; error : Option Err := none + +-- lib/result 的真实构造器(ok/error/value_or)映射: +def Result.success (v : Val) : Result := { ok := true, value := v } +def Result.failure (e : Err) : Result := { ok := false, error := some e } +``` + +生成文件里**不出现 `axiom`,也不出现 `opaque`**:外部操作是 `Env := Op → Val` 参数,后置条件是定理的假设 `h_post`。于是 `#print axioms` 为空,定理陈述本身就把"信任了什么"写清楚。 + +### 6.3 直接风格降级(无 monad、无 `do`) + +`StateM`/`do` 在证明里要额外展开 monad 定律,早返回的语义也容易踩坑。改用**续延式直接风格**:`compile_stmts(stmts, k)` 在 Rust 里把后续语句当续延,早返回就是"把 `k` 换成函数出口"。产出的 Lean 是纯 `let`/`if`/`pair`,`simp`/`split`/`omega` 直接可用。 + +输入(`verification/skill-proof/examples/approval.mq.md` 节选): + +```markdown +## 审批 ++ `金额` + +| 参数 | 类型 | 说明 | +|---|---|---| +| 金额 | int | 申请金额(元) | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result | + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | + +1. `金额` > 10000 + **审核 = [提交人工审核](人工审核(金额=`金额`))** + **结果 = [保留人工审核结论](result.ok(value=`审核`))** +2. * + **结果 = [自动通过](result.ok(value="auto"))** + +**结果** +``` + +输出: + +```lean +import MarqdoProof +open MarqdoProof + +namespace Generated.Approval + +structure Params where + 金额 : Int + deriving Repr, DecidableEq + +inductive Op where + | 人工审核 (金额 : Int) + deriving Repr, BEq + +def Op.name : Op → String + | .人工审核 _ => "人工审核" + +abbrev Env := Op → Val + +def run (env : Env) (p : Params) : Result × List Op := + if p.金额 > 10000 then + let v := env (.人工审核 p.金额) + (Result.success v, [.人工审核 p.金额]) + else + (Result.success (.str "auto"), []) + +theorem 大额必经人工 (env : Env) (p : Params) (h : p.金额 > 10000) : + (run env p).2.any (fun o => o.name == "人工审核") = true := by + unfold run + split_ifs <;> simp_all <;> omega + +end Generated.Approval +``` + +要点:每步带 `-- mq: line:col` 注释;中文标识符直接可用,含点/空格的用 `«…»`;命名冲突在生成前消解。 + +### 6.4 义务与定理 + +| 项 | 形状 | 来源 | +|---|---|---| +| 类型检查(T0) | 文件通过内核:字段、元数、分支同型 | Lean,编译结果即证据 | +| 终止(T1) | 无 `while`/递归 ⇒ Lean 接受为 `def` | 同上;需要 `partial` 的一律已跳过 | +| `effects_subset` | 实际 `Op` 集合 ⊆ `--effects` 授权 | Rust 判定,写证书 `obligations` | +| 作者定理(T2) | `∀ p, pre p → post p (run env p)` | 定理表 | +| 假设(T3) | `h_* : ∀ …, Post …` 作为定理前提 | 假设表 | + +违反 `effects_subset` 不是 `rejected` 而是 `error[proof.effects_exceeded]`:前者是"够不着",后者是"够得着且越权",必须区分。未给 `--effects` 时该义务记为 `skipped`,不假装通过。 + +### 6.5 策略 + +```lean +macro "mq_auto" : tactic => + `(tactic| first + | decide + | omega + | simp_all + | (split <;> simp_all) + | (split_ifs <;> simp_all <;> omega) + | aesop) +``` + +定理表 `策略` 列可写 `auto` / `omega` / `simp [run]` / 任意 tactic 片段;写 `none` 表示只生成不证(论文留人工证明钩子),状态记 `unverified` 而不是失败。 + +### 6.6 源码映射 + +每个语句前放 `-- mq: :`;`module.lean` 与 `plan.json` 同缓存。Lean 报 `Generated/X.lean:41:7: error: …` 时,驱动把 41 映射回 `.mq.md` 行,诊断指回源码,`lean_line` 放在 JSON 细节里。映射表进证书。 + +--- + +## 7. 作者面:定理表与语言习惯 + +### 7.1 语法与位置 + +表格构造**已有**(不新增核心标记),这里只给它一个新的**语义角色**: + +```markdown +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | +``` + +规则(与 `参数/返回/字段` 契约表同构): + +1. 表头别名:`定理/证明/claim/theorem`;列名 `结论/conclusion`、`前提/premise`(可缺省)、`策略/tactic`(可缺省)。 +2. 位置:函数体**首条可执行语句之前**,与契约表同一槽位;提取后从 body 移除,**不参与运行**。出现在别处仍是普通表,`check --proof` 报 `proof.claim_misplaced`。 +3. 一行一条;`定理` 列是函数内唯一 id,重复即 `proof.claim_duplicate`。 +4. 结论/前提是**受限表达式**:参数、`结果`、`轨迹`、`包含/contains`、`长度/length`、`下标/index`,以及算术/比较/布尔。其他名字 → `proof.claim_unknown_symbol`(带最近建议)。 +5. 一张表如果既像契约表(有 `类型` 列)又像定理表(有 `结论` 列)→ `proof.claim_ambiguous`,不猜。 + +### 7.2 语义 + +一条定理展开为: + +```lean +theorem (env : Env) (p : Params) (h : <前提>[p]) : + <结论>[p, (run env p)] := by … +``` + +- 前提在**入口状态**求值(参数),结论可引用参数、`结果`、`轨迹`。 +- 没有前提就是全称命题;`结果.ok = True` 天然表示"所有成功终止都满足"。 +- `轨迹` 有序;`包含/长度/下标` 三个谓词够表达"存在/顺序/计数",不再长大。 +- 定理是**声明**,不是代码:没有求值顺序、没有副作用、不能调用任意函数。 + +### 7.3 语言习惯审查(是否引入了多余语义) + +这是这次设计最需要交代清楚的一节。逐条回答"会不会破坏语言习惯"。 + +#### 7.3.1 实际新增了什么 + +| 新增项 | 性质 | 是否影响运行 | +|---|---|---| +| `Function.claims` 元数据 | 声明(与 `Function.contract` 同类) | **否**,提取后从 body 移除 | +| 定理作用域的两个保留名(`结果/轨迹`)与三个谓词 | 只在定理内可见的绑定 | **否**,不在普通表达式作用域 | +| 假设表作用域的 `返回` | 只在假设表内可见的绑定 | **否** | +| `check --proof` | 静态校验开关,默认关 | 否 | + +除此之外没有新语法、没有新标记、没有新求值规则、没有新类型系统。 + +#### 7.3.2 没有新增什么(逐项对照) + +| 风险项 | 结论 | 依据 | +|---|---|---| +| 新核心标记? | 否 | 用的是既有 GFM 表(`core-surface.md` 的 `table`);`CORE_CONSTRUCTS` 计数不变 | +| 新求值顺序/作用域? | 否 | 定理表与契约表一样,在解析期提取,不进 AST body | +| 新调用约定/形参? | 否 | 不要求调用者传证明参数,不给函数加隐藏形参 | +| 新类型系统(refinement/依赖类型)? | 否 | 只在表里写命题;不做类型层扩展 | +| 影响叙述比例/可读性? | 否 | 表是 code 构造;GitHub 渲染正常;`labels`/`narrative_ratio` 行为不变 | +| 影响 `check` 既有诊断? | 否 | 新表头不命中 `参数/返回/字段`,`parse_contract_table` 不认领;新增校验默认关 | + +#### 7.3.3 为什么不是别的写法 + +| 备选 | 为什么不用 | +|---|---| +| frontmatter `proof:` 块 | 丢函数作用域与行级锚点;一个函数一条定理时锚点落在文件头,诊断无法指回具体行;多函数文件无法分派 | +| `# 证明` 标题 | `#` 是对象、`##` 是函数,标题即单元——新增"标题=命题"会破坏"标题即可调用单元"这条既有习惯,且会进命名空间 | +| 围栏块(` ```proof ` 语言标签) | 代码围栏必须跟在空赋值后(`x =` + fence),否则解析器直接报错;为了写定理先造一个死变量,比表更别扭,且该值会被当作可执行值 | +| 注释里写定理(``) | 注释不参与语义,也拿不到行锚点;工具无法可靠区分"说明"与"定理" | +| 单独 `.proof.md` 旁挂文件 | 真理被拆成两份,正是这个项目一直在避免的事("代码与文档同一份") | +| 类型即契约(refinement) | 语义增量太大,且现有契约表已经承担类型声明;再来一套会形成"两份作者真相" | + +函数级表格是最符合本项目习惯的:**声明与函数同址、可定位、可校验、不可执行**——这正是 `参数/返回/字段` 表已经建立的模式。 + +#### 7.3.4 命名冲突与遮蔽 + +- 定理作用域里 `结果`/`轨迹`、假设作用域里 `返回` 是保留名。若函数有形参或局部变量同名,`check --proof` 报 `proof.name_shadow`(错误),要求改名——**不**做隐式优先,避免"同名不同义"。 +- 谓词名 `包含/长度/下标` 若与用户函数同名,同样报 `proof.name_shadow`,不做静默覆盖。 + +#### 7.3.5 仍然存在的风险与护栏 + +| 风险 | 说明 | 护栏 | +|---|---|---| +| "定理像代码"的错觉 | 作者可能以为 `结果.ok = False` 会在运行时求值 | 文档措辞统一为"声明";`view` 渲染成定理卡片;`check` 提示不可运行位置 | +| 定理表长出第二门语言 | 有人想写量词、自定义谓词、调用函数 | 谓词集合封闭(3 个);超出即 `proof.claim_unsupported`;ADR 改集合需重新评审 | +| 定理与代码漂移 | 改了分支但没改定理 | 定理锚定行号;`check --proof` 校验引用的变量仍存在;`prove` 每次重证 | +| 定理变成装饰 | 写了 `策略 none` 或永远 `unverified` | `audit` 统计"声明/已判定/未判定";证书只记录实际判定结果 | +| 表被误当数据表 | 普通文档表恰好叫 `定理` | 只有表头命中且列形正确才认领;两列的"定理/说明"表仍是普通表 | + +结论:**语义增量被压到三条声明级绑定,且不进入运行时**。它没有引入新的编程习惯,只是把"契约表"这一既有习惯扩展到"命题"。 + +### 7.4 假设表(T3) + +外部操作默认完全未知。要让"只要银行返回失败,我们就不会记账"这类推理成立,把假设写成表: + +```markdown +| 假设 | 前置 | 后置 | +|---|---|---| +| 银行.转账 | 金额 > 0 | 返回.ok = True | +``` + +- 表头 `假设/assumption`;`操作` 列是调用显示名(`库.成员`)。 +- 前置在实参上求值;后置在 `返回`(操作返回值)上求值;支持 `=/≠/包含/长度` 与 `返回.ok`(映射字段读取的语法糖)。 +- 生成 Lean 时不是公理,而是**定理前提**:`h_转账 : ∀ a, a > 0 → (env (.转账 a)).field? "ok" = some (.bool true)`。 +- 无法定型的后置 → `proof.assumption_untyped`(提示改成等式或补返回契约)。 +- `audit` 与证书 `assumptions` 一一对应。 + +### 7.5 与 `check` / `view` / `catalog` + +- `check`:新增 `--proof`(**默认关**,保持既有性能),校验表形、名字、片段;不跑 Lean。 +- `view`:定理表渲染成"已声明定理"卡片;有证书时附状态徽标(`proved`/`checked`/`unverified`)。不触发证明。 +- `catalog`/`knowledge`:`Artifact` 增可选 `proof:` 摘要(证书哈希 + 状态 + 定理数),供 EKM 与 `reuse` 过滤;不改变现有 schema 必填项。 + +--- + +## 8. 工程落点 + +### 8.1 新增 / 修改文件 + +| 文件 | 变更 | +|---|---| +| `src/prove/mod.rs` | API、状态机、报告聚合 | +| `src/prove/ir.rs` | Plan IR + 规范化 JSON + 指纹 | +| `src/prove/lower.rs` | AST → IR、子集验收、拒绝码、内联 | +| `src/prove/types.rs` | 类型推断与合一 | +| `src/prove/emit.rs` | IR → Lean(确定性、命名消解、span 注释、脚本生成) | +| `src/prove/offline.rs` | 符号执行、F1–F5 判定、反例 | +| `src/prove/driver.rs` | 工具链探测、Lake 包、`lean` 调用、超时、诊断映射 | +| `src/prove/cache.rs` | 证书、`index.json`、失效判定 | +| `src/prove/report.rs` | 文本 / `--json` 渲染 | +| `src/ast.rs` | `Function.claims: Vec` | +| `src/claim.rs`(或并入 `contract.rs`) | 定理表提取与校验 | +| `src/parse/mod.rs` | 定理表提取入口(首条可执行语句前) | +| `src/check.rs` | `--proof` | +| `src/main.rs` | `Commands::Prove`、`ProveAction`、json_errors | +| `src/lib.rs` | `pub mod prove;` | +| `verification/skill-proof/**` | Lean 库、样例、`LIBRARY-SHA256`、README | +| `tests/prove.rs` + `tests/prove/**` + `tests/prove_lean.rs` | 集成测试、夹具、Lean 语料(独立目标) | +| `.github/workflows/proof.yml` | elan + `lake build` + 语料门禁 | + +不新增 crate 依赖(`serde_json`、`sha2`、`anyhow` 已在);Lean 侧零依赖(只用 Std)。 + +### 8.2 API + +```rust +pub struct ProveOptions { + pub entry: Option, + pub only: Vec, + pub allow_opaque: Vec, + pub emit_dir: Option, + pub effects: Option, + pub strict_types: bool, + pub offline: bool, + pub timeout: Duration, + pub heartbeat: u64, + pub require_lean: bool, + pub report_only: bool, + pub no_cache: bool, + pub lean: Option, + pub library: Option, +} + +pub enum Verdict { Proved, Checked, Unverified, Unproved, Rejected, Error } + +pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result; +pub fn emit_path(path: &Path, out: &Path) -> Result; // 不判定 +pub fn audit_path(path: &Path) -> Result; // 不判定 +``` + +`main.rs` 只做参数搬运与退出码映射(与 `Commands::Verify` 同风格)。 + +### 8.3 缓存与证书 + +缓存键:`sha256(源码 ⊕ plan.json ⊕ schema ⊕ 库 sha256 ⊕ lean --version ⊕ marqdo 版本)`。证书: + +```jsonc +{ + "schema": 1, + "key": "…", + "status": "proved", + "tier": "lean", + "source": {"path": "skills/…", "sha256": "…", "artifact_id": "mq://…"}, + "lean": {"toolchain": "…", "library_sha256": "…", "module_sha256": "…", "axioms": []}, + "claims": [{"id": "…", "status": "proved", "decided_by": "omega"}], + "offline": {"claims": [{"id": "…", "status": "checked", "cases": 3}]}, + "obligations": [{"id": "effects_subset", "status": "passed"}], + "assumptions": ["银行.转账: 前置 金额 > 0;后置 返回.ok = True"], + "span_map": {"41": "21:1"}, + "created": "2026-11-13T09:00:00Z", + "marqdo": "2.8.0" +} +``` + +- 命中即跳过判定(报告标 `cache: hit`)。 +- 源文件、库、工具链任一变化即失效;暂不做部分重证。 +- 证书是**复核收据**,不是发布许可:推荐附在发布说明里,不强制。 +- `prove clean` 删 `.marqdo/prove`(`--emit` 目录不动)。 + +### 8.4 工具链与库发现 + +1. `--lean`/`--lake`;2. `MARQDO_PROOF_LEAN`/`MARQDO_PROOF_LAKE`;3. `PATH` 上的 `lake`,再 `lean`;4. 都没有 → 只跑离线,`lean: null`。 + +显式给出(flag 或环境变量)但路径不存在/不可执行 → `error[proof.lean_missing]`,**不**回退到离线:避免"我以为在跑 Lean,其实没有"。 + +库发现:`--library` → `MARQDO_PROOF_LIB` → 仓库内 `verification/skill-proof` → 安装根 `share/marqdo/proof/` → 相邻 `marqdo-proof/`。首次使用按 `LIBRARY-SHA256` 复制进 `.marqdo/prove/pkg` 并 `lake build` 一次(缓存);库哈希进证书。 + +### 8.5 环境变量 + +| 变量 | 作用 | +|---|---| +| `MARQDO_PROOF_LEAN` / `MARQDO_PROOF_LAKE` | 工具链路径 | +| `MARQDO_PROOF_LIB` | 语义库目录 | +| `MARQDO_PROOF_TIMEOUT` | 默认超时(秒) | +| `MARQDO_PROOF_CACHE` | 缓存根(默认 `.marqdo/prove`) | +| `MARQDO_PROOF_NO_CACHE` | 等价 `--no-cache` | +| `MARQDO_PROOF_REQUIRE_LEAN` | 等价 `--require-lean`(CI/测试用) | + +--- + +## 9. 测试与证据(摘要) + +完整矩阵见 [roadmap/prove.md](../roadmap/prove.md) §6。四类必须守住的证据: + +1. **单调性**(用户硬要求):语料库里每条离线 `checked` 的定理,Lean 都必须证出来;任何分歧 → `error[proof.divergence]`。 +2. **不执行**:带 `fs.write`/`exec` 的夹具在 `prove` 后不产生任何副作用。 +3. **确定性**:同输入两次运行,`module.lean` / `plan.json` / 证书键全等。 +4. **诚实性文案**:`checked` 与 `proved` 在文本、JSON、证书三处措辞一致,不允许出现"已验证"字样描述离线结果。 + +--- + +## 10. 已定事项 + +| # | 事项 | 结论 | 备注 | +|---|---|---|---| +| 1 | 命令名 | `marqdo prove` | 别名 `lean` | +| 2 | 是否强制 | **不强制**;规范与手册推荐 | 无 `--require-lean` 时缺工具链不失败 | +| 3 | 离线能否给结论 | 能,但只到 `checked` | 严格弱于 Lean(§5) | +| 4 | 定理写法 | 函数级 `定理` 表 | [ADR 0010](../adr/0010-skill-proof-boundary.md) | +| 5 | `check --proof` | 加,默认关 | | +| 6 | 首版 `foreach` | 不做,P3 再加 | 之前 `proof.foreach_pending` | +| 7 | 状态词 | `proved` / `checked` / `unverified` / `unproved` / `rejected` | 只有 `proved` 能说"已证明" | + +遗留(不阻塞开工,P2 前定):`假设` 表是否也认领 `前置/后置` 之外的列(如 `来源`);`--all` 的聚合粒度(按文件还是按函数);证书是否需要签名。 + +--- + +## 11. 文档与发布清单 + +- [ ] 本文件转 `Implemented`(分阶段勾) +- [ ] `doc/roadmap/prove.md`:里程碑、周计划、测试矩阵 +- [ ] `doc/adr/0010-skill-proof-boundary.md`:定理表角色 + 子集边界 + 顾问式定位 +- [ ] `doc/design/skill-proof-theory.md`:语义映射、定理形态、TCB 表 +- [ ] `verification/skill-proof/README.md`:构建、身份哈希、与 replay-policy 的关系 +- [ ] `README.md`:CLI 三行示例 + 状态表 + "推荐但不强制" +- [ ] `doc/tutorial/13-命令行工具.md`:先 `emit`,再 `prove` +- [ ] `skills/marqdo-dev/index.mq.md`:新增 `prove` 任务(推荐在发布前跑) +- [ ] `skills/marqdo/reference.md`:定理表语法速查 +- [ ] `CHANGELOG.md`:2.8.0;「核心表面 Δ:无(表格新增语义角色:定理)」 +- [ ] `.github/workflows/proof.yml`;`.gitignore` 已含 `.marqdo/` +- [ ] 发版手册:推荐附证书哈希,不设为硬门禁 + +--- + +## 12. 实现状态与偏差记录(P0/P1 落地时修订) + +| 状态 | 内容 | +|---|---| +| **P0 已落地** | `src/prove/`:`ir.rs`(Plan IR + 稳定 JSON)、`lower.rs`(子集验收/内联/不透明化/效应标签)、`types.rs`(字面量推断 + 分支合流 + `proof.type_mismatch`)、`emit.rs`(确定性 Lean 生成)、`mod.rs`(Report/Verdict/ProveOptions + `prove/emit/audit/clean`)。测试:`tests/prove.rs` 12 例 + 模块单元测试,全部不依赖 Lean。 | +| **P1(Rust 侧)已落地** | 定理表提取(`ast::Function.claims` + `contract::parse_claim_table`,首条可执行语句之前,提取后移出 body);`check --proof`(默认关):`proof.claim_malformed` / `claim_ambiguous` / `claim_misplaced` / `claim_duplicate` / `claim_unknown_symbol` / `claim_unsupported` / `name_shadow`;定理脚手架生成(受限文法 → Lean `theorem` 陈述 + §7.2 策略脚本)。Lean 判定(lake/driver/cache/CI)按 roadmap P1 第 2 周继续。 | + +### 与本文前面章节的偏差(以本表为准) + +1. **`result.ok/error/value_or`,不是 `result.success/failure`**:设计起草时假设的库名与 `lib/result.mq.md` 真实 API 不一致,实现以真实库为准(§4.5/§6.2 示例已同步修正)。Lean 侧库提供 `Result.success/failure` 作为映射目标。 +2. **P0/P1 的 `run` 返回 `Val × List Op`**:`result.ok(...)` 内联为 Val 字面映射构造(`mqResultOk`),而非单独的 `Result` 结构。P2 起按返回契约提升为类型化 `structure Params`/`Result`(§6.2 的形态),届时定理表可直接做字段级推理。 +3. **Op 构造器带元数**:`inductive Op` 的每个构造器按首现实参个数声明 `参数1..参数N : Val`(§6.2 示例省略了这一点)。 +4. **`--allow-opaque` 的效应标签恒为 `opaque`**:即便函数声明了契约效应也不沿用——行为完全未知时引用其声明只会误导 `audit` 读者(§2.2)。 diff --git a/doc/roadmap/prove.md b/doc/roadmap/prove.md new file mode 100644 index 0000000..ea2320f --- /dev/null +++ b/doc/roadmap/prove.md @@ -0,0 +1,409 @@ +# `marqdo prove` 实施路线(P0–P3) + +| | | +|---|---| +| 状态 | **计划(Proposed)· 未开工** | +| 日期 | 2026-11-13 | +| 设计 | [design/prove-cli.md](../design/prove-cli.md)(命令面、离线片段、定理表、语言习惯审查) | +| 决策 | [ADR 0010](../adr/0010-skill-proof-boundary.md)(定理表角色、子集边界、顾问式定位) | +| 目标版本 | CLI 2.8.0 | +| 总工期 | 6.5 人周(单人;P0+P1 共 3 周可演示) | + +--- + +## 0. 完成定义 + +| 阶段 | 完成定义(DoD) | +|---|---| +| P0 | `prove emit` / `prove audit` 可跑;确定性生成;12 个夹具的降级结论稳定;`cargo test --test prove` 在**没有 Lean** 的机器上全绿 | +| P1 | 定理表落地;有 Lean 时 `proved`,无 Lean 时至少 `unverified`;证书与源码映射可用;CI 跑通「假定理必须红」 | +| P2 | 离线判定 `checked` 可用;语料库强制 `offline_checked ⊆ lean_proved`;反例可读;`--require-lean` 严格模式 | +| P3 | 跨函数组合、`--all`、差分一致性;文档/教程/技能手册齐;2.8.0 发布 | + +关键指标(P3 收口时复核): + +- 语料 **≥ 40** 个夹具,覆盖 8 类(§6)。 +- 控制平面类定理的**离线覆盖率 ≥ 60%**(其余 `unverified`,不算失败)。 +- 冷启动(50 函数文件)**< 30s**;证书命中 **< 50ms**。 +- **单调性分歧 0 例**(语料 + CI 每次运行)。 + +--- + +## 1. 为什么先 Lean、后离线 + +离线判定器需要一把"标尺":没有 Lean 作为判据,无法知道它会不会"过度自信"。所以顺序是: + +1. P0 先把降级与生成做确定(无判定,不会撒谎); +2. P1 接上 Lean,得到**权威判据**与失败证据格式; +3. P2 才写离线判定,并用 P1 的 Lean 结果做语料护栏(`offline ⊆ lean`)。 + +如果反过来,P2 的判定器会在没有标尺的情况下生长,最后很难证明它保守。 + +--- + +## 2. P0 · 骨架与确定性生成(1 周) + +### 任务 + +| 天 | 任务 | 产物 | +|---|---|---| +| D1 | `Commands::Prove` + `ProveAction::{Emit,Audit,Clean}`;`--json` 外壳;`src/prove/mod.rs` 状态机骨架 | `marqdo prove --help` 正确;未知参数报 clap 错误 | +| D2 | `ir.rs` + `lower.rs`:参数、赋值、返回、调用→`Op`、`if/else`;`while`/递归/动态调用的拒绝码 | 12 个夹具降级到 IR,`plan.json` 可读 | +| D3 | `types.rs`:从契约表起步的推断与合一;`proof.type_mismatch` 等错误码 | 类型错误夹具给出两处行号 | +| D4 | `emit.rs`:确定性 Lean 生成(稳定排序、无时间戳、相对路径)、中文名、`-- mq:` 注释 | 两次运行字节一致 | +| D5 | `report.rs` + `audit`:内联/不透明/跳过三类清单;快照测试;`tests/prove.rs` | `cargo test --test prove` 无 Lean 全绿 | + +### 验收 + +```bash +marqdo prove emit tests/prove/fixtures/approval.mq.md -o /tmp/lean +marqdo prove audit tests/prove/fixtures/approval.mq.md --json | jq '.functions[0].ops, .functions[0].rejected' +# 两次 emit 的 sha256 相同 +``` + +### 明确不做 + +判定、证书、Lean 调用、定理表。P0 的 `prove` 只有 `emit`/`audit` 两个子命令可用,默认命令直接转发到 `emit` 并提示"判定将在 P1 提供"。 + +--- + +## 3. P1 · 定理表 + Lean 判定(2 周) + +### 第 1 周:语言面与工具链 + +| 任务 | 产物 | +|---|---| +| ADR 0010 落定;`Function.claims`;定理表提取(首条可执行语句前,提取后移出 body) | 解析后 `claims` 非空,body 里没有该表 | +| `check --proof`(默认关):表形、名字、片段、遮蔽 | `check` 报 `proof.claim_malformed` / `proof.name_shadow` | +| `verification/skill-proof/`:`lean-toolchain`、`lakefile`、`Basic/Result/Tactic`、`LIBRARY-SHA256` 脚本 | `lake build` 通过 | +| `driver.rs`:工具链探测、Lake 包、`lake env lean`、超时、stderr 解析 | 手工跑通 approval 样例 | +| `cache.rs`:证书、`index.json`、失效 | 二次运行毫秒返回 | + +### 第 2 周:定理语义与失败证据 + +| 任务 | 产物 | +|---|---| +| 结论/前提求值:参数、`结果`、`轨迹`、三个谓词 | 定理编译通过 | +| 脚本生成:`intro` → `unfold run` → `split_ifs <;> simp_all <;> omega` | 正例 `proved` | +| 失败解析:`unsolved goals` → 目标 + 上下文 → 映射回 `.mq.md` 行 | 假定理给出源码行与残余目标 | +| `.github/workflows/proof.yml`:elan 钉版、`lake build`、跑 Lean 用例 | CI 绿;假定理用例必须红 | +| 文本/JSON/退出码对齐设计文档 | 状态表逐项手测 | + +### 验收 + +```bash +marqdo prove tests/prove/fixtures/approval.mq.md --json | jq .status # "proved" +marqdo prove tests/prove/fixtures/false-claim.mq.md; echo $? # 1 +PATH=/usr/bin:/bin target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq .status +# P1 阶段没有离线判定,因此是 "unverified";P2 起升级为 "checked" +``` + +--- + +## 4. P2 · 离线判定与单调性(2 周) + +### 第 1 周:符号执行与 F1–F4 + +- `offline.rs`:符号状态(`Const/Param/OpResult/Unknown`)、路径条件、轨迹。 +- 分支分叉与返回路径收集;`if` 条件求值到符号原子。 +- F2 轨迹求值(`包含/长度/下标`)、F3 字面结果、F4 命题组合。 +- 结论:`checked` / `unverified` 两态;证书写入情形列表。 + +### 第 2 周:F5 区间、反例、护栏 + +- F5:单变量 `x ⋈ c` 的区间传播与蕴含判定(保守;不可判定即 `unverified`)。 +- 反例:路径可满足 + 结论字面假 → 端点见证值。 +- 分歧护栏:`checked` 但 Lean 未关闭 → `error[proof.divergence]`(含测试专用注入开关,见 §6 A3)。 +- 假设表(T3):前置/后置 → 定理前提;`proof.assumption_untyped`。 +- 单调性脚本:对语料逐条比对离线与 Lean 的定理状态。 + +### 验收 + +```bash +# 无 Lean 也能给出离线结论 +PATH=/usr/bin:/bin target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq .status # "checked" +# 单调性:语料中不存在 checked 而 Lean unproved 的定理 +cargo test --test prove_lean # 需工具链 +``` + +--- + +## 5. P3 · 组合与产品化(1.5 周) + +| 任务 | 产物 | +|---|---| +| 跨函数内联 + assume-guarantee(调用者用被调者证书里的后置条件) | 多函数编排证明 | +| `foreach`(有限列表,fold 编码) | Q1 夹具 | +| `--all` 目录模式、聚合报告、`--max-files` | 仓库级报告 | +| 差分一致性(T4):`Conformance.lean` + 解释器期望值 | CI 比对 | +| `view` 徽标、`catalog` `proof:` 字段、MLSP `proof` 方法(可选) | 读侧可见 | +| 文档:README、教程、两个 skill 手册、CHANGELOG、2.8.0 | 发布 | +| 发版手册:推荐附证书(不强制) | 流程更新 | + +### 验收 + +```bash +marqdo prove --all skills/ --json | jq '.status, (.files|length)' +lake build # verification/skill-proof/examples 全部通过 +``` + +--- + +## 6. 测试矩阵(针对性) + +夹具目录 `tests/prove/fixtures/`,集成测试 `tests/prove.rs`;Lean 相关用 `tests/prove_lean.rs`(独立测试目标,不进默认 `cargo test`)。 + +### A · 单调性与诚实性(最高优先级) + +| ID | 夹具 / 操作 | 期望 | 守住什么 | +|---|---|---|---| +| A1 | `approval.mq.md`:`包含(轨迹,"人工审核")` | 离线 `checked`;Lean `proved` | 离线结论被 Lean 确认 | +| A2 | `false-claim.mq.md`:大额时断言 `结果.ok = False` | `unproved`,退出 1;P2 起附反例 `金额=10001` | 假定理不被放绿 | +| A3 | 同一夹具 + 测试注入 `--fault-inject offline-claim`(仅 debug 构建存在) | `error[proof.divergence]`,退出 1,JSON `status=="error"` | 分歧必须显式失败,不许静默以离线为准 | +| A4 | 多变量线性命题(`金额 + 手续费 > 10000`) | 离线 `unverified`;跑 Lean 后 `proved` 或 `unproved` | 片段保守,不越界断言 | +| A5 | 语料全量:`checked` 集合 ⊆ Lean `proved` 集合 | 集合包含成立,0 反例 | 长期单调性回归 | + +### B · 语义一致性(T4) + +| ID | 内容 | 期望 | +|---|---|---| +| B1 | 纯函数语料(算术、比较、布尔、字符串拼接、`access`、`len`) | 解释器输出 == Lean `example : f args = expected := by decide` | +| B2 | 除零、取模零 | 与运行时错误语义一致(生成 `mq_div`/`mq_mod` 返回 Result.failure) | +| B3 | 中文标识符 `计算器.加法`、含空格名 `多 步` | 生成 `«…»`,Lean 接受 | +| B4 | 映射/表字面量:字段顺序、`ok` 字段读取 | Lean 结构与 Marqdo 取值一致 | +| B5 | 负数、大整数(`i64` 边界) | 无溢出漂移;超界按契约拒绝 | + +### C · 不执行(安全) + +| ID | 夹具 | 期望 | +|---|---|---| +| C1 | 函数里调 `fs.write`、`fs.make_dirs` | `prove` 后目标路径不存在 | +| C2 | 函数里调 `print` | stdout **只有** `prove` 的报告;没有程序输出 | +| C3 | `--emit` 到只读目录 | 清晰 IO 错误,退出 1,不 panic | + +### D · 子集与拒绝 + +| ID | 夹具 | 期望 | +|---|---|---| +| D1 | `while` 循环 | `proof.while`,行号准确;整体 `rejected`,退出 0 | +| D2 | 自递归 + 互递归 | `proof.recursion`,列出环上函数名 | +| D3 | 插件/动态调用 | `proof.dynamic_call` | +| D4 | 未定型变量(strict) | `proof.type_mismatch`,两处行号 | +| D5 | 同上 + `--no-strict-types` | 落 `Val`,报告标"弱类型",不报错 | +| D6 | `--allow-opaque 预检` | 该函数列为不透明操作,调用者仍可证 | + +### E · 定理表 + +| ID | 夹具 | 期望 | +|---|---|---| +| E1 | 未知名字 `审批人.ok` | `proof.claim_unknown_symbol` + 最近建议 | +| E2 | 重复 id | `proof.claim_duplicate` | +| E3 | 参数名 `结果` 遮蔽保留名 | `proof.name_shadow` | +| E4 | `策略 none` | 定理生成、不证;状态 `unverified`,不是失败 | +| E5 | 非法策略片段 `策略 nonsense` | `proof.claim_failed` 带 Lean 原始错误,不 panic | +| E6 | 缺 `结论` 列 / 表在语句之后 | `proof.claim_malformed` / `proof.claim_misplaced`(`check --proof`) | +| E7 | 两列「定理 / 说明」普通表 | 不认领,`check --proof` 不报 | +| E8 | `假设` 表:`返回.ok = True` 用于分支判断 | Lean `proved`;证书 `assumptions` 有该条 | + +### F · CLI / JSON / 退出码 + +| ID | 操作 | 期望 | +|---|---|---| +| F1 | 各状态夹具 | 退出码 == 设计表(0/0/0/0/1/1) | +| F2 | `--report-only` on A2 | 退出 0,状态仍 `unproved` | +| F3 | `--require-lean` 且 `PATH` 无 lean | 退出 2,`status=="unverified"` | +| F4 | `--json` | 键集合与类型快照;`schema==1`;无绝对路径 | +| F5 | 目录不带 `--all` | `proof.need_all`,退出 1 | +| F6 | `prove clean` | `.marqdo/prove` 消失;`--emit` 目录保留 | + +### G · 缓存与确定性 + +| ID | 操作 | 期望 | +|---|---|---| +| G1 | 连续两次 `prove emit` | `module.lean`、`plan.json` 字节相同 | +| G2 | 假 `lean` 脚本写日志;连续两次 `prove` | 日志只有 1 行(第二次命中缓存) | +| G3 | 改源码一个字符 | 证书键变化,重新判定 | +| G4 | 改库文件(模拟 `LIBRARY-SHA256` 变化) | 缓存失效 | +| G5 | 手工损坏 `certificate.json` | `proof.cache_corrupt`;重算或退出 1,不读坏证书 | + +### H · 编码边角 + +| ID | 内容 | 期望 | +|---|---|---| +| H1 | 空 else、两臂都早返回 | 生成退化正确,Lean 通过 | +| H2 | 不可达分支(`1. False`) | `audit` 标 warning;不阻塞 | +| H3 | 字符串含引号/换行/中文 | 转义正确,Lean 字面量等值 | +| H4 | 0 参数、0 语句函数 | 生成 `def run := ...` 合法 | +| H5 | 参数默认值 | 与契约默认一致;Lean 用显式值代入 | + +--- + +### 关键夹具草稿(P0 落盘到 `tests/prove/fixtures/`) + +正例(轨迹命题,A1): + +```markdown +## 审批 ++ `金额` + +| 参数 | 类型 | 说明 | +|---|---|---| +| 金额 | int | 申请金额(元) | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result | + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | + +1. `金额` > 10000 + **审核 = [提交人工审核](人工审核(金额=`金额`))** + **结果 = [保留人工审核结论](result.ok(value=`审核`))** +2. * + **结果 = [自动通过](result.ok(value="auto"))** + +**结果** +``` + +反例(A2):同构文件,只把定理换成 + +```markdown +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 不该自动放行 | 结果.ok = False | 金额 > 10000 | auto | +``` + +期望 `unproved`、退出 1;P2 起附反例 `金额 = 10001`。 + +不执行(C1): + +```markdown +## 落盘 ++ `path` + +**written = [真的写一个文件](fs.write_text(path=`path`, text="证明工具不该执行我"))** + +**written** +``` + +跑 `prove` 后指定路径必须不存在;`prove` 只做降级与生成。 + +拒绝(D1): + +```markdown +## 倒计时 ++ `n` + +- `n` > 0 + **n = n - 1** + +**n** +``` + +期望 `proof.while`,整体 `rejected`、退出 0(若没有别的未关闭定理)。 + +遮蔽(E3): + +```markdown +## 遮蔽 ++ `结果` + +| 定理 | 结论 | +|---|---| +| 读结果 | 结果.ok = True | +``` + +参数名与保留名冲突 → `proof.name_shadow`,要求改名,不做隐式优先。 + +--- + +## 7. 验收证据(可直接粘进 PR) + +```bash +# 1) 离线可用(把 PATH 收窄到没有 lean) +PATH=/usr/bin:/bin target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq -r .status +# checked + +# 2) 有 Lean 时升级为证明 +target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq -r .status +# proved + +# 3) 假定理必须红,且给出行号 +target/debug/marqdo prove tests/prove/fixtures/false-claim.mq.md; echo "exit=$?" +# error[proof.claim_failed] … --> false-claim.mq.md:31:3 +# exit=1 + +# 4) 单调性(语料) +cargo test --test prove_lean -- --nocapture +# offline_checked=37 lean_proved=37 divergences=0 + +# 5) 不执行 +rm -f /tmp/mq-prove-should-not-exist +target/debug/marqdo prove tests/prove/fixtures/side-effect.mq.md +test ! -e /tmp/mq-prove-should-not-exist && echo "no side effect" + +# 6) 确定性 +a=$(target/debug/marqdo prove emit tests/prove/fixtures/approval.mq.md -o /tmp/a && sha256sum /tmp/a/Generated/Approval.lean) +b=$(target/debug/marqdo prove emit tests/prove/fixtures/approval.mq.md -o /tmp/b && sha256sum /tmp/b/Generated/Approval.lean) +[ "${a%% *}" = "${b%% *}" ] && echo deterministic +``` + +--- + +## 8. CI 设计 + +```yaml +# .github/workflows/proof.yml(示意;action 版本以仓库既有 workflow 为准) +jobs: + corpus: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - name: Install elan (toolchain pinned by verification/skill-proof/lean-toolchain) + run: | + curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain none + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + - name: Build proof library (cache .lake) + working-directory: verification/skill-proof + run: lake build + - run: cargo build --locked + - run: cargo test --test prove --locked # 不需要 Lean 的部分 + - run: cargo test --test prove_lean --locked + env: { MARQDO_PROOF_REQUIRE_LEAN: "1" } + - run: bash scripts/check-proof-library.sh # LIBRARY-SHA256 与 BUILD-IDENTITY +``` + +原则: + +- `cargo test` **不依赖** Lean;Lean 用例在独立目标里,缺失工具链时打印 `SKIP: lean toolchain not found` 并在 `MARQDO_PROOF_REQUIRE_LEAN=1` 下转为失败。 +- 不使用 `#[ignore]` 作为成功证据(沿用 `executable-knowledge.yml` 的纪律)。 +- Lean 构建缓存 `.lake`,避免每次拉依赖。 + +--- + +## 9. 风险与回滚 + +| 风险 | 触发 | 应对 | +|---|---|---| +| Lean 工具链在 CI 不可用 | action 变更/网络 | 钉版本 + 缓存;`proof.yml` 失败只红该 job,不阻塞其它 | +| 离线判定"过度自信" | 片段实现 bug | 语料 A5 强制包含关系;运行期 A3 分歧即 error | +| 生成不确定 | HashMap 遍历顺序 | 全量 `BTreeMap`;两次 emit 字节比对进 CI | +| 定理表被误用成数据表 | 表头重名 | 只有表头+列形同时命中才认领;`check --proof` 可关 | +| 破坏既有 `check` 性能 | 提取逻辑 | `--proof` 默认关;提取只做一次线性扫描 | +| 范围蔓延(想把整个语言编译过去) | 需求诱惑 | ADR 0010 写死子集;新增构造需重新评审 | + +回滚:`prove` 是**纯增量**(新命令 + 新可选表角色);删除命令与 `Function.claims` 字段即可回到现状,已有 `.mq.md` 不受影响(定理表在无 `prove` 的旧版本里只是普通表格)。 + +--- + +## 10. 不做清单(本版本) + +- `while`、递归、动态派发的形式化(拒绝而非近似)。 +- 字符串/JSON/浮点/公式库的语义建模。 +- 自动修复不成立的定理。 +- 证明缓存的服务端共享。 +- IDE 内联证明状态(先走 `view` 徽标)。 +- 强制门禁:任何"必须 proved 才能发布"的默认行为。 diff --git a/src/ast.rs b/src/ast.rs index 2e1c4e5..364e7ea 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -95,6 +95,22 @@ pub struct Function { pub contract: Option, /// 集合契约(T2.1):变量名 → 字段契约(紧邻 `` `名` = `` 绑定之前的文档表)。 pub var_contracts: HashMap, + /// 定理表(ADR 0010):函数级命题声明;首条可执行语句之前提取,不参与运行。 + pub claims: Vec, +} + +/// 一条定理声明(设计 §7.1):`| 定理 | 结论 | 前提 | 策略 |` 的一行。 +#[derive(Debug, Clone)] +pub struct Claim { + /// 定理 id(函数内唯一;重复由 `check --proof` 报 `proof.claim_duplicate`)。 + pub id: String, + /// 受限表达式文本(参数、`结果`、`轨迹`、三个谓词、算术/比较/布尔)。 + pub conclusion: String, + pub premise: Option, + /// `auto`(默认)或 `none`;其他值由 `check --proof` 报 unsupported。 + pub tactic: Option, + /// 表行所在行号(锚定漂移检测)。 + pub line: u32, } impl Function { diff --git a/src/check.rs b/src/check.rs index 394acc7..f36aa8b 100644 --- a/src/check.rs +++ b/src/check.rs @@ -23,14 +23,17 @@ use crate::load; /// 读取文件 + 装载(含 import)后做全量契约互查。 pub fn check_path(path: &Path) -> Result> { - check_path_opts(path, false) + check_path_opts(path, false, false) } /// `implicit_labels` enables the fuzzy M5 check (prose above `>` calls). /// /// It is **off by default**: describing a call in prose is freeform, so the /// check is inherently ambiguous and would be noisy — opt in when you want it. -pub fn check_path_opts(path: &Path, implicit_labels: bool) -> Result> { +/// +/// `proof` enables the theorem-table check (`check --proof`, ADR 0010, +/// 默认关):表形、名字、片段、遮蔽。 +pub fn check_path_opts(path: &Path, implicit_labels: bool, proof: bool) -> Result> { let module = load::load_module(path)?; let mut out = check_module(&module, Some(path)); if implicit_labels { @@ -38,6 +41,9 @@ pub fn check_path_opts(path: &Path, implicit_labels: bool) -> Result usize { prev[b.len()] } +/// 供 `prove::proof_check` 复用的最近名建议(编辑距离 ≤ 2)。 +pub fn suggest_closest(name: &str, known: &[String]) -> Option { + suggest(name, known) +} + fn suggest(name: &str, known: &[String]) -> Option { let lower = name.to_ascii_lowercase(); let mut best: Option<(usize, String)> = None; diff --git a/src/contract.rs b/src/contract.rs index 83a3fca..cb958b3 100644 --- a/src/contract.rs +++ b/src/contract.rs @@ -265,6 +265,117 @@ const TYPE_HEADERS: &[&str] = &["类型", "type"]; const DESC_HEADERS: &[&str] = &["说明", "描述", "备注", "注释", "desc", "description"]; const NULLABLE_HEADERS: &[&str] = &["可空", "nullable", "optional"]; +// ---------- 定理表识别(ADR 0010 / 设计 §7.1) ---------- + +/// 定理表头(第一列)词表:`定理/证明/claim/theorem`。 +pub const CLAIM_NAME_HEADERS: &[&str] = &["定理", "证明", "claim", "theorem"]; +/// 结论列词表(必填列)。 +pub const CLAIM_CONCLUSION_HEADERS: &[&str] = &["结论", "conclusion"]; +/// 前提列词表(可缺省)。 +pub const CLAIM_PREMISE_HEADERS: &[&str] = &["前提", "premise", "assumes"]; +/// 策略列词表(可缺省)。 +pub const CLAIM_TACTIC_HEADERS: &[&str] = &["策略", "tactic"]; + +/// 表头是否命中定理表第一列(只看词,不看列形)。 +pub fn header_hits_claim(headers: &[String]) -> bool { + find_col(headers, CLAIM_NAME_HEADERS).is_some() +} + +/// 定理表认领判定(设计 §7.1 规则 1/5): +/// - `None`:表头不命中定理词表 → 普通表; +/// - `Some(Ok(rows))`:命中且列形正确(有结论列,无 `类型` 列)→ 定理表; +/// - `Some(Err(e))`:命中但有形状问题(歧义/行数不齐/缺名)→ `check --proof` 报。 +pub fn parse_claim_table( + pairs: &[(String, Expr)], + start_line: u32, +) -> Option, ClaimTableError>> { + let headers: Vec = pairs.iter().map(|(k, _)| k.clone()).collect(); + if !header_hits_claim(&headers) { + return None; + } + // 同时有 `类型` 列与 `结论` 列 → 歧义,不猜(§7.1 规则 5)。 + if find_col(&headers, TYPE_HEADERS).is_some() + && find_col(&headers, CLAIM_CONCLUSION_HEADERS).is_some() + { + return Some(Err(ClaimTableError { + code: "proof.claim_ambiguous", + message: "表同时含 `类型` 与 `结论` 列——契约表与定理表不猜,请拆开或改名".into(), + })); + } + // 无结论列 → 不是定理表(两列的 `定理/说明` 是普通说明表,§7.3.5)。 + let Some(conclusion_col) = find_col(&headers, CLAIM_CONCLUSION_HEADERS) else { + return None; + }; + let premise_col = find_col(&headers, CLAIM_PREMISE_HEADERS); + let tactic_col = find_col(&headers, CLAIM_TACTIC_HEADERS); + // 第一列=定理名;若第一列不是命中列,命中列才是名字列。 + let name_col = find_col(&headers, CLAIM_NAME_HEADERS).unwrap_or(0); + + let names = col_rows(&pairs[name_col].1).unwrap_or_default(); + let conclusions = claim_col_rows(&pairs[conclusion_col].1); + if names.len() != conclusions.len() { + return Some(Err(ClaimTableError { + code: "proof.claim_malformed", + message: format!( + "定理/结论 列行数不一致({} vs {})", + names.len(), + conclusions.len() + ), + })); + } + let premises = premise_col + .map(|c| claim_col_rows(&pairs[c].1)) + .unwrap_or_default(); + let tactics = tactic_col + .map(|c| col_rows(&pairs[c].1).unwrap_or_default()) + .unwrap_or_default(); + if !premises.is_empty() && premises.len() != names.len() { + return Some(Err(ClaimTableError { + code: "proof.claim_malformed", + message: "前提 列行数与 定理 列不一致".into(), + })); + } + if !tactics.is_empty() && tactics.len() != names.len() { + return Some(Err(ClaimTableError { + code: "proof.claim_malformed", + message: "策略 列行数与 定理 列不一致".into(), + })); + } + + let mut rows = Vec::new(); + for (i, name) in names.iter().enumerate() { + let name = name.trim(); + if name.is_empty() { + return Some(Err(ClaimTableError { + code: "proof.claim_malformed", + message: format!("定理表第 {} 行缺定理名", i + 1), + })); + } + rows.push(crate::ast::Claim { + id: name.to_string(), + conclusion: conclusions[i].trim().to_string(), + // 空前提单元格 = 无前提(全称命题)。 + premise: premises + .get(i) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()), + tactic: tactics + .get(i) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()), + line: start_line, + }); + } + Some(Ok(rows)) +} + +/// 定理表形状错误(`check --proof` 才报;默认关)。 +#[derive(Debug, Clone)] +pub struct ClaimTableError { + pub code: &'static str, + pub message: String, +} + fn norm_header(h: &str) -> String { h.trim().trim_matches('`').to_ascii_lowercase() } @@ -298,6 +409,57 @@ fn col_rows(e: &Expr) -> Option> { } } +/// 定理表单元格取文本:标量直取;比较/算术/布尔表达式按 `a op b` 还原 +/// (`金额 > 10000` 这类单元格会解析成 Binary,不能因为不是标量就丢行)。 +/// 不认识的形状 → None(该行按缺失处理,`check --proof` 会报 unknown_symbol)。 +fn claim_cell_text(e: &Expr) -> Option { + if let Some(text) = cell_to_text(e) { + return Some(text); + } + match e { + Expr::Binary { op, left, right } => Some(format!( + "{} {} {}", + claim_cell_text(left)?, + op_token(*op), + claim_cell_text(right)? + )), + Expr::Unary { op, expr } => match op { + crate::ast::UnaryOp::Not => Some(format!("非 ({})", claim_cell_text(expr)?)), + crate::ast::UnaryOp::Neg => Some(format!("-({})", claim_cell_text(expr)?)), + }, + _ => None, + } +} + +fn op_token(op: crate::ast::BinaryOp) -> &'static str { + use crate::ast::BinaryOp as B; + match op { + B::Add => "+", + B::Sub => "-", + B::Mul => "*", + B::Div => "/", + B::Eq => "=", + B::Ne => "≠", + B::Lt => "<", + B::Le => "≤", + B::Gt => ">", + B::Ge => "≥", + B::And => "且", + B::Or => "或", + } +} + +/// 定理表列取文本(行级 None 不整列丢弃——只丢该行该列)。 +fn claim_col_rows(e: &Expr) -> Vec { + match e { + Expr::List(items) => items + .iter() + .map(|item| claim_cell_text(item).unwrap_or_default()) + .collect(), + scalar => vec![claim_cell_text(scalar).unwrap_or_default()], + } +} + fn is_nullable(raw: &str) -> bool { matches!( norm_header(raw).as_str(), diff --git a/src/frontend_elaboration_tests.rs b/src/frontend_elaboration_tests.rs index b6a2330..c6257e5 100644 --- a/src/frontend_elaboration_tests.rs +++ b/src/frontend_elaboration_tests.rs @@ -16,8 +16,12 @@ fn local_json(value: &Value) -> serde_json::Value { } fn document(id: &str, source: &str) -> (PathBuf, crate::ast::Module) { - let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("target/frontend-elaboration") + // Scratch belongs to the build target dir; honor CARGO_TARGET_DIR when set. + let base = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); + let dir = base + .join("frontend-elaboration") .join(format!("{id}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("main.mq.md"); diff --git a/src/lib.rs b/src/lib.rs index a90972d..7a61214 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -45,6 +45,7 @@ pub mod runtime; pub mod workbench; pub mod parse; pub mod project; +pub mod prove; pub mod repair; pub mod sema; pub mod value; diff --git a/src/main.rs b/src/main.rs index 069e651..111b5d5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -218,6 +218,10 @@ enum Commands { /// Parse an unmarked file with the legacy grammar for migration review. #[arg(long)] legacy_markup: bool, + + /// Validate theorem tables (ADR 0010; 默认关): shape, symbols, shadowing + #[arg(long)] + proof: bool, }, /// Occlusion label queries: pending stubs (built-in words) or keyword search Labels { @@ -495,6 +499,81 @@ enum Commands { #[command(subcommand)] action: WasmAction, }, + /// Compile SKILL orchestration to Lean 4 and (P1+) prove theorems (推荐但不强制) + Prove { + /// Action (default: emit + report) + #[command(subcommand)] + action: Option, + + /// Program path (.mq.md; default ./index.mq.md) + #[arg(value_name = "FILE")] + file: Option, + + /// One JSON object on stdout (agent-facing stable contract) + #[arg(long)] + json: bool, + + /// Only lower/emit these functions (display path, repeatable) + #[arg(long = "only", value_name = "FN")] + only: Vec, + + /// Output dir for emit (default .marqdo/prove//) + #[arg(long = "emit", short = 'o', value_name = "DIR")] + emit_dir: Option, + + /// Don't write artifacts; report only + #[arg(long)] + report_only: bool, + + /// Downgrade this function wholesale to one opaque op (repeatable) + #[arg(long = "allow-opaque", value_name = "FN")] + allow_opaque: Vec, + + /// Type inference is strict by default; this relaxes to Val (weaker proofs) + #[arg(long = "no-strict-types")] + no_strict_types: bool, + + /// CI strict mode: unjudged statuses exit 2 (P1+) + #[arg(long)] + require_lean: bool, + }, +} + +#[derive(Subcommand, Debug)] +enum ProveAction { + /// Generate deterministic Lean module + plan.json (no judging) + Emit { + #[arg(value_name = "FILE")] + file: Option, + #[arg(long = "emit", short = 'o', value_name = "DIR")] + emit_dir: Option, + #[arg(long)] + json: bool, + #[arg(long = "only", value_name = "FN")] + only: Vec, + #[arg(long = "allow-opaque", value_name = "FN")] + allow_opaque: Vec, + #[arg(long = "no-strict-types")] + no_strict_types: bool, + }, + /// Report inline/opaque/rejected classification (no judging) + Audit { + #[arg(value_name = "FILE")] + file: Option, + #[arg(long)] + json: bool, + #[arg(long = "only", value_name = "FN")] + only: Vec, + #[arg(long = "allow-opaque", value_name = "FN")] + allow_opaque: Vec, + #[arg(long = "no-strict-types")] + no_strict_types: bool, + }, + /// Delete .marqdo/prove caches and certificates + Clean { + #[arg(long)] + json: bool, + }, } #[derive(Subcommand, Debug)] @@ -656,7 +735,9 @@ fn main() -> ExitCode { let cli = Cli::parse(); let json_errors = matches!( &cli.command, - Commands::Run { json: true, .. } | Commands::Check { json: true, .. } + Commands::Run { json: true, .. } + | Commands::Check { json: true, .. } + | Commands::Prove { json: true, .. } ); match try_main(cli) { Ok(code) => ExitCode::from(code as u8), @@ -958,13 +1039,14 @@ fn try_main(cli: Cli) -> Result { implicit_labels, narrative_ratio, legacy_markup, + proof, } => { let mut diags = if legacy_markup { marqdo::parse::expr::with_markup(marqdo::parse::expr::Markup::Classic, || { - marqdo::check::check_path_opts(&file, implicit_labels) + marqdo::check::check_path_opts(&file, implicit_labels, proof) })? } else { - marqdo::check::check_path_opts(&file, implicit_labels)? + marqdo::check::check_path_opts(&file, implicit_labels, proof)? }; if narrative_ratio { diags.extend(marqdo::narrative_ratio::check_file(&file)?); @@ -989,6 +1071,87 @@ fn try_main(cli: Cli) -> Result { } Ok(errors.min(1)) } + Commands::Prove { + action, + file, + json, + only, + emit_dir, + report_only, + allow_opaque, + no_strict_types, + require_lean, + } => { + // 子命令参数覆盖顶层默认;默认动作 = emit + 报告。 + let (file, action_json, action_emit, action_only, action_opaque, action_relax) = + match &action { + Some(ProveAction::Emit { + file, + emit_dir, + json, + only, + allow_opaque, + no_strict_types, + }) => ( + file.clone(), + *json, + Some(emit_dir.clone()), + only.clone(), + allow_opaque.clone(), + *no_strict_types, + ), + Some(ProveAction::Audit { + file, + json, + only, + allow_opaque, + no_strict_types, + }) => ( + file.clone(), + *json, + None, + only.clone(), + allow_opaque.clone(), + *no_strict_types, + ), + Some(ProveAction::Clean { json }) => { + let removed = marqdo::prove::clean()?; + if *json { + println!("{{\"ok\":true,\"removed\":{removed}}}"); + } else { + println!("prove clean: 已删除 {removed} 项(.marqdo/prove)"); + } + return Ok(0); + } + None => (file.clone(), false, Some(emit_dir.clone()), only.clone(), allow_opaque.clone(), no_strict_types), + }; + let file = file.unwrap_or_else(|| PathBuf::from("index.mq.md")); + // emit 目标:显式 --emit 优先;None → mod.rs 用默认 `.marqdo/prove/`。 + // audit 永不写盘;默认动作受 --report-only 控制;emit 子命令总是写盘。 + let emit_target = action_emit.flatten(); + let report_only = matches!(action, Some(ProveAction::Audit { .. })) + || (action.is_none() && report_only); + let opts = marqdo::prove::ProveOptions { + entry: None, + only: action_only, + allow_opaque: action_opaque, + emit_dir: emit_target, + strict_types: !action_relax, + require_lean, + report_only, + }; + let report = marqdo::prove::prove_path(&file, &opts)?; + for d in &report.diagnostics { + // 诊断走 stderr(stdout 只放结果/报告)。 + eprintln!("{}", d.format_message()); + } + if json || action_json { + println!("{}", report.to_json()); + } else { + print!("{}", report.to_text()); + } + Ok(report.status.exit_code(require_lean)) + } Commands::Labels { paths, grep, diff --git a/src/parse/mod.rs b/src/parse/mod.rs index a67398f..76dc280 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -319,6 +319,7 @@ impl<'a> Cursor<'a> { dead_binds: Vec::new(), contract: None, var_contracts: std::collections::HashMap::new(), + claims: Vec::new(), }; // Prose decls pending promotion (name → optional default text). let mut prose_decls: Vec<(String, Option, u32)> = Vec::new(); @@ -2078,10 +2079,23 @@ fn extract_function_contract(fun: &mut Function, lines: &[ClassifiedLine]) -> Re let (end_line, quote) = table_quote(lines, span.line); let Some(parsed) = crate::contract::parse_contract_table(pairs, span.line, end_line, quote) else { - // 非契约形状:普通文档/数据表 → 原样保留(P1 零回归的关键)。 - keep.push(stmt.clone()); - i += 1; - continue; + // 非契约形状:先试定理表(ADR 0010),再按普通表保留。 + match crate::contract::parse_claim_table(pairs, span.line) { + // 合法定理表:只在「首个可执行行之前」生效;提取后从 body 移除。 + // 其余位置仍是普通表,由 `check --proof` 报 proof.claim_misplaced。 + Some(Ok(rows)) if prefix_zone => { + fun.claims.extend(rows); + i += 1; + continue; + } + // 畸形/歧义/错位的定理形表:保持普通表(默认关), + // `check --proof` 重扫 body 时报 malformed/ambiguous/misplaced。 + _ => { + keep.push(stmt.clone()); + i += 1; + continue; + } + } }; let piece = parsed?; // 契约形状但畸形 → 必产诊断(contract.malformed) let is_fn_contract = !piece.params.is_empty() || piece.returns.is_some(); diff --git a/src/prove/emit.rs b/src/prove/emit.rs new file mode 100644 index 0000000..5802d89 --- /dev/null +++ b/src/prove/emit.rs @@ -0,0 +1,684 @@ +//! Lean 生成(`doc/design/prove-cli.md` §4.1 ④ / §6)。 +//! +//! 确定性硬要求:同输入两次运行字节一致。做法:无时间戳、无绝对路径、 +//! 集合按首次出现顺序(降级本身确定)、映射键排序、浮点定长。 +//! +//! P0 形态:参数统一 `Val`(P1 起按契约提升为 `Int`/`String` 等以配合 +//! `structure Params` 与定理表);`result.ok/error` 内联为库构造器。 + +use std::fmt::Write as _; + +use crate::prove::ir::{ + BinOp, Expr as IrExpr, FnPlan, InterpPart, Plan, PlanTy, PureExpr, Step, UnOp, +}; + +/// 库名(verification/skill-proof 提供;P1 落地)。 +pub const LIBRARY_IMPORT: &str = "MarqdoProof"; + +/// 生成整个文件模块。返回 `(文件名, 内容)`。 +pub fn emit_module(plan: &Plan, module_stem: &str) -> (String, String) { + let namespace = namespace_of(module_stem); + let mut out = String::new(); + let _ = writeln!(out, "import {LIBRARY_IMPORT}"); + let _ = writeln!(out, "open MarqdoProof"); + let _ = writeln!(out); + let _ = writeln!(out, "-- 由 `marqdo prove emit` 生成:确定性输出,请勿手改。"); + let _ = writeln!(out, "-- 源:{}(sha256 {})", plan.module, plan.source_sha256); + let _ = writeln!(out, "namespace Generated.{}", namespace); + let _ = writeln!(out); + + // 模块级 Op:所有函数的不透明操作并集(保持首次出现顺序,去重)。 + emit_op_inductive(&mut out, plan); + let _ = writeln!(out); + + for fun in &plan.functions { + emit_function(&mut out, fun); + let _ = writeln!(out); + emit_theorems(&mut out, fun); + let _ = writeln!(out); + } + + let _ = writeln!(out, "end Generated.{}", namespace); + let file_name = format!("{namespace}.lean"); + (file_name, out) +} + +/// 定理脚手架(§7.2):受限文法可解析的命题 → `theorem` 陈述 + `sorry` +fn emit_theorems(out: &mut String, fun: &FnPlan) { + if fun.claims.is_empty() { + return; + } + let fun_name = lean_ident(&fun.name); + // 定理形参:`env 轨迹₀` + 函数形参。 + let mut binders = String::from("(env : Env) (轨迹₀ : List Op)"); + for param in &fun.params { + let _ = write!(binders, " ({} : Val)", lean_ident(¶m.name)); + } + for claim in &fun.claims { + let premise_lean = claim + .premise + .as_deref() + .and_then(claim_to_lean_bool); + let conclusion_lean = claim_to_lean_bool(&claim.conclusion); + let premise_text = match (&claim.premise, premise_lean) { + (Some(_), Some(lean)) => format!(" (h_前提 : mqTruth {lean})"), + _ => String::new(), + }; + let tactic = claim.tactic.as_deref().unwrap_or("auto"); + let _ = writeln!(out, "-- 定理 {}(策略 {tactic};mq: {})", claim.id, claim.line); + match conclusion_lean { + Some(conclusion) => { + let _ = writeln!( + out, + "theorem {} {binders}{premise_text} :", + lean_ident(&format!("{}.{}", fun.name, claim.id)) + ); + let _ = writeln!( + out, + " ∀ (结果 : Val) (轨迹 : List Op)," + ); + let _ = writeln!( + out, + " ({fun_name} env 轨迹₀ {} = (结果, 轨迹)) →", + fun.params + .iter() + .map(|p| lean_ident(&p.name)) + .collect::>() + .join(" ") + ); + let _ = writeln!(out, " {conclusion} := by"); + let _ = writeln!(out, " intro 结果 轨迹 h_run"); + let _ = writeln!(out, " unfold {fun_name} at h_run"); + let _ = writeln!(out, " split at h_run <;> simp_all <;> omega"); + } + _ => { + let _ = writeln!( + out, + "-- 未生成:前提/结论超出受限文法(check --proof 会给具体诊断)" + ); + } + } + } +} + +/// 命名空间:文件名的安全标识符(保留 unicode 字母;不安全字符 → `_`)。 +pub fn namespace_of(stem: &str) -> String { + let mut out = String::new(); + for ch in stem.chars() { + if ch.is_alphanumeric() || ch == '_' { + out.push(ch); + } else { + out.push('_'); + } + } + if out.is_empty() { + out.push('M'); + } + if out.chars().next().is_some_and(|c| c.is_ascii_digit()) { + out.insert(0, 'M'); + } + out +} + +/// Lean 保留字与本模块保留名(含点/空格的用 `«…»`;关键字加前缀)。 +const LEAN_KEYWORDS: &[&str] = &[ + "fun", "let", "in", "do", "match", "with", "if", "then", "else", "true", "false", "and", "or", + "not", "def", "theorem", "abbrev", "structure", "inductive", "where", "deriving", "open", + "namespace", "end", "import", "by", "have", "show", "assume", "from", "at", "exists", +]; + +fn lean_ident(name: &str) -> String { + if LEAN_KEYWORDS.contains(&name) || name == "env" || name == "轨迹" || name == "结果" { + format!("v_{name}") + } else if name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '·') + && !name.chars().next().is_some_and(|c| c.is_ascii_digit()) + { + name.to_string() + } else { + format!("«{name}»") + } +} + +fn op_ctor(op_id: &str) -> String { + // `调用:人工审核` → `«调用:人工审核»`(guillemet 标识符)。 + format!("«{op_id}»") +} + +fn emit_op_inductive(out: &mut String, plan: &Plan) { + // 收集 op(首现顺序去重)。 + let mut ops: Vec<&crate::prove::ir::OpDecl> = Vec::new(); + for fun in &plan.functions { + for op in &fun.ops { + if !ops.iter().any(|o| o.id == op.id) { + ops.push(op); + } + } + } + if ops.is_empty() { + let _ = writeln!(out, "inductive Op where"); + let _ = writeln!(out, " | 无操作 deriving Repr, BEq"); + let _ = writeln!(out); + let _ = writeln!(out, "def Op.name : Op → String"); + let _ = writeln!(out, " | .无操作 => \"\""); + return; + } + let _ = writeln!(out, "inductive Op where"); + for op in &ops { + let fields = match op.arity { + 0 => String::new(), + n => (1..=n) + .map(|i| format!("(参数{i} : Val)")) + .collect::>() + .join(" "), + }; + let _ = writeln!(out, " | {} {}", op_ctor(&op.id), fields); + } + let _ = writeln!(out, " deriving Repr, BEq"); + let _ = writeln!(out); + let _ = writeln!(out, "def Op.name : Op → String"); + for op in &ops { + let label = op.id.strip_prefix("调用:").unwrap_or(&op.id); + let blanks = " ".repeat(op.arity); + let _ = writeln!(out, " | .{} {}=> \"{}\"", op_ctor(&op.id), blanks, label); + } +} + +fn emit_function(out: &mut String, fun: &FnPlan) { + let name = lean_ident(&fun.name); + // 参数列表:`def f (env : Env) (轨迹 : List Op) (p1 : Val) …` + let mut sig = String::from("(env : Env) (轨迹 : List Op)"); + for param in &fun.params { + let _ = write!(sig, " ({} : Val)", lean_ident(¶m.name)); + } + let _ = writeln!(out, "-- {} 返回 {}", fun.name, fun.result_ty.name()); + let _ = writeln!(out, "def {name} {sig} : Val × List Op :="); + if fun.steps.is_empty() { + let _ = writeln!(out, " (Val.none, 轨迹)"); + return; + } + emit_seq(out, &mut String::from(" "), &[&fun.steps]); +} + +/// 续延式直接降级(§6.3):`chunks` 是"当前点之后还要执行的所有步骤"。 +/// +/// `if` 的两臂续延是「臂内步骤 + 臂外剩余」——执行继续到分支之后, +/// 除非某臂已提前 `Return`。这是 P0 第一版的续延丢失 bug 的修正: +/// 分支绝不能吞掉后续语句。 +fn emit_seq(out: &mut String, indent: &mut String, chunks: &[&[Step]]) { + match chunks.split_first() { + None => { + // 走到末尾都没有 return:Marqdo 返回 None(诚实占位,不译运行时)。 + let _ = writeln!(out, "{indent}(Val.none, 轨迹)"); + } + Some((first, rest)) => match first.split_first() { + None => emit_seq(out, indent, rest), + Some((step, more)) => emit_step(out, indent, step, more, rest), + }, + } +} + +fn tail_chunks<'a>(more: &'a [Step], rest: &[&'a [Step]]) -> Vec<&'a [Step]> { + let mut next: Vec<&'a [Step]> = Vec::with_capacity(rest.len() + 1); + if !more.is_empty() { + next.push(more); + } + next.extend_from_slice(rest); + next +} + +fn emit_step(out: &mut String, indent: &mut String, step: &Step, more: &[Step], rest: &[&[Step]]) { + match step { + Step::Bind { var, expr, line } => { + let _ = writeln!(out, "{indent}-- mq: {line}:1"); + match expr { + IrExpr::Op { id, args } => { + let _ = writeln!( + out, + "{indent}let {} := env (Op.{} {})", + lean_ident(var), + op_ctor(id), + emit_args(args) + ); + let _ = writeln!( + out, + "{indent}let 轨迹 := 轨迹 ++ [Op.{} {}]", + op_ctor(id), + emit_args(args) + ); + } + other => { + let _ = writeln!( + out, + "{indent}let {} := {}", + lean_ident(var), + emit_expr(other) + ); + } + } + emit_seq(out, indent, &tail_chunks(more, rest)); + } + Step::Return { expr, line } => { + let _ = writeln!(out, "{indent}-- mq: {line}:1"); + match expr { + IrExpr::Op { id, args } => { + let _ = writeln!( + out, + "{indent}(env (Op.{} {}), 轨迹 ++ [Op.{} {}])", + op_ctor(id), + emit_args(args), + op_ctor(id), + emit_args(args) + ); + } + other => { + let _ = writeln!(out, "{indent}({}, 轨迹)", emit_expr(other)); + } + } + } + Step::Trace { op, args, line } => { + let _ = writeln!(out, "{indent}-- mq: {line}:1"); + let _ = writeln!( + out, + "{indent}let 轨迹 := 轨迹 ++ [Op.{} {}]", + op_ctor(op), + emit_args(args) + ); + emit_seq(out, indent, &tail_chunks(more, rest)); + } + Step::If { + cond, + then, + otherwise, + line, + } => { + let _ = writeln!(out, "{indent}-- mq: {line}:1"); + let _ = writeln!(out, "{indent}if {} then", emit_cond(cond)); + indent.push_str(" "); + let then_chunks = { + let mut v: Vec<&[Step]> = Vec::with_capacity(rest.len() + 1); + v.push(then); + v.extend_from_slice(&tail_chunks(more, rest)); + v + }; + emit_seq(out, indent, &then_chunks); + indent.truncate(indent.len() - 2); + let _ = writeln!(out, "{indent}else"); + indent.push_str(" "); + let else_chunks = { + let mut v: Vec<&[Step]> = Vec::with_capacity(rest.len() + 1); + v.push(otherwise); + v.extend_from_slice(&tail_chunks(more, rest)); + v + }; + emit_seq(out, indent, &else_chunks); + indent.truncate(indent.len() - 2); + } + } +} + +/// 条件:比较直接产出 Bool;其余经 `mqTruth`(Val → Bool)。 +fn emit_cond(cond: &PureExpr) -> String { + match cond { + PureExpr::Bin { + operator: BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge, + .. + } => emit_pure(cond), + _ => format!("mqTruth ({})", emit_pure(cond)), + } +} + +fn emit_args(args: &[PureExpr]) -> String { + args.iter() + .map(|a| emit_pure(a)) + .collect::>() + .join(" ") +} + +fn emit_expr(expr: &IrExpr) -> String { + match expr { + IrExpr::Pure(pure) => emit_pure(pure), + // 语句层不会遇到(Op 已在 Bind/Return/Trace 处理);防御性回退。 + IrExpr::Op { id, args } => { + format!("env (Op.{} {})", op_ctor(id), emit_args(args)) + } + IrExpr::Formula => "Val.none -- $$公式$$:不透明值".into(), + IrExpr::Code => "Val.none -- code 围栏:不透明值".into(), + } +} + +fn emit_pure(pure: &PureExpr) -> String { + match pure { + PureExpr::Int(i) => format!("(Val.int {i})"), + PureExpr::Num(n) => format!("(Val.num {n:?})"), + PureExpr::Bool(b) => format!("(Val.bool {})", if *b { "true" } else { "false" }), + PureExpr::Text(s) => format!("(Val.text {})", lean_string(s)), + PureExpr::None => "Val.none".into(), + PureExpr::Var(name) => lean_ident(name), + PureExpr::Bin { operator, left, right } => { + let (l, r) = (emit_pure(left), emit_pure(right)); + match operator { + BinOp::Add => format!("(mqAdd {l} {r})"), + BinOp::Sub => format!("(mqSub {l} {r})"), + BinOp::Mul => format!("(mqMul {l} {r})"), + BinOp::Div => format!("(mqDiv {l} {r})"), + BinOp::Eq => format!("(mqEq {l} {r})"), + BinOp::Ne => format!("(mqNot (mqEq {l} {r}))"), + BinOp::Lt => format!("(mqLt {l} {r})"), + BinOp::Le => format!("(mqLe {l} {r})"), + BinOp::Gt => format!("(mqGt {l} {r})"), + BinOp::Ge => format!("(mqGe {l} {r})"), + BinOp::And => format!("(mqAnd {l} {r})"), + BinOp::Or => format!("(mqOr {l} {r})"), + } + } + PureExpr::Un { operator, expr } => { + let e = emit_pure(expr); + match operator { + UnOp::Not => format!("(mqNot {e})"), + UnOp::Neg => format!("(mqNeg {e})"), + } + } + PureExpr::Index { base, key } => { + format!("(mqAccess {} {})", emit_pure(base), lean_string(key)) + } + PureExpr::Access { base, key } => { + format!("(mqAccess {} {})", emit_pure(base), lean_string(key)) + } + PureExpr::Len(inner) => format!("(mqLen {})", emit_pure(inner)), + PureExpr::Interp(parts) => emit_interp(parts), + PureExpr::List(items) => { + let inner: Vec = items.iter().map(emit_pure).collect(); + format!("(Val.list [{}])", inner.join(", ")) + } + PureExpr::Map(entries) => { + let inner: Vec = entries + .iter() + .map(|(k, v)| format!("({}, {})", lean_string(k), emit_pure(v))) + .collect(); + format!("(Val.map [{}])", inner.join(", ")) + } + PureExpr::Ctor { name, args } => emit_ctor(name, args), + } +} + +/// 内联构造器:`result.ok/error/value_or` 映射到库辅助函数 +/// (Val 字面 map,与 lib/result 行为一致);`mq.*` 直呼。 +fn emit_ctor(name: &str, args: &[PureExpr]) -> String { + let rendered: Vec = args.iter().map(emit_pure).collect(); + match (name, rendered.as_slice()) { + ("result.ok", [value]) => format!("(mqResultOk {value})"), + ("result.error", [code, message, operation]) => { + format!("(mqResultError {code} {message} {operation})") + } + ("result.value_or", [r, default]) => format!("(mqValueOr {r} {default})"), + _ => format!("({} {})", name.replace('.', "_"), rendered.join(" ")), + } +} + +fn emit_interp(parts: &[InterpPart]) -> String { + let mut pieces: Vec = Vec::new(); + for part in parts { + match part { + InterpPart::Lit(text) => pieces.push(format!("(Val.text {})", lean_string(text))), + InterpPart::Var(name) => pieces.push(lean_ident(name)), + } + } + if pieces.is_empty() { + return "(Val.text \"\")".into(); + } + let mut it = pieces.into_iter(); + let first = it.next().unwrap(); + it.fold(first, |acc, piece| format!("(mqAppend {acc} {piece})")) +} + +/// Lean 字符串字面量(转义 `\` `"` 与控制字符;非 ASCII 原样保留)。 +fn lean_string(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for ch in s.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// 模块 stem(命名空间用):去扩展名的文件名。 +pub fn stem_of(path: &str) -> String { + std::path::Path::new(path) + .file_stem() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_else(|| "Module".into()) +} + +/// PlanTy 的 Lean 侧提示注释(P1 提升类型用;P0 参数统一 Val)。 +pub fn ty_hint(ty: &PlanTy) -> &'static str { + match ty { + PlanTy::Int => "Int", + PlanTy::Num => "Float", + PlanTy::Bool => "Bool", + PlanTy::Text => "String", + _ => "Val", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::prove::ir::{Expr, FnPlan, OpDecl, PlanTy, Step}; + + #[test] + fn lean_ident_keeps_chinese_and_quotes_dotted() { + assert_eq!(lean_ident("金额"), "金额"); + assert_eq!(lean_ident("审批台.审批"), "«审批台.审批»"); + // 与本模块保留名冲突的变量必须改名(确定性映射)。 + assert_eq!(lean_ident("env"), "v_env"); + assert_eq!(lean_ident("轨迹"), "v_轨迹"); + assert_eq!(lean_ident("结果"), "v_结果"); + assert_eq!(lean_ident("let"), "v_let"); + } + + #[test] + fn lean_string_escapes_quotes_and_newline_only() { + assert_eq!(lean_string("a\"b\\c"), "\"a\\\"b\\\\c\""); + assert_eq!(lean_string("行\n进"), "\"行\\n进\""); + assert_eq!(lean_string("中文"), "\"中文\""); + } + + #[test] + fn namespace_sanitizes_unsafe_chars_deterministically() { + assert_eq!(namespace_of("approval.mq"), "approval_mq"); + assert_eq!(namespace_of("示例"), "示例"); + assert_eq!(namespace_of("1abc"), "M1abc"); + assert_eq!(namespace_of(""), "M"); + } + + #[test] + fn emit_module_is_deterministic_and_sorted_by_first_appearance() { + let plan = Plan { + schema: crate::prove::ir::SCHEMA, + module: "demo.mq.md".into(), + source_sha256: "ab".repeat(32), + functions: vec![ + FnPlan { + name: "机器.运转".into(), + params: vec![], + result_ty: PlanTy::Any, + ops: vec![ + OpDecl { + id: "调用:写盘".into(), + effect: "fs.write".into(), + params: vec![], + arity: 1, + }, + OpDecl { + id: "调用:读盘".into(), + effect: "fs.read".into(), + params: vec![], + arity: 0, + }, + ], + steps: vec![Step::Bind { + var: "回执".into(), + expr: Expr::Op { + id: "调用:写盘".into(), + args: vec![], + }, + line: 3, + }], + effects: vec!["fs.write".into()], + claims: vec![], + assumptions: vec![], + }, + FnPlan { + name: "从机.待机".into(), + params: vec![], + result_ty: PlanTy::Any, + ops: vec![], + steps: vec![Step::Return { + expr: Expr::Pure(PureExpr::Int(7)), + line: 9, + }], + effects: vec![], + claims: vec![], + assumptions: vec![], + }, + ], + }; + let (name1, out1) = emit_module(&plan, "demo"); + let (name2, out2) = emit_module(&plan, "demo"); + assert_eq!(name1, name2); + assert_eq!(out1, out2, "两次生成必须字节一致"); + assert!(out1.contains("import MarqdoProof")); + assert!(out1.contains("namespace Generated.demo")); + // Op 按首现顺序:写盘在读盘前。 + let write_pos = out1.find("«调用:写盘»").expect("write op"); + let read_pos = out1.find("«调用:读盘»").expect("read op"); + assert!(write_pos < read_pos); + // Op 元数:读盘 0 元 → 无参构造器。 + assert!(out1.contains("| «调用:读盘»"), "{out1}"); + // Return 直译成对(字面量自带括号,形成双重括号——合法 Lean)。 + assert!(out1.contains("((Val.int 7), 轨迹)"), "{out1}"); + // 溯源注释。 + assert!(out1.contains("-- mq: 3:1")); + // 无时间戳。 + assert!(!out1.contains("20") || !out1.contains("T"), "no timestamps"); + } + + #[test] + fn empty_plan_emits_no_op_ctors() { + let plan = Plan { + schema: crate::prove::ir::SCHEMA, + module: "空.mq.md".into(), + source_sha256: "cd".repeat(32), + functions: vec![], + }; + let (name, out) = emit_module(&plan, "空"); + assert_eq!(name, "空.lean"); + assert!(out.contains("| 无操作")); + assert!(!out.contains("«调用:")); + } +} + + +/// 受限命题文本 → Lean Bool 项;解析失败或含未知形状 → None(emit 侧留注释)。 +/// 语义映射(§7.2): +/// - `结果.ok / 结果.value / 结果.error` → `mqAccess 结果 "ok"` 等; +/// - `包含(轨迹, s)` → `(轨迹.map Op.name).contains s`; +/// - `长度(轨迹)` → `(轨迹.length : Nat)`(与自然数比较); +/// - 形参/算术/比较 → mq 辅助函数(Val 面)。 +fn claim_to_lean_bool(text: &str) -> Option { + let toks = super::proof_check::tokenize_claim(text).ok()?; + let (_, ast) = super::proof_check::parse_claim_expr(&toks).ok()?; + Some(claim_term(&ast)) +} + +fn claim_term(ast: &super::proof_check::ClaimAst) -> String { + use super::proof_check::{ClaimAst as A, CTok}; + match ast { + A::Lit(CTok::Int(i)) => format!("(Val.int {i})"), + A::Lit(CTok::Num(n)) => format!("(Val.num {n:?})"), + A::Lit(CTok::Bool(b)) => format!("(Val.bool {b})"), + A::Lit(CTok::Text(s)) => format!("(Val.text {})", lean_string(s)), + A::Lit(other) => format!("-- 未知字面量 {other:?}"), + A::Var(name) => { + // 定理作用域里 `结果`/`轨迹` 是 ∀ 绑定的输出名(不加 v_ 前缀); + // `根.字段` → mqAccess 字段读取;其余按标识符规则(形参等)。 + let (root, field) = match name.split_once('.') { + Some((r, f)) => (r, Some(f)), + None => (name.as_str(), None), + }; + match (root, field) { + ("结果", Some(f)) => format!("(mqAccess 结果 {})", lean_string(f)), + ("轨迹", Some(f)) => format!("(mqAccess 轨迹 {})", lean_string(f)), + ("结果", None) => "结果".to_string(), + ("轨迹", None) => "轨迹".to_string(), + _ => lean_ident(name), + } + } + A::Call { name, args } => { + // `轨迹`(定理作用域的输出轨迹)上的谓词有专用 Lean 形式。 + let on_trace = matches!(args.first(), Some(A::Var(v)) if v == "轨迹"); + match (name.as_str(), args.len(), on_trace) { + ("包含", 2, true) => { + format!( + "((轨迹.map Op.name).contains {})", + strip_val_text(&claim_term(&args[1])) + ) + } + ("长度", 1, true) => "(轨迹.length : Nat)".to_string(), + _ => { + let rendered: Vec = args.iter().map(claim_term).collect(); + match (name.as_str(), rendered.as_slice()) { + ("包含", [list, item]) => format!("(mqContains {list} {item})"), + ("长度", [list]) => format!("(mqNatOf (mqLen {list}))"), + ("下标", [list, index]) => { + format!("(mqAccess {list} (mqStrOfNat {index}))") + } + _ => format!("({} {})", name, rendered.join(" ")), + } + } + } + } + A::Bin { op, left, right } => { + let (l, r) = (claim_term(left), claim_term(right)); + match *op { + "+" => format!("(mqAdd {l} {r})"), + "-" => format!("(mqSub {l} {r})"), + "*" => format!("(mqMul {l} {r})"), + "/" => format!("(mqDiv {l} {r})"), + "=" => format!("(mqEq {l} {r})"), + "≠" => format!("(mqNot (mqEq {l} {r}))"), + "<" => format!("(mqLt {l} {r})"), + "≤" => format!("(mqLe {l} {r})"), + ">" => format!("(mqGt {l} {r})"), + "≥" => format!("(mqGe {l} {r})"), + "且" => format!("(mqAnd {l} {r})"), + "或" => format!("(mqOr {l} {r})"), + other => format!("-- 未知算子 {other}"), + } + } + A::Un { op, expr } => { + let e = claim_term(expr); + match *op { + "非" => format!("(mqNot {e})"), + "-" => format!("(mqNeg {e})"), + other => format!("-- 未知一元算子 {other}"), + } + } + } +} + +/// `包含` 的成员是文本字面量时剥掉 Val 包裹(`(Val.text "x")` → `"x"`)。 +fn strip_val_text(term: &str) -> String { + term.strip_prefix("(Val.text ") + .and_then(|rest| rest.strip_suffix(')')) + .map(|s| s.to_string()) + .unwrap_or_else(|| term.to_string()) +} diff --git a/src/prove/ir.rs b/src/prove/ir.rs new file mode 100644 index 0000000..75e3616 --- /dev/null +++ b/src/prove/ir.rs @@ -0,0 +1,296 @@ +//! Plan IR(`doc/design/prove-cli.md` §4.2)。 +//! +//! `plan.json` 的形状:版本化、可序列化、无时间戳。缓存键与论文工具都以 +//! 它为输入。表达式分两层:[`PureExpr`] 是可翻译成 Lean 项的纯片段; +//! 其余调用一律是不透明操作([`Step::Trace`] 引用 [`FnPlan::ops`])。 + +use serde::Serialize; + +/// IR schema version(缓存失效用;形状变化必须 +1)。 +pub const SCHEMA: u32 = 1; + +/// 契约类型在 Plan IR 里的形状(`contract::Ty` 的可序列化投影)。 +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum PlanTy { + Int, + Num, + Bool, + Text, + List, + Map, + /// 内联 `Result` 构造器(`lib/result`):`ok/value/error` 三字段结构。 + Result, + /// 未知/任意(`--no-strict-types` 或未标注)。定理只能做等式判断。 + Any, + /// `# 对象` 类型实例。 + Object(String), +} + +impl PlanTy { + pub fn name(&self) -> String { + match self { + PlanTy::Int => "int".into(), + PlanTy::Num => "num".into(), + PlanTy::Bool => "bool".into(), + PlanTy::Text => "text".into(), + PlanTy::List => "list".into(), + PlanTy::Map => "map".into(), + PlanTy::Result => "result".into(), + PlanTy::Any => "any".into(), + PlanTy::Object(n) => n.clone(), + } + } + + pub fn from_contract(ty: &crate::contract::Ty) -> PlanTy { + match ty { + crate::contract::Ty::Any => PlanTy::Any, + crate::contract::Ty::Text => PlanTy::Text, + crate::contract::Ty::Number => PlanTy::Int, + crate::contract::Ty::Bool => PlanTy::Bool, + crate::contract::Ty::List => PlanTy::List, + crate::contract::Ty::Map => PlanTy::Map, + crate::contract::Ty::Object(n) => PlanTy::Object(n.clone()), + } + } +} + +/// 二元运算(纯片段内的算术/比较/布尔)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum BinOp { + Add, + Sub, + Mul, + Div, + Eq, + Ne, + Lt, + Le, + Gt, + Ge, + And, + Or, +} + +impl BinOp { + pub fn from_ast(op: crate::ast::BinaryOp) -> BinOp { + use crate::ast::BinaryOp as A; + match op { + A::Add => BinOp::Add, + A::Sub => BinOp::Sub, + A::Mul => BinOp::Mul, + A::Div => BinOp::Div, + A::Eq => BinOp::Eq, + A::Ne => BinOp::Ne, + A::Lt => BinOp::Lt, + A::Le => BinOp::Le, + A::Gt => BinOp::Gt, + A::Ge => BinOp::Ge, + A::And => BinOp::And, + A::Or => BinOp::Or, + } + } +} + +/// 一元运算。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum UnOp { + Not, + Neg, +} + +/// 纯表达式:可翻译成 Lean 项的部分(§4.2 表达式分层)。 +/// 相邻标记(`kind` + `value`):新类型变体也能稳定序列化。 +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "kind", content = "value", rename_all = "snake_case")] +pub enum PureExpr { + Int(i64), + Num(f64), + Bool(bool), + Text(String), + None, + Var(String), + Bin { + operator: BinOp, + left: Box, + right: Box, + }, + Un { + operator: UnOp, + expr: Box, + }, + /// 映射字段/下标读取:`` [键](映射) `` / `` `m`[^键] ``。 + Index { + base: Box, + key: String, + }, + /// `access(base, key)`(含 `取`/`取值` 别名)。 + Access { + base: Box, + key: String, + }, + /// `len(value)`(含 `长度` 别名)。 + Len(Box), + /// 文本插值拼接(`` "共 `n` 条" `` → append 序列)。 + Interp(Vec), + List(Vec), + Map(Vec<(String, PureExpr)>), + /// 已内联的构造器调用(`result.success/failure`)。 + Ctor { + name: String, + args: Vec, + }, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "part", content = "value", rename_all = "snake_case")] +pub enum InterpPart { + Lit(String), + Var(String), +} + +/// 语句(§4.3 接受矩阵的接受侧)。 +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Step { + /// `**x = 表达式**` + Bind { + var: String, + expr: Expr, + line: u32, + }, + /// `**返回表达式**`(粗体无赋值) + Return { + expr: Expr, + line: u32, + }, + /// `1. 条件 / 2. *`(else 由 `cond: None` 表示) + If { + cond: PureExpr, + then: Vec, + otherwise: Vec, + line: u32, + }, + /// 语句形式调用(`> 调用` / `*语句*`):值丢弃,但仍进轨迹。 + Trace { + op: String, + args: Vec, + line: u32, + }, +} + +/// 语句内表达式:纯表达式或不透明操作调用。 +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Expr { + Pure(PureExpr), + /// 不透明操作调用:`ops` 里的 `id`(接收者/插件/有效应的调用)。 + Op { + id: String, + args: Vec, + }, + /// `$$…$$` 公式:不透明值,不翻译。 + Formula, + /// ``` 围栏 code 值(不经 parse 拒绝时降为不透明)。 + Code, +} + +/// 一个不透明操作的声明(Lean 里是 `Op` 构造器 + `Env` 查询键)。 +#[derive(Debug, Clone, Serialize)] +pub struct OpDecl { + pub id: String, + pub effect: String, + pub params: Vec<(String, PlanTy)>, + /// 实参个数(首次出现处;同名操作元数一致)。 + pub arity: usize, +} + +/// 定理占位(P1 起填充;P0 恒为空,保持 `plan.json` 形状稳定)。 +#[derive(Debug, Clone, Serialize)] +pub struct ClaimPlan { + pub id: String, + pub premise: Option, + pub conclusion: String, + pub tactic: Option, + /// 定理表行号(锚定源码漂移)。 + pub line: u32, +} + +/// 假设表条目(T3;P0 恒为空)。 +#[derive(Debug, Clone, Serialize)] +pub struct AssumptionPlan { + pub op: String, + pub premise: Option, + pub postcondition: String, +} + +/// 单个函数的 Plan。 +#[derive(Debug, Clone, Serialize)] +pub struct FnPlan { + pub name: String, + pub params: Vec, + pub result_ty: PlanTy, + /// 该函数用到的不透明操作(按出现顺序,去重)。 + pub ops: Vec, + pub steps: Vec, + pub effects: Vec, + pub claims: Vec, + pub assumptions: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ParamPlan { + pub name: String, + pub ty: PlanTy, + pub has_default: bool, +} + +/// 整个文件的 Plan。 +#[derive(Debug, Clone, Serialize)] +pub struct Plan { + pub schema: u32, + /// 相对当前工作目录的路径(确定性要求:无绝对路径、无时间戳)。 + pub module: String, + pub source_sha256: String, + pub functions: Vec, +} + +impl Plan { + /// 规范化 JSON(键序稳定、无空白差异;两次运行必须字节一致)。 + pub fn to_stable_json(&self) -> String { + let value = serde_json::to_value(self).expect("plan serializes"); + format_value(&value) + } +} + +/// 确定性 JSON 序列化:对象键排序、数组保序、定长浮点。 +fn format_value(value: &serde_json::Value) -> String { + use serde_json::Value; + match value { + Value::Null => "null".into(), + Value::Bool(b) => b.to_string(), + Value::Number(n) => n.to_string(), + Value::String(s) => serde_json::to_string(s).expect("string serializes"), + Value::Array(items) => { + let inner: Vec = items.iter().map(format_value).collect(); + format!("[{}]", inner.join(",")) + } + Value::Object(map) => { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + let inner: Vec = keys + .into_iter() + .map(|k| { + format!( + "{}:{}", + serde_json::to_string(k).expect("key serializes"), + format_value(&map[k]) + ) + }) + .collect(); + format!("{{{}}}", inner.join(",")) + } + } +} diff --git a/src/prove/lower.rs b/src/prove/lower.rs new file mode 100644 index 0000000..e7ca523 --- /dev/null +++ b/src/prove/lower.rs @@ -0,0 +1,1241 @@ +//! 降级:AST → Plan IR(`doc/design/prove-cli.md` §4.1 ②)。 +//! +//! 三条硬边界(设计 §2.2)——`while`/递归/动态派发(函数值、无法解析的裸名) +//! **拒绝,不降级**;静态可拼写的未知调用(方法、`工程.成员` 一类插件路径) +//! 一律不透明化为 [`ir::Expr::Op`](诚实:行为完全未知,效应照 sema 标注)。 +//! 本模块不执行任何代码,只读 AST。 + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use anyhow::Result; + +use crate::ast::{self, Arg, BinaryOp, CallExpr, Expr, Function, Module, Stmt}; +use crate::diagnostics::{Diagnostic, Severity, Span}; +use crate::prove::ir::{ + BinOp, ClaimPlan, Expr as IrExpr, FnPlan, InterpPart, OpDecl, ParamPlan, Plan, PlanTy, + PureExpr, Step, UnOp, SCHEMA, +}; +use crate::sema::bind::{call_display, resolve_for_exec}; +use crate::host::HostFn; +use crate::sema::ir::EffectSet; +use crate::sema::resolution::Target; + +/// 单个函数的降级产物(plan 或拒绝原因)。 +#[derive(Debug)] +pub struct Lowered { + pub display: String, + /// 对象体(`# 类型`)不是可证单元:不证也不算拒绝。 + pub is_object: bool, + pub plan: Option, + /// 全部拒绝原因(`proof.while` / `proof.recursion` / `proof.dynamic_call` / …)。 + pub rejected: Vec, +} + +/// 降级上下文:模块 + 效应表(来自 sema;缺失时效应保守记 `unknown`)。 +pub struct Lowerer<'m> { + module: &'m Module, + /// `(file, display_name) → effects`(sema 闭包 artifact 的源位置键)。 + effects: BTreeMap<(String, String), EffectSet>, + allow_opaque: BTreeSet, +} + +impl<'m> Lowerer<'m> { + pub fn new( + module: &'m Module, + effects: BTreeMap<(String, String), EffectSet>, + _strict_types: bool, + allow_opaque: &[String], + ) -> Self { + Self { + module, + effects, + allow_opaque: allow_opaque.iter().cloned().collect(), + } + } + + /// 降级全部函数(含子函数),按源码顺序。 + pub fn lower_module(&self) -> Vec { + let mut out = Vec::new(); + self.lower_functions(self.module.functions.as_slice(), "", &mut out); + out + } + + fn lower_functions(&self, funs: &[Function], prefix: &str, out: &mut Vec) { + for fun in funs { + let display = if prefix.is_empty() { + fun.name.clone() + } else { + format!("{prefix}.{}", fun.name) + }; + out.push(self.lower_function(&display, fun)); + self.lower_functions(&fun.children, &display, out); + } + } + + fn lower_function(&self, display: &str, fun: &Function) -> Lowered { + let mut rejected = Vec::new(); + // 对象体(`# 类型`)不是可证单元:P0 只证函数/方法。 + if fun.is_object() { + return Lowered { + display: display.to_string(), + is_object: true, + plan: None, + rejected, + }; + } + // `--allow-opaque `:整体降级为单个不透明操作,优先于子集验收 + // (作者显式声明"行为未知",因此 while/递归也不再是拒绝理由)。 + if self.allow_opaque.contains(display) { + return Lowered { + display: display.to_string(), + is_object: false, + plan: Some(self.opaque_whole(display, fun)), + rejected, + }; + } + // 子集验收先于一切:拒绝的函数不生成 plan。 + self.check_subset(fun, &mut rejected); + if !rejected.is_empty() { + return Lowered { + display: display.to_string(), + is_object: false, + plan: None, + rejected, + }; + } + + let mut body = Body::default(); + for stmt in &fun.body { + self.lower_stmt(fun, stmt, &mut body); + } + if !body.rejected.is_empty() { + return Lowered { + display: display.to_string(), + is_object: false, + plan: None, + rejected: body.rejected, + }; + } + let plan = FnPlan { + name: display.to_string(), + params: fun + .params + .iter() + .map(|p| ParamPlan { + name: p.name.clone(), + ty: self.param_ty(fun, &p.name), + has_default: p.default.is_some(), + }) + .collect(), + result_ty: self.result_ty(fun), + ops: body.ops, + steps: body.steps, + effects: body + .op_effects + .iter() + .filter(|e| e.as_str() != "pure") + .cloned() + .collect(), + claims: fun + .claims + .iter() + .map(|c| ClaimPlan { + id: c.id.clone(), + premise: c.premise.clone(), + conclusion: c.conclusion.clone(), + tactic: c.tactic.clone(), + line: c.line, + }) + .collect(), + assumptions: Vec::new(), + }; + Lowered { + display: display.to_string(), + is_object: false, + plan: Some(plan), + rejected, + } + } + + fn opaque_whole(&self, display: &str, fun: &Function) -> FnPlan { + // 行为完全未知:效应标签一律 `opaque`(§4.5,比猜测诚实)。 + let effect = "opaque".to_string(); + let mut ops = Vec::new(); + let id = format!("调用:{display}"); + ops.push(OpDecl { + id: id.clone(), + effect, + params: Vec::new(), + arity: fun.params.len(), + }); + FnPlan { + name: display.to_string(), + params: fun + .params + .iter() + .map(|p| ParamPlan { + name: p.name.clone(), + ty: PlanTy::Any, + has_default: p.default.is_some(), + }) + .collect(), + result_ty: PlanTy::Any, + ops, + steps: vec![Step::Trace { + op: id, + args: fun + .params + .iter() + .map(|p| PureExpr::Var(p.name.clone())) + .collect(), + line: fun.span.line, + }], + effects: vec!["opaque".into()], + claims: Vec::new(), + assumptions: Vec::new(), + } + } + + // ---------------------------------------------------------------- 子集验收 + + /// 子集验收(§4.3 拒绝侧)。收集全部原因,不止第一条。 + fn check_subset(&self, fun: &Function, rejected: &mut Vec) { + for stmt in &fun.body { + self.check_stmt(stmt, fun, rejected); + } + // 递归:本函数显示名出现在自身可静态解析的调用闭包里。 + let display = self.display_of(fun); + if self.recurses(fun, &display, &mut BTreeSet::new()) { + rejected.push(reject( + self.module, + fun.span, + "proof.recursion", + format!("`{display}` 递归调用不在可证子集(需要归纳证明,超出 P0–P3 范围)"), + )); + } + } + + fn check_stmt(&self, stmt: &Stmt, fun: &Function, rejected: &mut Vec) { + match stmt { + Stmt::While { span, .. } => rejected.push(reject( + self.module, + *span, + "proof.while", + format!( + "`-` 循环不在可证子集:`{}` 被跳过(无循环 ⇒ 返回路径有限)", + fun.name + ), + )), + Stmt::ForEach { span, .. } => rejected.push(reject( + self.module, + *span, + "proof.foreach_pending", + "foreach 在 P3 才进入可证子集(需要列表有限性证据)", + )), + Stmt::Assign { value, span, .. } => self.check_expr(value, fun, *span, rejected), + Stmt::Return { value, span } => self.check_expr(value, fun, *span, rejected), + Stmt::Expr { value, span } => self.check_expr(value, fun, *span, rejected), + Stmt::Call { call, span } => self.check_call(call, fun, *span, rejected), + Stmt::Branch { arms, .. } => { + for arm in arms { + if let Some(cond) = &arm.condition { + // 条件的 span 在解析期未单独记录,用函数级锚点替代。 + self.check_expr(cond, fun, fun.span, rejected); + } + for s in &arm.body { + self.check_stmt(s, fun, rejected); + } + } + } + } + } + + fn check_expr(&self, expr: &Expr, fun: &Function, span: Span, rejected: &mut Vec) { + match expr { + Expr::Call(call) => self.check_call(call, fun, span, rejected), + Expr::Occluded { payload, .. } => { + if let Some(payload) = payload { + self.check_expr(payload, fun, span, rejected); + } + } + Expr::Binary { left, right, .. } => { + self.check_expr(left, fun, span, rejected); + self.check_expr(right, fun, span, rejected); + } + Expr::Unary { expr, .. } => self.check_expr(expr, fun, span, rejected), + Expr::List(items) => { + for item in items { + self.check_expr(item, fun, span, rejected); + } + } + Expr::Map(entries) => { + for (_, value) in entries { + self.check_expr(value, fun, span, rejected); + } + } + Expr::Index { base, .. } => self.check_expr(base, fun, span, rejected), + Expr::Interp(parts) => { + for part in parts { + if let ast::InterpPart::Index { .. } = part { + rejected.push(reject( + self.module, + span, + "proof.unsupported", + "插值中的下标读取不在 P0 纯片段", + )); + } + } + } + Expr::Var(_) | Expr::Literal(_) | Expr::Formula(_) | Expr::Code(_) => {} + } + } + + fn check_call(&self, call: &CallExpr, fun: &Function, span: Span, rejected: &mut Vec) { + for arg in &call.args { + let value = match arg { + Arg::Positional(value) | Arg::Named { value, .. } => value, + }; + self.check_expr(value, fun, span, rejected); + } + match resolve_for_exec(self.module, fun, call) { + Target::Local(target) => { + if target.is_object() { + rejected.push(reject( + self.module, + span, + "proof.dynamic_call", + format!("对象构造 `{}` 不在 P0 纯片段", call_display(call)), + )); + } + } + Target::Import { .. } | Target::Builtin(_) | Target::Host(_) => {} + Target::Dynamic { reason, name } => { + use crate::sema::bind::DynamicReason as R; + match reason { + R::CallFn | R::Plugin => rejected.push(reject( + self.module, + span, + "proof.dynamic_call", + format!("`{name}`:函数值/未知裸名调用不在可证子集"), + )), + // 方法调用(`` `recv`.m ``)与两段静态路径(`工程.成员`)都是 + // 静态可拼写的调用点 → 不透明操作,不拒绝(§4.3)。 + R::MethodReceiver => {} + } + } + Target::Unresolved { message, .. } => { + rejected.push(reject( + self.module, + span, + "proof.dynamic_call", + format!("`{}` 无法静态解析:{message}", call_display(call)), + )); + } + } + } + + fn display_of(&self, fun: &Function) -> String { + fn walk<'a>( + funs: &'a [Function], + prefix: &str, + target: &Function, + out: &mut Option, + ) { + if out.is_some() { + return; + } + for f in funs { + let display = if prefix.is_empty() { + f.name.clone() + } else { + format!("{prefix}.{}", f.name) + }; + if std::ptr::eq(f, target) { + *out = Some(display.clone()); + return; + } + walk(&f.children, &display, target, out); + } + } + let mut found = None; + walk(&self.module.functions, "", fun, &mut found); + found.unwrap_or_else(|| fun.name.clone()) + } + + /// 递归检测:从 `fun` 出发的可静态解析局部调用是否回到 `display`。 + fn recurses(&self, fun: &Function, display: &str, visiting: &mut BTreeSet) -> bool { + if !visiting.insert(display.to_string()) { + return true; + } + let mut found = false; + let calls = self.all_calls(fun); + for (call, callee_fun) in calls { + if let Target::Local(target) = resolve_for_exec(self.module, callee_fun, call) { + let target_display = self.display_of(target); + if target_display == display || self.recurses(target, &target_display, visiting) { + found = true; + break; + } + } + } + visiting.remove(display); + found + } + + /// 函数体里每个调用点及其**所在函数**(解析作用域)。 + fn all_calls<'a>(&'a self, fun: &'a Function) -> Vec<(&'a CallExpr, &'a Function)> { + let mut out = Vec::new(); + for stmt in &fun.body { + self.collect_stmt_calls(stmt, fun, &mut out); + } + out + } + + fn collect_stmt_calls<'a>( + &'a self, + stmt: &'a Stmt, + owner: &'a Function, + out: &mut Vec<(&'a CallExpr, &'a Function)>, + ) { + match stmt { + Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { + for call in collect_calls(value) { + out.push((call, owner)); + } + } + Stmt::Call { call, .. } => out.push((call, owner)), + Stmt::Branch { arms, .. } => { + for arm in arms { + if let Some(cond) = &arm.condition { + for call in collect_calls(cond) { + out.push((call, owner)); + } + } + for s in &arm.body { + self.collect_stmt_calls(s, owner, out); + } + } + } + _ => {} + } + } + + // ---------------------------------------------------------------- 语句降级 + + fn lower_stmt(&self, fun: &Function, stmt: &Stmt, body: &mut Body) { + match stmt { + Stmt::Assign { name, value, span, .. } => { + let expr = self.lower_expr(value, fun, span.line, body); + body.steps.push(Step::Bind { + var: name.clone(), + expr, + line: span.line, + }); + } + Stmt::Return { value, span } => { + let expr = self.lower_expr(value, fun, span.line, body); + body.steps.push(Step::Return { + expr, + line: span.line, + }); + } + Stmt::Call { call, span } => { + // 语句形式调用:值丢弃,但有效应的调用必须留下轨迹。 + if let IrExpr::Op { id, args } = self.lower_call_expr(call, fun, body) { + body.steps.push(Step::Trace { + op: id, + args, + line: span.line, + }); + } + } + Stmt::Expr { value, span } => { + if let IrExpr::Op { id, args } = self.lower_expr(value, fun, span.line, body) { + body.steps.push(Step::Trace { op: id, args, line: span.line }); + } + } + Stmt::Branch { arms, span } => { + let step = self.lower_branch(arms, span.line, fun, body); + body.steps.extend(step); + } + Stmt::While { span, .. } => body.rejected.push(reject( + self.module, + *span, + "proof.while", + "循环不在可证子集", + )), + Stmt::ForEach { span, .. } => body.rejected.push(reject( + self.module, + *span, + "proof.foreach_pending", + "foreach 在 P3 才进入可证子集", + )), + } + } + + /// 多臂分支 → 嵌套 if/else(保持源顺序;`1. 条件 / 2. *` 是两臂常态)。 + fn lower_branch( + &self, + arms: &[ast::BranchArm], + line: u32, + fun: &Function, + body: &mut Body, + ) -> Vec { + let Some(first) = arms.first() else { + return Vec::new(); + }; + let Some(cond) = &first.condition else { + // 首臂即 else(无条件的 `1. *`):平铺为主体。 + let before = body.steps.len(); + for s in &first.body { + self.lower_stmt(fun, s, body); + } + return body.steps.split_off(before); + }; + let cond_ir = self.lower_pure_required(cond, fun, line, body); + let then = { + let mut sub = Body { + inline_depth: body.inline_depth, + ..Body::default() + }; + for s in &first.body { + self.lower_stmt(fun, s, &mut sub); + } + let steps = std::mem::take(&mut sub.steps); + body.absorb(sub); + steps + }; + let otherwise = if arms.len() > 1 { + self.lower_branch(&arms[1..], line, fun, body) + } else { + Vec::new() + }; + vec![Step::If { + cond: cond_ir, + then, + otherwise, + line, + }] + } + + // ---------------------------------------------------------------- 表达式降级 + + fn lower_expr(&self, expr: &Expr, fun: &Function, line: u32, body: &mut Body) -> IrExpr { + match expr { + Expr::Call(call) => self.lower_call_expr(call, fun, body), + Expr::Occluded { payload, .. } => match payload { + Some(payload) => self.lower_expr(payload, fun, line, body), + None => IrExpr::Pure(PureExpr::None), + }, + other => match self.lower_pure(other, fun, body) { + Some(pure) => IrExpr::Pure(pure), + None => match other { + // `$$…$$` 公式与 code 围栏:不透明值(设计 §4.3,不翻译)。 + Expr::Formula(_) => IrExpr::Formula, + Expr::Code(_) => IrExpr::Code, + // 动态键读取 `` [`k`](m) ``:不透明读操作。 + Expr::Index { label: ast::IndexKey::Var(name), .. } => { + let id = body.register_op( + &format!("读取:`{name}`"), + "pure".to_string(), + 0, + ); + IrExpr::Op { id, args: Vec::new() } + } + _ => IrExpr::Pure(PureExpr::None), + }, + }, + } + } + + /// 调用 → 内联构造器 / 纯内建 / 不透明 Op。 + fn lower_call_expr(&self, call: &CallExpr, fun: &Function, body: &mut Body) -> IrExpr { + let mut args: Vec = Vec::with_capacity(call.args.len()); + for arg in call.args.iter() { + let value = match arg { + Arg::Positional(value) | Arg::Named { value, .. } => value, + }; + args.push(self.lower_arg(value, fun, body)); + } + match resolve_for_exec(self.module, fun, call) { + Target::Builtin(name) => lower_builtin(name, args, body), + Target::Host(host) => { + if host_is_pure(host) { + // Access 特形(字段读取)或 mq.* 构造器。 + return lower_host_pure(host, args); + } + let id = body.register_op(&call_display(call), effect_label_of_host(host), args.len()); + IrExpr::Op { id, args } + } + Target::Local(target) => { + let display = self.display_of(target); + // 自递归(防御;子集验收已拒绝)或超深内联 → 不透明。 + if std::ptr::eq(target, fun) || body.inline_depth >= 4 { + let id = body.register_op(&call_display(call), self.effect_of("self", &display), args.len()); + return IrExpr::Op { id, args }; + } + if self.is_inline_candidate(target) { + body.inline_depth += 1; + let lowered = self.inline_body(target, &args, body); + body.inline_depth -= 1; + lowered + } else { + let id = body.register_op(&call_display(call), self.effect_of("self", &display), args.len()); + IrExpr::Op { id, args } + } + } + Target::Import { bind, lib, fun: target, .. } => { + // lib/result 的构造器内联为结构(§4.5;真实库名是 ok/error/value_or)。 + if bind == "result" && matches!(target.name.as_str(), "ok" | "error" | "value_or") { + return IrExpr::Pure(PureExpr::Ctor { + name: format!("result.{}", target.name), + args, + }); + } + let display = if call.path.is_some() { + call_display(call) + } else { + format!("{bind}.{}", target.name) + }; + let effect = self.effect_of(&source_file(lib), &display); + let effect = if effect == "unknown" { + imported_effect_label(lib, target) + } else { + effect + }; + let id = body.register_op(&display, effect, args.len()); + IrExpr::Op { id, args } + } + // 方法调用 / 两段静态路径:不透明(§4.3),接收者不展开。 + Target::Dynamic { name, .. } => { + let id = body.register_op(&name, "unknown".to_string(), args.len()); + IrExpr::Op { id, args } + } + Target::Unresolved { message, .. } => { + body.rejected.push(reject( + self.module, + Span::new(0, 0), + "proof.dynamic_call", + format!("`{}` 无法静态解析:{message}", call_display(call)), + )); + IrExpr::Pure(PureExpr::None) + } + } + } + + /// 实参降级:纯表达式直接用;不透明子调用先绑定临时变量再引用。 + /// 临时名全局递增(`实参N`),避免内联展开时遮蔽调用者的同名变量。 + fn lower_arg(&self, value: &Expr, fun: &Function, body: &mut Body) -> PureExpr { + if let Some(pure) = self.lower_pure(value, fun, body) { + return pure; + } + match self.lower_expr(value, fun, 0, body) { + // 嵌套纯调用(lower_pure 因解析上下文失败的回退路径)。 + IrExpr::Pure(pure) => pure, + IrExpr::Op { id, args } => { + body.temps_count += 1; + let temp = format!("实参{}", body.temps_count); + body.steps.push(Step::Bind { + var: temp.clone(), + expr: IrExpr::Op { id, args }, + line: 0, + }); + PureExpr::Var(temp) + } + _ => PureExpr::None, + } + } + + /// §4.5 内联判据(P0 保守版):无分支的直线函数 + sema 效应 pure + 非递归。 + /// 含分支的被调在 P0 一律不透明化(符号执行落地后在 P2 放宽)。 + fn is_inline_candidate(&self, target: &Function) -> bool { + if target.is_object() || has_branching(&target.body) { + return false; + } + let stmt_count = count_stmts(&target.body); + if stmt_count == 0 || stmt_count > 24 { + return false; + } + let display = self.display_of(target); + self.effect_of("self", &display) == "pure" + } + + /// 内联直线函数体:形参 → 实参替换,语句平铺;返回值即调用值。 + /// op 声明按 id 去重共享;步骤先替换形参再并入主体。 + fn inline_body(&self, target: &Function, args: &[PureExpr], body: &mut Body) -> IrExpr { + let mut result = IrExpr::Pure(PureExpr::None); + let mut sub = Body { + inline_depth: body.inline_depth, + temps_count: body.temps_count, + ..Body::default() + }; + for stmt in &target.body { + match stmt { + Stmt::Return { value, .. } => { + result = self.lower_expr(value, target, crate::ast::stmt_line(stmt), &mut sub); + } + _ => self.lower_stmt(target, stmt, &mut sub), + } + } + let params: Vec = target.params.iter().map(|p| p.name.clone()).collect(); + for step in sub.steps { + body.steps.push(substitute_step(&step, ¶ms, args)); + } + for op in sub.ops { + if body.op_ids.insert(op.id.clone()) { + body.op_effects.insert(op.effect.clone()); + body.ops.push(op); + } + } + body.op_effects.extend(sub.op_effects); + body.rejected.extend(sub.rejected); + body.temps_count = body.temps_count.max(sub.temps_count); + substitute_expr(&result, ¶ms, args) + } + + fn effect_of(&self, file: &str, display: &str) -> String { + self.effects + .get(&(file.to_string(), display.to_string())) + .map(effect_label) + .unwrap_or_else(|| "unknown".into()) + } + + fn param_ty(&self, fun: &Function, name: &str) -> PlanTy { + if let Some(contract) = &fun.contract { + if let Some(param) = contract.params.iter().find(|p| p.name == name) { + return PlanTy::from_contract(¶m.ty); + } + } + PlanTy::Any + } + + fn result_ty(&self, fun: &Function) -> PlanTy { + if let Some(contract) = &fun.contract { + if let Some(ret) = &contract.returns { + return PlanTy::from_contract(&ret.ty); + } + } + PlanTy::Any + } + + // ---------------------------------------------------------------- 纯片段 + + /// 纯表达式降级:能翻译返回 Some;不能返回 None(调用方决定不透明化)。 + fn lower_pure(&self, expr: &Expr, fun: &Function, body: &mut Body) -> Option { + match expr { + Expr::Literal(ast::Literal::None) => Some(PureExpr::None), + Expr::Literal(ast::Literal::Bool(b)) => Some(PureExpr::Bool(*b)), + Expr::Literal(ast::Literal::Int(i)) => Some(PureExpr::Int(*i)), + Expr::Literal(ast::Literal::Num(n)) => Some(PureExpr::Num(*n)), + Expr::Literal(ast::Literal::Text(s)) => Some(PureExpr::Text(s.clone())), + Expr::Var(name) => Some(PureExpr::Var(name.clone())), + Expr::Binary { op, left, right } => Some(PureExpr::Bin { + operator: bin_op(*op), + left: Box::new(self.lower_pure(left, fun, body)?), + right: Box::new(self.lower_pure(right, fun, body)?), + }), + Expr::Unary { op, expr } => Some(PureExpr::Un { + operator: match op { + ast::UnaryOp::Not => UnOp::Not, + ast::UnaryOp::Neg => UnOp::Neg, + }, + expr: Box::new(self.lower_pure(expr, fun, body)?), + }), + Expr::List(items) => Some(PureExpr::List( + items + .iter() + .map(|item| self.lower_pure(item, fun, body)) + .collect::>>()?, + )), + Expr::Map(entries) => Some(PureExpr::Map( + entries + .iter() + .map(|(k, v)| Some((k.clone(), self.lower_pure(v, fun, body)?))) + .collect::>>()?, + )), + Expr::Index { base, label } => { + let key = match label { + ast::IndexKey::Lit(key) => key.clone(), + ast::IndexKey::Var(_) => return None, // 动态键 → 不透明读 + }; + Some(PureExpr::Index { + base: Box::new(self.lower_pure(base, fun, body)?), + key, + }) + } + Expr::Interp(parts) => Some(PureExpr::Interp( + parts + .iter() + .map(|part| match part { + ast::InterpPart::Lit(text) => Some(InterpPart::Lit(text.clone())), + ast::InterpPart::Var(name) => Some(InterpPart::Var(name.clone())), + ast::InterpPart::Index { .. } => None, + }) + .collect::>>()?, + )), + Expr::Call(call) => { + let args: Option> = call + .args + .iter() + .map(|arg| match arg { + Arg::Positional(value) | Arg::Named { value, .. } => { + self.lower_pure(value, fun, body) + } + }) + .collect(); + let args = args?; + match resolve_for_exec(self.module, fun, call) { + Target::Builtin(name) if builtin_is_pure(name) => { + Some(match lower_builtin_pure(name, args) { + IrExpr::Pure(pure) => pure, + _ => return None, + }) + } + Target::Host(host) if host_is_pure(host) => { + Some(match lower_host_pure(host, args) { + IrExpr::Pure(pure) => pure, + _ => return None, + }) + } + _ => None, + } + } + _ => None, + } + } + + /// 分支条件必须是纯表达式(§4.3);不是就报 unsupported。 + fn lower_pure_required(&self, expr: &Expr, fun: &Function, line: u32, body: &mut Body) -> PureExpr { + match self.lower_pure(expr, fun, body) { + Some(pure) => pure, + None => { + body.rejected.push(reject( + self.module, + Span::new(line, 1), + "proof.unsupported", + "分支条件不在纯片段(只接受字面量/变量/比较/布尔)", + )); + PureExpr::None + } + } + } +} + +// ---------------------------------------------------------------- 内建与效应 + +/// 纯内建(可进纯片段)。 +fn builtin_is_pure(name: &str) -> bool { + matches!( + name, + "len" | "str" | "int" | "type" | "trim" | "split" | "join" | "at" + ) +} + +/// `print`/`input` 有效应,按不透明操作处理;其余内建进纯片段。 +fn lower_builtin(name: &str, args: Vec, body: &mut Body) -> IrExpr { + match name { + "print" => { + let id = body.register_op("打印", "output.write", 1); + IrExpr::Op { id, args } + } + "input" => { + let id = body.register_op("输入", "user.input", 1); + IrExpr::Op { id, args } + } + _ => lower_builtin_pure(name, args), + } +} + +fn lower_builtin_pure(name: &str, args: Vec) -> IrExpr { + match (name, args.as_slice()) { + ("len", [only]) => IrExpr::Pure(PureExpr::Len(Box::new(only.clone()))), + ("at", [base, key]) => IrExpr::Pure(PureExpr::Ctor { + name: "mq.at".into(), + args: vec![base.clone(), key.clone()], + }), + _ => IrExpr::Pure(PureExpr::Ctor { + name: format!("mq.{name}"), + args, + }), + } +} + +/// 纯 Host 函数进纯片段;`access`/`取`/`取值` 是字段读取的标准形。 +fn lower_host_pure(host: HostFn, args: Vec) -> IrExpr { + if matches!(host, HostFn::Access) { + if let [base, PureExpr::Text(key)] = args.as_slice() { + return IrExpr::Pure(PureExpr::Access { + base: Box::new(base.clone()), + key: key.clone(), + }); + } + } + IrExpr::Pure(PureExpr::Ctor { + name: format!("mq.{}", host.name()), + args, + }) +} + +fn host_is_pure(host: HostFn) -> bool { + host.effects() == ["pure"] +} + +fn effect_label_of_host(host: HostFn) -> String { + let effects = host.effects(); + if effects == ["pure"] { + "pure".into() + } else { + effects + .first() + .map(|s| (*s).to_string()) + .unwrap_or_else(|| "unknown".into()) + } +} + +/// 无 sema 效应表时的库函数效应回退(与 sema 的 imported_effects 同思路的保守版)。 +fn imported_effect_label(lib: &Module, fun: &Function) -> String { + let mut visiting = std::collections::HashSet::new(); + imported_effect_impl(lib, fun, &mut visiting) +} + +fn imported_effect_impl( + module: &Module, + fun: &Function, + visiting: &mut std::collections::HashSet<(Option, u32)>, +) -> String { + let identity = (module.source.path.clone(), fun.span.line); + if !visiting.insert(identity) { + return "pure".into(); + } + let mut effect = "pure".to_string(); + for stmt in &fun.body { + let calls: Vec<&CallExpr> = match stmt { + Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { + collect_calls(value) + } + Stmt::Call { call, .. } => vec![call], + _ => vec![], + }; + for call in calls { + match resolve_for_exec(module, fun, call) { + Target::Builtin(name) => { + if !builtin_is_pure(name) { + effect = if name == "print" { "output.write" } else { "user.input" }.into(); + } + } + Target::Host(host) => { + let label = effect_label_of_host(host); + if label != "pure" { + effect = label; + } + } + Target::Local(target) => { + let label = imported_effect_impl(module, target, visiting); + if label != "pure" { + effect = label; + } + } + Target::Import { lib: inner, fun: target, .. } => { + let label = imported_effect_impl(inner, target, visiting); + if label != "pure" { + effect = label; + } + } + _ => effect = "unknown".into(), + } + } + } + effect +} + +fn effect_label(effects: &EffectSet) -> String { + if effects.is_pure() { + "pure".into() + } else { + effects + .values() + .into_iter() + .find(|e| e.as_str() != "pure" && e.as_str() != "unknown") + .unwrap_or_else(|| { + if effects.contains("unknown") { + "unknown".into() + } else { + "pure".into() + } + }) + } +} + +fn source_file(module: &Module) -> String { + module + .source + .path + .as_ref() + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default() +} + +fn bin_op(op: BinaryOp) -> BinOp { + use BinaryOp as A; + match op { + A::Add => BinOp::Add, + A::Sub => BinOp::Sub, + A::Mul => BinOp::Mul, + A::Div => BinOp::Div, + A::Eq => BinOp::Eq, + A::Ne => BinOp::Ne, + A::Lt => BinOp::Lt, + A::Le => BinOp::Le, + A::Gt => BinOp::Gt, + A::Ge => BinOp::Ge, + A::And => BinOp::And, + A::Or => BinOp::Or, + } +} + +fn collect_calls(expr: &Expr) -> Vec<&CallExpr> { + let mut out = Vec::new(); + fn go<'a>(expr: &'a Expr, out: &mut Vec<&'a CallExpr>) { + match expr { + Expr::Call(call) => { + out.push(call); + for arg in &call.args { + match arg { + Arg::Positional(value) | Arg::Named { value, .. } => go(value, out), + } + } + } + Expr::Binary { left, right, .. } => { + go(left, out); + go(right, out); + } + Expr::Unary { expr, .. } => go(expr, out), + Expr::List(items) => items.iter().for_each(|e| go(e, out)), + Expr::Map(entries) => entries.iter().for_each(|(_, v)| go(v, out)), + Expr::Index { base, .. } => go(base, out), + Expr::Occluded { payload, .. } => { + if let Some(p) = payload { + go(p, out) + } + } + _ => {} + } + } + go(expr, &mut out); + out +} + +fn has_branching(stmts: &[Stmt]) -> bool { + fn go(stmt: &Stmt) -> bool { + match stmt { + Stmt::Branch { arms, .. } => { + arms.iter().any(|arm| arm.body.iter().any(go)) + } + Stmt::While { body, .. } | Stmt::ForEach { body, .. } => body.iter().any(go), + _ => false, + } + } + stmts.iter().any(go) +} + +fn count_stmts(stmts: &[Stmt]) -> usize { + fn go(stmt: &Stmt) -> usize { + 1 + match stmt { + Stmt::Branch { arms, .. } => arms + .iter() + .map(|arm| arm.body.iter().map(go).sum::()) + .sum(), + _ => 0, + } + } + stmts.iter().map(go).sum() +} + +fn reject(module: &Module, span: Span, code: &str, message: impl Into) -> Diagnostic { + Diagnostic::new(module.source.path.as_deref(), span, message) + .with_source(&module.source) + .with_code(code) + .with_severity(Severity::Warning) +} + +// ---------------------------------------------------------------- 实参替换 + +fn substitute_step(step: &Step, params: &[String], args: &[PureExpr]) -> Step { + match step { + Step::Bind { var, expr, line } => Step::Bind { + var: var.clone(), + expr: substitute_expr(expr, params, args), + line: *line, + }, + Step::Return { expr, line } => Step::Return { + expr: substitute_expr(expr, params, args), + line: *line, + }, + Step::If { + cond, + then, + otherwise, + line, + } => Step::If { + cond: substitute_pure(cond, params, args), + then: then.iter().map(|s| substitute_step(s, params, args)).collect(), + otherwise: otherwise + .iter() + .map(|s| substitute_step(s, params, args)) + .collect(), + line: *line, + }, + Step::Trace { op, args: op_args, line } => Step::Trace { + op: op.clone(), + args: op_args + .iter() + .map(|a| substitute_pure(a, params, args)) + .collect(), + line: *line, + }, + } +} + +fn substitute_expr(expr: &IrExpr, params: &[String], args: &[PureExpr]) -> IrExpr { + match expr { + IrExpr::Pure(pure) => IrExpr::Pure(substitute_pure(pure, params, args)), + IrExpr::Op { id, args: op_args } => IrExpr::Op { + id: id.clone(), + args: op_args + .iter() + .map(|a| substitute_pure(a, params, args)) + .collect(), + }, + other => other.clone(), + } +} + +fn substitute_pure(pure: &PureExpr, params: &[String], args: &[PureExpr]) -> PureExpr { + match pure { + PureExpr::Var(name) => params + .iter() + .position(|p| p == name) + .and_then(|i| args.get(i)) + .cloned() + .unwrap_or_else(|| pure.clone()), + PureExpr::Bin { operator, left, right } => PureExpr::Bin { + operator: *operator, + left: Box::new(substitute_pure(left, params, args)), + right: Box::new(substitute_pure(right, params, args)), + }, + PureExpr::Un { operator, expr } => PureExpr::Un { + operator: *operator, + expr: Box::new(substitute_pure(expr, params, args)), + }, + PureExpr::Index { base, key } => PureExpr::Index { + base: Box::new(substitute_pure(base, params, args)), + key: key.clone(), + }, + PureExpr::Access { base, key } => PureExpr::Access { + base: Box::new(substitute_pure(base, params, args)), + key: key.clone(), + }, + PureExpr::Len(inner) => PureExpr::Len(Box::new(substitute_pure(inner, params, args))), + PureExpr::List(items) => PureExpr::List( + items + .iter() + .map(|i| substitute_pure(i, params, args)) + .collect(), + ), + PureExpr::Map(entries) => PureExpr::Map( + entries + .iter() + .map(|(k, v)| (k.clone(), substitute_pure(v, params, args))) + .collect(), + ), + PureExpr::Ctor { name, args: ctor_args } => PureExpr::Ctor { + name: name.clone(), + args: ctor_args + .iter() + .map(|a| substitute_pure(a, params, args)) + .collect(), + }, + other => other.clone(), + } +} + +// ---------------------------------------------------------------- 降级状态 + +#[derive(Default)] +struct Body { + steps: Vec, + ops: Vec, + op_ids: BTreeSet, + op_effects: BTreeSet, + rejected: Vec, + /// 临时实参变量计数(`实参N`,全局递增防遮蔽)。 + temps_count: usize, + inline_depth: usize, +} + +impl Body { + fn register_op(&mut self, display: &str, effect: impl Into, arity: usize) -> String { + let id = format!("调用:{display}"); + if self.op_ids.insert(id.clone()) { + let effect = effect.into(); + self.op_effects.insert(effect.clone()); + self.ops.push(OpDecl { + id: id.clone(), + effect, + params: Vec::new(), + arity, + }); + } + id + } + + /// 子体降级后并回主状态(ops / 效应 / 拒绝 / 临时变量;steps 由调用方取走)。 + fn absorb(&mut self, sub: Body) { + for op in sub.ops { + if self.op_ids.insert(op.id.clone()) { + self.op_effects.insert(op.effect.clone()); + self.ops.push(op); + } + } + self.op_effects.extend(sub.op_effects); + self.rejected.extend(sub.rejected); + self.temps_count = self.temps_count.max(sub.temps_count); + } +} + +// ---------------------------------------------------------------- 入口 + +/// 从模块生成 Plan(确定性输出;`module_display` 为相对路径)。 +pub fn build_plan( + module: &Module, + source_sha256: &str, + module_display: &str, + effects: BTreeMap<(String, String), EffectSet>, + allow_opaque: &[String], +) -> Result<(Plan, Vec)> { + let lowerer = Lowerer::new(module, effects, false, allow_opaque); + let lowered = lowerer.lower_module(); + let plan = Plan { + schema: SCHEMA, + module: module_display.to_string(), + source_sha256: source_sha256.to_string(), + functions: lowered.iter().filter_map(|l| l.plan.clone()).collect(), + }; + Ok((plan, lowered)) +} + +/// 效应表构建:sema 闭包 artifact → `(file, display) → effects`。 +/// sema 编译失败时返回空表(效应保守记 `unknown`,绝不臆造 pure)。 +pub fn effect_map(path: &Path) -> BTreeMap<(String, String), EffectSet> { + let mut map = BTreeMap::new(); + if let Ok(compilation) = crate::sema::ir::compile_file_closure(path) { + for artifact in &compilation.semantics.artifacts { + map.insert( + (artifact.source.file.clone(), artifact.display_name.clone()), + artifact.effects.clone(), + ); + } + } + map +} diff --git a/src/prove/mod.rs b/src/prove/mod.rs new file mode 100644 index 0000000..2524934 --- /dev/null +++ b/src/prove/mod.rs @@ -0,0 +1,382 @@ +//! `marqdo prove`:SKILL 控制平面 → Lean 4(`doc/design/prove-cli.md`)。 +//! +//! 三条契约(设计 §1.3): +//! 1. **诚实**——只报实际做过的判定;`checked` 永不冒充 Lean 结论; +//! 2. **单调**——离线判定严格弱于 Lean(P2 落地护栏); +//! 3. **不执行**——本模块只读源码,从不运行目标程序。 +//! +//! P0 范围(roadmap/prove.md §2):装载 → 降级 → 定型 → 确定性生成 + audit。 +//! 判定(离线 ⑤ / Lean ⑥)在 P1/P2 接入;状态只到 `unverified` / `rejected` / +//! `error`。 + +pub mod emit; +pub mod ir; +pub mod lower; +pub mod proof_check; +pub mod types; + +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use anyhow::{Context, Result}; + +use crate::diagnostics::Diagnostic; +use crate::prove::lower::Lowered; + +/// 判定层级(P0 恒 `none`)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tier { + Lean, + Offline, + None, +} + +impl Tier { + pub fn as_str(self) -> &'static str { + match self { + Tier::Lean => "lean", + Tier::Offline => "offline", + Tier::None => "none", + } + } +} + +/// 状态词(§1.2;P0 只会产生 `unverified` / `rejected` / `error`)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + Proved, + Checked, + Unverified, + Unproved, + Rejected, + Error, +} + +impl Verdict { + pub fn as_str(self) -> &'static str { + match self { + Verdict::Proved => "proved", + Verdict::Checked => "checked", + Verdict::Unverified => "unverified", + Verdict::Unproved => "unproved", + Verdict::Rejected => "rejected", + Verdict::Error => "error", + } + } + + /// 聚合优先级(差者胜):error > unproved > rejected > unverified > checked > proved。 + pub fn rank(self) -> u8 { + match self { + Verdict::Proved => 0, + Verdict::Checked => 1, + Verdict::Unverified => 2, + Verdict::Rejected => 3, + Verdict::Unproved => 4, + Verdict::Error => 5, + } + } + + pub fn worst(a: Verdict, b: Verdict) -> Verdict { + if a.rank() >= b.rank() { + a + } else { + b + } + } +} + +/// 退出码(§3.3)。 +impl Verdict { + pub fn exit_code(self, require_lean: bool) -> i32 { + match self { + Verdict::Error => 1, + Verdict::Unproved => 1, + Verdict::Rejected | Verdict::Unverified | Verdict::Checked if require_lean => 2, + _ => 0, + } + } +} + +/// 选项(§8.2;P0 生效的子集见字段注释)。 +#[derive(Debug, Clone)] +pub struct ProveOptions { + pub entry: Option, + pub only: Vec, + pub allow_opaque: Vec, + pub emit_dir: Option, + pub strict_types: bool, + pub require_lean: bool, + pub report_only: bool, +} + +impl Default for ProveOptions { + fn default() -> Self { + Self { + entry: None, + only: Vec::new(), + allow_opaque: Vec::new(), + emit_dir: None, + strict_types: true, + require_lean: false, + report_only: false, + } + } +} + +/// 单函数报告。 +#[derive(Debug, Clone)] +pub struct FunctionReport { + pub name: String, + pub verdict: Verdict, + pub tier: Tier, + /// 不透明操作(id, effect)。 + pub ops: Vec<(String, String)>, + /// 拒绝原因(code, message, line)。 + pub rejected: Vec<(String, String, u32)>, + /// 定理声明(id, premise, conclusion, tactic)。 + pub claims: Vec<(String, Option, String, Option)>, +} + +/// 整体报告。 +#[derive(Debug, Clone)] +pub struct Report { + pub file: String, + pub source_sha256: String, + pub status: Verdict, + pub functions: Vec, + pub diagnostics: Vec, + pub emitted: Vec, + pub duration_ms: u128, +} + +impl Report { + /// JSON 面(§3.5;`status` 枚举稳定,`lean` 恒 null 直到 P1)。 + pub fn to_json(&self) -> serde_json::Value { + use serde_json::json; + json!({ + "schema": 1, + "status": self.status.as_str(), + "file": self.file, + "source_sha256": self.source_sha256, + "artifact_id": serde_json::Value::Null, + "functions": self.functions.iter().map(|f| json!({ + "name": f.name, + "status": f.verdict.as_str(), + "tier": f.tier.as_str(), + "claims": f.claims.iter().map(|(id, premise, conclusion, tactic)| json!({ + "id": id, + "premise": premise, + "conclusion": conclusion, + "tactic": tactic, + })).collect::>(), + "obligations": [], + "ops": f.ops.iter().map(|(id, effect)| json!({ + "id": id, "effect": effect, + })).collect::>(), + "rejected": f.rejected.iter().map(|(code, message, line)| json!({ + "code": code, "message": message, "line": line, + })).collect::>(), + })).collect::>(), + "lean": serde_json::Value::Null, + "assumptions": [], + "diagnostics": self.diagnostics.iter().map(|d| d.to_json()).collect::>(), + "emitted": self.emitted.iter().map(|p| p.display().to_string()).collect::>(), + "duration_ms": self.duration_ms as u64, + }) + } + + /// 文本面(§3.4 风格;诊断走 stderr 由 main 负责)。 + pub fn to_text(&self) -> String { + let mut out = String::new(); + let functions = self.functions.len(); + let rejected = self + .functions + .iter() + .filter(|f| f.verdict == Verdict::Rejected) + .count(); + let ops: usize = self.functions.iter().map(|f| f.ops.len()).sum(); + out.push_str(&format!("prove: {}\n", self.file)); + out.push_str(&format!( + " status: {}{}\n", + self.status.as_str(), + if self.status == Verdict::Unverified { + "(P0:仅降级与生成,判定将在 P1 提供)" + } else { + "" + } + )); + out.push_str(&format!( + " functions: {functions} · opaque ops: {ops} · rejected: {rejected}\n" + )); + for f in &self.functions { + if f.verdict == Verdict::Rejected { + let codes: Vec<&str> = f.rejected.iter().map(|(c, _, _)| c.as_str()).collect(); + out.push_str(&format!(" rejected: {} ({})\n", f.name, codes.join(", "))); + } + } + for p in &self.emitted { + out.push_str(&format!(" emitted: {}\n", p.display())); + } + out + } +} + +/// P0 主入口:装载 → 降级 → 定型 → 生成。 +pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result { + let started = Instant::now(); + let module = crate::load::load_module(path) + .with_context(|| format!("装载 {}", path.display()))?; + let source_sha256 = module + .source + .sha256 + .clone() + .unwrap_or_default(); + let file_display = display_path(path); + + // ① 装载完成;② 降级(效应表来自 sema;失败时保守 unknown)。 + let effects = lower::effect_map(path); + let (plan, lowered) = lower::build_plan( + &module, + &source_sha256, + &file_display, + effects, + &opts.allow_opaque, + )?; + + // ③ 定型(分支合流等;错误码 proof.type_mismatch)。 + let mut diagnostics: Vec = Vec::new(); + diagnostics.extend(types::typecheck_plan(&module, &lowered, opts.strict_types)); + + // ④ 生成(--report-only 时跳过写盘)。 + let mut emitted: Vec = Vec::new(); + if !opts.report_only { + let dir = match &opts.emit_dir { + Some(dir) => dir.clone(), + None => default_emit_dir(&source_sha256), + }; + let generated = dir.join("Generated"); + std::fs::create_dir_all(&generated) + .with_context(|| format!("创建 {}", generated.display()))?; + let (file_name, lean) = emit::emit_module(&plan, &emit::stem_of(&file_display)); + let lean_path = generated.join(&file_name); + std::fs::write(&lean_path, &lean) + .with_context(|| format!("写入 {}", lean_path.display()))?; + let plan_path = dir.join("plan.json"); + std::fs::write(&plan_path, plan.to_stable_json()) + .with_context(|| format!("写入 {}", plan_path.display()))?; + emitted.push(relative_cwd(&lean_path)); + emitted.push(relative_cwd(&plan_path)); + } + + // 汇总:错误诊断 → error;有拒绝函数 → rejected;否则 unverified。 + let has_type_errors = diagnostics + .iter() + .any(|d| matches!(d.severity, crate::diagnostics::Severity::Error)); + let functions = summarize(&lowered, &opts.only); + let mut status = Verdict::Unverified; + if !functions.is_empty() { + status = functions + .iter() + .map(|f| f.verdict) + .fold(Verdict::Proved, Verdict::worst); + } + if has_type_errors { + status = Verdict::Error; + } + + Ok(Report { + file: file_display, + source_sha256, + status, + functions, + diagnostics, + emitted, + duration_ms: started.elapsed().as_millis(), + }) +} + +fn summarize(lowered: &[Lowered], only: &[String]) -> Vec { + lowered + .iter() + .filter(|l| !l.is_object) + .filter(|l| only.is_empty() || only.iter().any(|name| name == &l.display)) + .map(|l| { + let (verdict, tier, ops, rejected, claims) = match &l.plan { + Some(plan) => ( + Verdict::Unverified, + Tier::None, + plan.ops + .iter() + .map(|op| (op.id.clone(), op.effect.clone())) + .collect(), + Vec::new(), + plan.claims + .iter() + .map(|c| { + ( + c.id.clone(), + c.premise.clone(), + c.conclusion.clone(), + c.tactic.clone(), + ) + }) + .collect(), + ), + None => ( + Verdict::Rejected, + Tier::None, + Vec::new(), + l.rejected + .iter() + .map(|d| { + ( + d.code.clone(), + d.message.clone(), + d.span.line, + ) + }) + .collect(), + Vec::new(), + ), + }; + FunctionReport { + name: l.display.clone(), + verdict, + tier, + ops, + rejected, + claims, + } + }) + .collect() +} + +/// 默认产物目录:`.marqdo/prove//`(key = 源 sha256 前 8 位)。 +pub fn default_emit_dir(source_sha256: &str) -> PathBuf { + PathBuf::from(".marqdo/prove").join(&source_sha256[..source_sha256.len().min(8)]) +} + +/// `prove clean`:删除 `.marqdo/prove`(--emit 指定目录不动)。 +pub fn clean() -> Result { + let root = Path::new(".marqdo/prove"); + if !root.exists() { + return Ok(0); + } + let count = std::fs::read_dir(root)?.count(); + std::fs::remove_dir_all(root) + .with_context(|| format!("删除 {}", root.display()))?; + Ok(count) +} + +fn display_path(path: &Path) -> String { + let cwd = std::env::current_dir().unwrap_or_default(); + path.strip_prefix(&cwd) + .unwrap_or(path) + .to_string_lossy() + .to_string() +} + +fn relative_cwd(path: &Path) -> PathBuf { + let cwd = std::env::current_dir().unwrap_or_default(); + path.strip_prefix(&cwd).unwrap_or(path).to_path_buf() +} diff --git a/src/prove/proof_check.rs b/src/prove/proof_check.rs new file mode 100644 index 0000000..2b43802 --- /dev/null +++ b/src/prove/proof_check.rs @@ -0,0 +1,842 @@ +//! `check --proof`:定理表的静态校验(设计 §7;默认关)。 +//! +//! 校验项(全部 advisory 之外都是 Error 级诊断): +//! - `proof.claim_malformed` 表头命中定理词表但列形不齐 +//! - `proof.claim_ambiguous` 同时有 `类型` 与 `结论` 列 +//! - `proof.claim_misplaced` 合法定理表出现在首条可执行语句之后 +//! - `proof.claim_duplicate` 同一函数内定理 id 重复 +//! - `proof.claim_unknown_symbol` 结论/前提引用了受限符号集之外的名字 +//! - `proof.claim_unsupported` 谓词超出封闭集合(包含/长度/下标)或元数不对 +//! - `proof.name_shadow` 保留名(`结果`/`轨迹`)被形参/局部变量遮蔽 + +use std::path::Path; + +use crate::ast::{Expr, Function, Module, Stmt}; +use crate::contract; +use crate::diagnostics::{Diagnostic, Severity, Span}; + +/// 定理作用域保留名(§7.3.4)。 +pub const RESERVED_CLAIM_NAMES: &[&str] = &["结果", "轨迹"]; + +/// 谓词封闭集合(§7.3.5:改集合需重新评审 ADR)。 +pub const PREDICATES: &[(&str, usize)] = &[("包含", 2), ("长度", 1), ("下标", 2)]; + +/// 入口:对整个模块做定理表校验。 +pub fn check_proofs(module: &Module, path: Option<&Path>) -> Vec { + let mut out = Vec::new(); + let mut function_names: Vec = Vec::new(); + collect_function_names(module, &mut function_names); + let has_claims = module_has_claims(module); + walk_checks( + module, + &module.functions, + path, + &function_names, + has_claims, + &mut out, + ); + for (_, child) in module.import_modules.iter() { + out.extend(check_proofs_imported(child, path)); + } + out +} + +fn check_proofs_imported(module: &Module, path: Option<&Path>) -> Vec { + // import 的库文件自带定理表也按同规则校验(诊断指向本文件行号即可)。 + let mut out = Vec::new(); + let mut function_names: Vec = Vec::new(); + collect_function_names(module, &mut function_names); + let has_claims = module_has_claims(module); + walk_checks( + module, + &module.functions, + path, + &function_names, + has_claims, + &mut out, + ); + out +} + +fn collect_function_names(module: &Module, out: &mut Vec) { + fn go(funs: &[Function], out: &mut Vec) { + for f in funs { + out.push(f.name.clone()); + go(&f.children, out); + } + } + go(&module.functions, out); + for child in module.import_modules.values() { + collect_function_names(child, out); + } +} + +fn module_has_claims(module: &Module) -> bool { + fn go(funs: &[Function]) -> bool { + funs.iter() + .any(|f| !f.claims.is_empty() || go(&f.children)) + } + go(&module.functions) + || module + .import_modules + .values() + .any(|m| module_has_claims(m)) +} + +fn walk_checks( + module: &Module, + funs: &[Function], + path: Option<&Path>, + function_names: &[String], + has_claims: bool, + out: &mut Vec, +) { + for fun in funs { + check_claim_duplicates(module, fun, path, out); + check_name_shadow(module, fun, function_names, has_claims, path, out); + check_misplaced_and_malformed(module, fun, path, out); + check_claim_symbols(module, fun, path, out); + walk_checks(module, &fun.children, path, function_names, has_claims, out); + } +} + +fn proof_diag( + module: &Module, + path: Option<&Path>, + span: Span, + code: &str, + message: String, + suggestion: String, +) -> Diagnostic { + let _ = module; + Diagnostic::new(path, span, message) + .with_code(code) + .with_severity(Severity::Error) + .with_suggestion(suggestion) +} + +/// 同一函数内定理 id 重复(§7.1 规则 3)。 +fn check_claim_duplicates(module: &Module, fun: &Function, path: Option<&Path>, out: &mut Vec) { + let mut seen: Vec<&str> = Vec::new(); + for claim in &fun.claims { + if seen.contains(&claim.id.as_str()) { + out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_duplicate", + format!("定理 `{}` 在 `{}` 内重复声明", claim.id, fun.name), + "定理 id 在函数内必须唯一;重命名或删除重复行".into(), + )); + } else { + seen.push(&claim.id); + } + } +} + +/// 遮蔽检查(§7.3.4):保留名 `结果`/`轨迹` 不得被形参占用; +/// 谓词名 `包含/长度/下标` 不得与用户函数同名(有定理表时才有意义)。 +fn check_name_shadow( + module: &Module, + fun: &Function, + function_names: &[String], + has_claims: bool, + path: Option<&Path>, + out: &mut Vec, +) { + if fun.claims.is_empty() && !has_claims { + return; + } + for param in &fun.params { + if RESERVED_CLAIM_NAMES.contains(¶m.name.as_str()) { + out.push(proof_diag( + module, + path, + param.span, + "proof.name_shadow", + format!( + "形参 `{}` 与定理作用域保留名冲突(`{}` 也要声明定理)", + param.name, + fun.name + ), + format!("把形参 `{}` 改名;`结果`/`轨迹` 在定理里指返回值与操作轨迹", param.name), + )); + } + } + for pred in PREDICATES { + if function_names.iter().any(|n| n == pred.0) { + out.push(proof_diag( + module, + path, + fun.span, + "proof.name_shadow", + format!( + "函数名 `{}` 与定理谓词 `{}` 同名(谓词集合封闭:包含/长度/下标)", + fun.name, pred.0 + ), + format!("把函数 `{}` 改名,避免定理表里的 `{}` 歧义", fun.name, pred.0), + )); + } + } +} + +/// 错位与畸形:body 里仍是定理形的表(默认关时解析器不提取它们)。 +fn check_misplaced_and_malformed( + module: &Module, + fun: &Function, + path: Option<&Path>, + out: &mut Vec, +) { + let mut prefix_zone = true; + for stmt in &fun.body { + let (pairs, span) = match stmt { + Stmt::Expr { + value: Expr::Map(pairs), + span, + } => (pairs, *span), + Stmt::Expr { value: Expr::List(_), .. } => continue, + _ => { + prefix_zone = false; + continue; + } + }; + match contract::parse_claim_table(pairs, span.line) { + Some(Ok(_rows)) => { + // 合法定理形却还在 body:一定是位置不对(prefix zone 内会被提取)。 + out.push(proof_diag( + module, + path, + span, + "proof.claim_misplaced", + format!( + "`{}` 的定理表出现在首条可执行语句之后——它是普通表,不会成为定理", + fun.name + ), + "把定理表移到函数体开头(与契约表同一槽位)".into(), + )); + } + Some(Err(err)) => { + out.push(proof_diag( + module, + path, + span, + err.code, + err.message, + "对照定理表形状:| 定理 | 结论 | 前提 | 策略 |(前提/策略可省)".into(), + )); + } + None => {} + } + let _ = prefix_zone; + } +} + +/// 受限符号集校验(§7.1 规则 4):前提只看形参;结论可加 `结果`/`轨迹`。 +fn check_claim_symbols(module: &Module, fun: &Function, path: Option<&Path>, out: &mut Vec) { + if fun.claims.is_empty() { + return; + } + let params: Vec = fun.params.iter().map(|p| p.name.clone()).collect(); + for claim in &fun.claims { + if let Some(tactic) = &claim.tactic { + if tactic != "auto" && tactic != "none" { + out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_malformed", + format!("定理 `{}` 的策略 `{}` 不在 auto/none 内", claim.id, tactic), + "策略列只接受 auto(自动)或 none(永远 unverified)".into(), + )); + } + } + if let Some(premise) = &claim.premise { + check_claim_expr( + module, + path, + premise, + claim, + ¶ms, + false, + out, + ); + } + check_claim_expr(module, path, &claim.conclusion, claim, ¶ms, true, out); + } +} + +fn check_claim_expr( + module: &Module, + path: Option<&Path>, + text: &str, + claim: &crate::ast::Claim, + params: &[String], + conclusion_scope: bool, + out: &mut Vec, +) { + let tokens = match tokenize_claim(text) { + Ok(t) => t, + Err(msg) => { + out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_malformed", + format!("定理 `{}` 的表达无法解析:{msg}", claim.id), + "受限表达式:名字、数字、字符串、比较/算术/布尔、包含(轨迹,x)/长度(轨迹)/下标(轨迹,i)".into(), + )); + return; + } + }; + match parse_claim_expr(&tokens) { + Ok((_, ast)) => collect_symbols( + module, + path, + claim, + &ast, + params, + conclusion_scope, + out, + ), + Err(msg) => { + out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_malformed", + format!("定理 `{}` 的表达无法解析:{msg}", claim.id), + "受限表达式:名字、数字、字符串、比较/算术/布尔、包含(轨迹,x)/长度(轨迹)/下标(轨迹,i)".into(), + )); + } + } +} + +// ---------------------------------------------------------------- 受限表达式 + +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum CTok { + Name(String), + Int(i64), + Num(f64), + Text(String), + Bool(bool), + Op(&'static str), + LParen, + RParen, + Comma, + Dot, +} + +/// 词法:把受限表达文本切成记号(emit 与 check 共用)。 +pub(crate) fn tokenize_claim(text: &str) -> Result, String> { + let mut out = Vec::new(); + let chars: Vec = text.chars().collect(); + let mut i = 0usize; + while i < chars.len() { + let c = chars[i]; + if c.is_whitespace() { + i += 1; + continue; + } + match c { + '(' => out.push(CTok::LParen), + ')' => out.push(CTok::RParen), + ',' | ',' => out.push(CTok::Comma), + '.' | '。' => out.push(CTok::Dot), + '"' | '“' | '”' => { + // 字符串字面量(到下一个同类引号)。 + let close = c; + let mut j = i + 1; + let mut s = String::new(); + while j < chars.len() && chars[j] != close { + s.push(chars[j]); + j += 1; + } + if j >= chars.len() { + return Err("字符串没有闭合引号".into()); + } + out.push(CTok::Text(s)); + i = j; + } + '`' => { + // `` `名字` `` → 名字。 + let mut j = i + 1; + let mut s = String::new(); + while j < chars.len() && chars[j] != '`' { + s.push(chars[j]); + j += 1; + } + if j >= chars.len() { + return Err("反引号名没有闭合".into()); + } + out.push(CTok::Name(s)); + i = j; + } + '0'..='9' => { + let mut j = i; + let mut s = String::new(); + let mut dotted = false; + while j < chars.len() && (chars[j].is_ascii_digit() || chars[j] == '.') { + if chars[j] == '.' { + if dotted { + break; + } + dotted = true; + } + s.push(chars[j]); + j += 1; + } + if dotted { + out.push(CTok::Num(s.parse::().map_err(|_| "数字解析失败")?)); + } else { + out.push(CTok::Int(s.parse::().map_err(|_| "整数解析失败")?)); + } + i = j - 1; + } + '=' => out.push(CTok::Op("=")), + '≠' | '!' => out.push(CTok::Op("≠")), + '<' => out.push(CTok::Op("<")), + '≤' => out.push(CTok::Op("≤")), + '>' => out.push(CTok::Op(">")), + '≥' => out.push(CTok::Op("≥")), + '+' => out.push(CTok::Op("+")), + '-' | '−' => out.push(CTok::Op("-")), + '*' | '×' => out.push(CTok::Op("*")), + '/' | '÷' => out.push(CTok::Op("/")), + _ => { + // 名字 / 中文词 / 关键字。 + if c.is_alphanumeric() || c == '_' { + let mut j = i; + let mut s = String::new(); + while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_' || chars[j] == '.') { + s.push(chars[j]); + j += 1; + } + i = j - 1; + match s.as_str() { + "且" | "and" => out.push(CTok::Op("且")), + "或" | "or" => out.push(CTok::Op("或")), + "非" | "not" => out.push(CTok::Op("非")), + "真" | "true" | "True" => out.push(CTok::Bool(true)), + "假" | "false" | "False" => out.push(CTok::Bool(false)), + _ => { + // `名字.字段` 已并入 s(含点)。 + out.push(CTok::Name(s)); + } + } + } else { + return Err(format!("无法识别的字符 `{c}`")); + } + } + } + i += 1; + } + Ok(out) +} + +#[derive(Debug, Clone)] +#[allow(dead_code)] // op/字面值记号保留:P1 语义求值与 Lean 脚本生成要用。 +pub(crate) enum ClaimAst { + Lit(CTok), + /// 名字(可含 `.字段`;已合并进字符串)。 + Var(String), + Call { name: String, args: Vec }, + Bin { op: &'static str, left: Box, right: Box }, + Un { op: &'static str, expr: Box }, +} + +struct P<'a> { + toks: &'a [CTok], + pos: usize, +} + +impl<'a> P<'a> { + fn peek(&self) -> Option<&CTok> { + self.toks.get(self.pos) + } + fn next(&mut self) -> Option { + let t = self.toks.get(self.pos).cloned(); + if t.is_some() { + self.pos += 1; + } + t + } + fn eat_op(&mut self, ops: &[&str]) -> Option<&'static str> { + let CTok::Op(o) = self.peek()? else { + return None; + }; + if !ops.contains(o) { + return None; + } + let hit: &'static str = match *o { + "+" => "+", + "-" => "-", + "*" => "*", + "/" => "/", + "=" => "=", + "≠" => "≠", + "<" => "<", + "≤" => "≤", + ">" => ">", + "≥" => "≥", + "且" => "且", + "或" => "或", + "非" => "非", + _ => return None, + }; + self.pos += 1; + Some(hit) + } +} + +pub(crate) fn parse_claim_expr(toks: &[CTok]) -> Result<(Vec, ClaimAst), String> { + let mut p = P { toks, pos: 0 }; + let ast = parse_or(&mut p)?; + if p.pos != toks.len() { + return Err(format!("表达式末尾有多余内容(第 {} 个记号起)", p.pos + 1)); + } + Ok((toks.to_vec(), ast)) +} + +fn parse_or(p: &mut P) -> Result { + let mut left = parse_and(p)?; + while let Some(op) = p.eat_op(&["或"]) { + let right = parse_and(p)?; + left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; + } + Ok(left) +} + +fn parse_and(p: &mut P) -> Result { + let mut left = parse_cmp(p)?; + while let Some(op) = p.eat_op(&["且"]) { + let right = parse_cmp(p)?; + left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; + } + Ok(left) +} + +fn parse_cmp(p: &mut P) -> Result { + let left = parse_add(p)?; + if let Some(op) = p.eat_op(&["=", "≠", "<", "≤", ">", "≥"]) { + let right = parse_add(p)?; + return Ok(ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }); + } + Ok(left) +} + +fn parse_add(p: &mut P) -> Result { + let mut left = parse_mul(p)?; + while let Some(op) = p.eat_op(&["+", "-"]) { + let right = parse_mul(p)?; + left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; + } + Ok(left) +} + +fn parse_mul(p: &mut P) -> Result { + let mut left = parse_unary(p)?; + while let Some(op) = p.eat_op(&["*", "/"]) { + let right = parse_unary(p)?; + left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; + } + Ok(left) +} + +fn parse_unary(p: &mut P) -> Result { + if let Some(op) = p.eat_op(&["非"]) { + let expr = parse_unary(p)?; + return Ok(ClaimAst::Un { op, expr: Box::new(expr) }); + } + if let Some(CTok::Op("-")) = p.peek() { + p.pos += 1; + let expr = parse_unary(p)?; + return Ok(ClaimAst::Un { op: "-", expr: Box::new(expr) }); + } + parse_atom(p) +} + +fn parse_atom(p: &mut P) -> Result { + match p.next() { + Some(CTok::LParen) => { + let e = parse_or(p)?; + match p.next() { + Some(CTok::RParen) => Ok(e), + _ => Err("缺少右括号".into()), + } + } + Some(t @ (CTok::Int(_) | CTok::Num(_) | CTok::Text(_) | CTok::Bool(_))) => Ok(ClaimAst::Lit(t)), + Some(CTok::Name(name)) => { + // 谓词调用:名字后紧跟 `(`。 + if matches!(p.peek(), Some(CTok::LParen)) { + p.pos += 1; + let mut args = Vec::new(); + if !matches!(p.peek(), Some(CTok::RParen)) { + loop { + args.push(parse_or(p)?); + match p.next() { + Some(CTok::Comma) => continue, + Some(CTok::RParen) => break, + _ => return Err("调用参数列表未闭合".into()), + } + } + } else { + p.pos += 1; + } + return Ok(ClaimAst::Call { name, args }); + } + Ok(ClaimAst::Var(name)) + } + other => Err(format!("这里应该是一个名字或值,得到 {other:?}")), + } +} + +/// 收集受限符号并校验(§7.1 规则 4 + §7.3.5 谓词封闭)。 +fn collect_symbols( + module: &Module, + path: Option<&Path>, + claim: &crate::ast::Claim, + ast: &ClaimAst, + params: &[String], + conclusion_scope: bool, + out: &mut Vec, +) { + match ast { + ClaimAst::Lit(_) => {} + ClaimAst::Var(name) => { + // 名字可带 `.字段`(结果.ok / 回执.value)——只校验根名字。 + let root = name.split('.').next().unwrap_or(name); + let known = params.contains(&root.to_string()) + || (conclusion_scope && RESERVED_CLAIM_NAMES.contains(&root)); + if !known { + let suggestion = crate::check::suggest_closest(root, params); + let mut d = proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_unknown_symbol", + format!( + "定理 `{}` 引用了未知名字 `{root}`({}作用域只允许{})", + claim.id, + if conclusion_scope { "结论" } else { "前提" }, + if conclusion_scope { + "形参、结果、轨迹" + } else { + "形参" + } + ), + suggestion + .map(|s| format!("是不是想写 `{s}`?")) + .unwrap_or_else(|| { + if conclusion_scope { + "只引用形参与 `结果`/`轨迹`".into() + } else { + "前提里只引用形参(入口状态求值)".into() + } + }), + ); + d = d.with_severity(Severity::Error); + out.push(d); + } + } + ClaimAst::Call { name, args } => { + match PREDICATES.iter().find(|(n, _)| n == name) { + Some((_, arity)) if *arity == args.len() => {} + Some((_, arity)) => out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_unsupported", + format!( + "谓词 `{name}` 需要 {arity} 个参数,定理 `{}` 给了 {} 个", + claim.id, + args.len() + ), + "谓词集合封闭:包含(轨迹,x) / 长度(轨迹) / 下标(轨迹,i)".into(), + )), + None => out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_unsupported", + format!( + "定理 `{}` 调用了 `{name}`——定理里只能用包含/长度/下标三个谓词", + claim.id + ), + "谓词集合封闭(§7.3.5);要扩集合先改 ADR 0010".into(), + )), + } + for arg in args { + collect_symbols(module, path, claim, arg, params, conclusion_scope, out); + } + } + ClaimAst::Bin { left, right, .. } => { + collect_symbols(module, path, claim, left, params, conclusion_scope, out); + collect_symbols(module, path, claim, right, params, conclusion_scope, out); + } + ClaimAst::Un { expr, .. } => { + collect_symbols(module, path, claim, expr, params, conclusion_scope, out); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse_ok(text: &str) -> ClaimAst { + let toks = tokenize_claim(text).expect("tokenize"); + parse_claim_expr(&toks).expect("parse").1 + } + + #[test] + fn restricted_grammar_parses_design_examples() { + // 设计 §7.1 的示例句全部可解析。 + let _ = parse_ok("包含(轨迹, \"人工审核\")"); + let _ = parse_ok("金额 > 10000"); + let _ = parse_ok("结果.ok = True"); + let _ = parse_ok("长度(轨迹) = 2"); + let _ = parse_ok("下标(轨迹, 0) = \"x\""); + let _ = parse_ok("非 结果.ok = False 且 金额 ≥ 0"); + let _ = parse_ok("金额 + 1 ≤ 10 或 假"); + } + + #[test] + fn tokenizer_rejects_unterminated_strings() { + assert!(tokenize_claim("包含(轨迹, \"未闭合").is_err()); + } + + #[test] + fn reserved_outputs_render_without_field_access_prefix() { + // emit 侧翻译:结果/轨迹 是定理作用域绑定名,不加 v_ 前缀。 + let ast = parse_ok("轨迹"); + assert!(matches!(ast, ClaimAst::Var(ref n) if n == "轨迹")); + let ast = parse_ok("结果.ok"); + assert!(matches!(ast, ClaimAst::Var(ref n) if n == "结果.ok")); + } + + #[test] + fn symbol_check_reports_unknown_and_suggests() { + let module = Module::default(); + let claim = crate::ast::Claim { + id: "引用未知".into(), + conclusion: "额度 > 0".into(), + premise: None, + tactic: Some("auto".into()), + line: 3, + }; + let mut out = Vec::new(); + check_claim_expr( + &module, + None, + "额度 > 0", + &claim, + &["金额".to_string()], + true, + &mut out, + ); + assert_eq!(out.len(), 1); + assert_eq!(out[0].code, "proof.claim_unknown_symbol"); + // 最近建议(编辑距离):额度 → 金额 不够近,无建议也要有消息。 + assert!(out[0].message.contains("额度")); + } + + #[test] + fn symbol_check_accepts_params_in_premise_and_outputs_in_conclusion() { + let module = Module::default(); + let claim = crate::ast::Claim { + id: "合法".into(), + conclusion: "结果.ok = True".into(), + premise: Some("金额 > 0".into()), + tactic: None, + line: 1, + }; + let mut out = Vec::new(); + check_claim_expr( + &module, + None, + "金额 > 0", + &claim, + &["金额".to_string()], + false, + &mut out, + ); + check_claim_expr( + &module, + None, + "结果.ok = True", + &claim, + &["金额".to_string()], + true, + &mut out, + ); + assert!(out.is_empty(), "{out:?}"); + } + + #[test] + fn premise_may_not_reference_outputs() { + let module = Module::default(); + let claim = crate::ast::Claim { + id: "前提越界".into(), + conclusion: "结果.ok = True".into(), + premise: Some("轨迹 = 0".into()), + tactic: None, + line: 1, + }; + let mut out = Vec::new(); + check_claim_expr( + &module, + None, + "轨迹 = 0", + &claim, + &[], + false, + &mut out, + ); + assert!(out + .iter() + .any(|d| d.code == "proof.claim_unknown_symbol"), "{out:?}"); + } + + #[test] + fn predicate_arity_and_closure_are_enforced() { + let module = Module::default(); + let claim = crate::ast::Claim { + id: "元数错".into(), + conclusion: "包含(轨迹, \"a\", \"b\")".into(), + premise: None, + tactic: None, + line: 1, + }; + let mut out = Vec::new(); + check_claim_expr( + &module, + None, + "包含(轨迹, \"a\", \"b\")", + &claim, + &[], + true, + &mut out, + ); + assert!(out.iter().any(|d| d.code == "proof.claim_unsupported"), "{out:?}"); + + let claim2 = crate::ast::Claim { + id: "越界谓词".into(), + conclusion: "求和(金额, 1) > 0".into(), + premise: None, + tactic: None, + line: 2, + }; + let mut out2 = Vec::new(); + check_claim_expr( + &module, + None, + "求和(金额, 1) > 0", + &claim2, + &["金额".to_string()], + true, + &mut out2, + ); + assert!(out2.iter().any(|d| d.code == "proof.claim_unsupported"), "{out2:?}"); + } +} diff --git a/src/prove/types.rs b/src/prove/types.rs new file mode 100644 index 0000000..0b4b43b --- /dev/null +++ b/src/prove/types.rs @@ -0,0 +1,251 @@ +//! 定型(`doc/design/prove-cli.md` §4.1 ③):契约表驱动的轻量推断。 +//! +//! P0 范围:参数/返回类型来自契约表;字面量赋值给最具体类型;分支合流时 +//! 同名变量类型不相容报 `proof.type_mismatch`(带两处行号)。其余一律 +//! `Any`(`--no-strict-types` 语义下的诚实回退,不做猜测)。 + +use std::collections::BTreeMap; + +use crate::diagnostics::{Diagnostic, Severity, Span}; +use crate::prove::ir::{PlanTy, PureExpr, Step}; + +/// 单函数类型检查产物。 +#[derive(Debug, Default)] +pub struct Typed { + pub diagnostics: Vec, +} + +/// 对一个函数的 steps 做类型检查。 +/// +/// `params`:形参类型(契约表)。返回收集到的诊断。 +pub fn typecheck( + module: &crate::ast::Module, + params: &[(String, PlanTy)], + steps: &[Step], + strict: bool, +) -> Typed { + let mut env: BTreeMap = params + .iter() + .map(|(name, ty)| (name.clone(), (ty.clone(), 0))) + .collect(); + let mut diagnostics = Vec::new(); + check_steps(module, steps, &mut env, &mut diagnostics, strict); + Typed { diagnostics } +} + +fn check_steps( + module: &crate::ast::Module, + steps: &[Step], + env: &mut BTreeMap, + out: &mut Vec, + strict: bool, +) { + for step in steps { + match step { + Step::Bind { var, expr, line } => { + let ty = expr_type(expr, env); + match ty { + Some(new_ty) => { + if let Some((old_ty, old_line)) = env.get(var) { + let merged = conflate(old_ty, &new_ty); + if merged.is_none() { + out.push(mismatch( + module, + Span::new(*line, 1), + *old_line, + var, + old_ty, + &new_ty, + )); + } + let merged = merged.unwrap_or(PlanTy::Any); + if strict && merged == PlanTy::Any && new_ty != PlanTy::Any { + // 严格模式下落 Any 的合流仍允许,但记录在案。 + } + env.insert(var.clone(), (merged, *line)); + } else { + env.insert(var.clone(), (new_ty, *line)); + } + } + None => { + // 未知类型:保留旧类型(若有),否则 Any。 + env.entry(var.clone()).or_insert((PlanTy::Any, *line)); + } + } + } + Step::Return { expr, .. } => { + let _ = expr_type(expr, env); + } + Step::If { + then, + otherwise, + line, + .. + } => { + // 分支合流:两臂各自检查后合并同名变量类型。 + let mut then_env = env.clone(); + let mut else_env = env.clone(); + check_steps(module, then, &mut then_env, out, strict); + check_steps(module, otherwise, &mut else_env, out, strict); + let then_vars: Vec<(String, (PlanTy, u32))> = + then_env.iter().map(|(k, v)| (k.clone(), v.clone())).collect(); + for (name, (then_ty, then_line)) in then_vars { + if name.starts_with("实参") { + continue; + } + match else_env.get(&name) { + Some((else_ty, else_line)) => { + match conflate(&then_ty, else_ty) { + Some(merged) => { + env.insert(name, (merged, *line)); + } + None => { + out.push(mismatch( + module, + Span::new(then_line.max(1), 1), + *else_line, + &name, + &then_ty, + else_ty, + )); + env.insert(name, (PlanTy::Any, *line)); + } + } + } + None => { + env.insert(name, (then_ty, then_line)); + } + } + } + // 只在 else 出现的变量也进入合流后的环境。 + for (name, (else_ty, _)) in &else_env { + then_env.entry(name.clone()).or_insert((else_ty.clone(), 0)); + } + } + Step::Trace { .. } => {} + } + } +} + +/// 纯表达式的保守类型:只认字面量/构造器/列表/映射/len/access/插值。 +fn expr_type(expr: &crate::prove::ir::Expr, env: &BTreeMap) -> Option { + match expr { + crate::prove::ir::Expr::Pure(pure) => pure_type(pure, env), + crate::prove::ir::Expr::Op { .. } => None, + crate::prove::ir::Expr::Formula | crate::prove::ir::Expr::Code => None, + } +} + +fn pure_type(pure: &PureExpr, env: &BTreeMap) -> Option { + match pure { + PureExpr::Int(_) => Some(PlanTy::Int), + PureExpr::Num(_) => Some(PlanTy::Num), + PureExpr::Bool(_) => Some(PlanTy::Bool), + PureExpr::Text(_) => Some(PlanTy::Text), + PureExpr::None => Some(PlanTy::Any), + PureExpr::Var(name) => env.get(name).map(|(ty, _)| ty.clone()), + PureExpr::Bin { operator: op, left, right } => { + use crate::prove::ir::BinOp as B; + let lt = pure_type(left, env); + let rt = pure_type(right, env); + match op { + B::Add | B::Sub | B::Mul | B::Div => { + let lt = lt?; + let rt = rt?; + match (<, &rt) { + (PlanTy::Text, _) | (_, PlanTy::Text) => Some(PlanTy::Text), + (PlanTy::Num, _) | (_, PlanTy::Num) => Some(PlanTy::Num), + (PlanTy::Int, PlanTy::Int) => Some(PlanTy::Int), + _ => None, + } + } + B::Eq | B::Ne | B::Lt | B::Le | B::Gt | B::Ge | B::And | B::Or => Some(PlanTy::Bool), + } + } + PureExpr::Un { operator: op, expr } => match op { + crate::prove::ir::UnOp::Not => Some(PlanTy::Bool), + crate::prove::ir::UnOp::Neg => pure_type(expr, env), + }, + PureExpr::Index { base, .. } => match pure_type(base, env)? { + PlanTy::Map => Some(PlanTy::Any), + PlanTy::List => Some(PlanTy::Any), + PlanTy::Result => Some(PlanTy::Any), + _ => Some(PlanTy::Any), + }, + PureExpr::Access { base, .. } => match pure_type(base, env)? { + PlanTy::Result => Some(PlanTy::Any), + _ => Some(PlanTy::Any), + }, + PureExpr::Len(_) => Some(PlanTy::Int), + PureExpr::Interp(_) => Some(PlanTy::Text), + PureExpr::List(_) => Some(PlanTy::List), + PureExpr::Map(_) => Some(PlanTy::Map), + PureExpr::Ctor { name, .. } => { + if name.starts_with("result.") { + Some(PlanTy::Result) + } else { + None + } + } + } +} + +/// 类型合流:相同 → 相同;Int+Num → Num;含 Any → Any;否则 None(冲突)。 +fn conflate(a: &PlanTy, b: &PlanTy) -> Option { + use PlanTy as T; + if a == b { + return Some(a.clone()); + } + match (a, b) { + (T::Any, other) | (other, T::Any) => Some(other.clone()), + (T::Int, T::Num) | (T::Num, T::Int) => Some(T::Num), + _ => None, + } +} + +fn mismatch( + module: &crate::ast::Module, + span: Span, + other_line: u32, + var: &str, + old: &PlanTy, + new: &PlanTy, +) -> Diagnostic { + Diagnostic::new( + module.source.path.as_deref(), + span, + format!( + "`{var}` 在分支合流处类型不相容:{a} vs {b}", + a = old.name(), + b = new.name() + ), + ) + .with_source(&module.source) + .with_code("proof.type_mismatch") + .with_severity(Severity::Error) + .with_suggestion(format!( + "另一处绑定在第 {other_line} 行;统一两臂的类型或改用 --no-strict-types" + )) +} + +/// 把类型检查接到降级产物上(mod.rs 调用)。 +pub fn typecheck_plan( + module: &crate::ast::Module, + lowered: &[crate::prove::lower::Lowered], + strict: bool, +) -> Vec { + let mut out = Vec::new(); + for item in lowered { + let Some(plan) = &item.plan else { + continue; + }; + let params: Vec<(String, PlanTy)> = plan + .params + .iter() + .map(|p| (p.name.clone(), p.ty.clone())) + .collect(); + let typed = typecheck(module, ¶ms, &plan.steps, strict); + out.extend(typed.diagnostics); + } + out +} diff --git a/src/source_map_tests.rs b/src/source_map_tests.rs index 67d52a9..252f634 100644 --- a/src/source_map_tests.rs +++ b/src/source_map_tests.rs @@ -19,8 +19,12 @@ fn line(text: &str, marker: &str) -> u32 { + 1 } fn root(label: &str) -> PathBuf { - let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("target/source-map") + // Scratch belongs to the build target dir; honor CARGO_TARGET_DIR when set. + let base = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); + let dir = base + .join("source-map") .join(format!("{label}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); dir diff --git a/tests/prove.rs b/tests/prove.rs new file mode 100644 index 0000000..1d7d70c --- /dev/null +++ b/tests/prove.rs @@ -0,0 +1,670 @@ +//! `marqdo prove` P0 集成测试(roadmap/prove.md §6 A–H 矩阵的 P0 部分)。 +//! +//! 全部不依赖 Lean:判定在 P1 接入,P0 只验「装载 → 降级 → 定型 → 确定性生成」。 +//! 每个用例在 `target/` 下的独立临时目录里跑 CLI(与 `Commands::Check` 同款)。 + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +struct Scratch { + dir: PathBuf, +} + +impl Scratch { + fn new(name: &str) -> Self { + let target = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); + let dir = target.join("prove-tests").join(name); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("create scratch dir"); + Self { dir } + } + + /// 把 lib/result.mq.md 拷进临时项目(import 相对文档解析)。 + fn provision_lib(&self) { + let src = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib/result.mq.md"); + let dst = self.dir.join("lib/result.mq.md"); + fs::create_dir_all(self.dir.join("lib")).expect("create lib dir"); + fs::copy(&src, &dst).expect("copy lib/result.mq.md"); + } + + fn write(&self, rel: &str, content: &str) -> PathBuf { + let path = self.dir.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).expect("create fixture parent"); + } + fs::write(&path, content).expect("write fixture"); + path + } + + fn run(&self, args: &[&str]) -> Run { + let exe: &Path = Path::new(env!("CARGO_BIN_EXE_marqdo")); + let output = Command::new(exe) + .args(args) + .current_dir(&self.dir) + .env("MARQDO_RUNTIME_DIR", self.dir.join("runtime")) + .output() + .expect("run marqdo"); + Run { + code: output.status.code().unwrap_or(1), + stdout: String::from_utf8_lossy(&output.stdout).to_string(), + stderr: String::from_utf8_lossy(&output.stderr).to_string(), + } + } +} + +struct Run { + code: i32, + stdout: String, + stderr: String, +} + +/// 审批样例(roadmap §7 / 设计 §2.5):分支 + 内联 result + 不透明 import。 +const APPROVAL: &str = r#"--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +审批一个报销申请:大额必须人工审核,小额自动通过。 + +# 审批台 + +## 审批 ++ `金额` + +| 参数 | 类型 | 说明 | +|---|---|---| +| 金额 | int | 申请金额(元) | + +1. `金额` > 10000 + **回执 = [提交人工审核](人工审核(金额=`金额`))** + **结果 = [保留结论](result.ok(value=[取值](access(`回执`, "value"))))** +2. * + **结果 = [自动通过](result.ok(value="auto"))** + +*结果* + +## 人工审核 ++ `金额` + +**回执 = [请求送审](工程.送审(金额=`金额`))** + +*回执* +"#; + +/// 倒计时:while 循环 → P0 拒绝(proof.while)。 +const COUNTDOWN: &str = r#"--- +markup: occlusion +--- + +# 倒计时器 + +## 倒数 ++ `n` + +**剩余 = `n`** +- `剩余` > 0 + **剩余 = `剩余` - 1** + +*剩余* +"#; + +/// 分支后还有 return:两臂都必须带上后续(续延丢失回归测试)。 +const BRANCH_THEN_RETURN: &str = r#"--- +markup: occlusion +--- + +# 盒子 + +## 挑选 ++ `n` + +1. `n` > 0 + **输出 = "正"** +2. * + **输出 = "负"** + +*输出* +"#; + +/// 裸未知名:动态调用 → 拒绝。 +const UNKNOWN_CALL: &str = r#"--- +markup: occlusion +--- + +# 神秘 + +## 执行 + +**回执 = [召唤](不存在的函数(`1`))** + +*回执* +"#; + +/// 带定理表的审批样例(roadmap §3 / 设计 §7.1;与设计文档示例同形)。 +const APPROVAL_WITH_CLAIMS: &str = r#"--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 审批台 + +## 审批 ++ `金额` + +| 参数 | 类型 | 说明 | +|---|---|---| +| 金额 | int | 申请金额(元) | + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | +| 恒有结果 | 结果.ok = True | | auto | + +1. `金额` > 10000 + **回执 = [提交人工审核](人工审核(金额=`金额`))** + **结果 = [保留结论](result.ok(value=[取值](access(`回执`, "value"))))** +2. * + **结果 = [自动通过](result.ok(value="auto"))** + +*结果* + +## 人工审核 ++ `金额` + +**回执 = [请求送审](工程.送审(金额=`金额`))** + +*回执* +"#; + +fn read(dir: &Path, rel: &str) -> String { + fs::read_to_string(dir.join(rel)).unwrap_or_else(|e| panic!("read {rel}: {e}")) +} + +#[test] +fn p0_a_emit_writes_deterministic_artifacts() { + let s = Scratch::new("a_deterministic"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r1 = s.run(&["prove", "approval.mq.md", "--emit", "out1"]); + assert_eq!(r1.code, 0, "emit1 stderr={}", r1.stderr); + let r2 = s.run(&["prove", "approval.mq.md", "--emit", "out2"]); + assert_eq!(r2.code, 0, "emit2 stderr={}", r2.stderr); + + for rel in ["out1/plan.json", "out1/Generated/approval_mq.lean"] { + assert!(s.dir.join(&rel).is_file(), "missing {rel}"); + } + // 确定性:两次 emit 字节一致(plan + lean)。 + assert_eq!( + read(&s.dir, "out1/plan.json"), + read(&s.dir, "out2/plan.json"), + "plan.json must be byte-identical" + ); + assert_eq!( + read(&s.dir, "out1/Generated/approval_mq.lean"), + read(&s.dir, "out2/Generated/approval_mq.lean"), + "lean module must be byte-identical" + ); +} + +#[test] +fn p0_b_json_contract_shape() { + let s = Scratch::new("b_json_shape"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md", "--report-only", "--json"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["schema"], 1); + assert_eq!(v["status"], "unverified"); + assert_eq!(v["file"], "approval.mq.md"); + assert!(v["source_sha256"].as_str().is_some_and(|h| h.len() == 64)); + let functions = v["functions"].as_array().expect("functions array"); + assert_eq!(functions.len(), 2, "对象不进报告,只有两个函数"); + let names: Vec<&str> = functions + .iter() + .map(|f| f["name"].as_str().expect("name")) + .collect(); + assert_eq!(names, vec!["审批台.审批", "审批台.人工审核"]); + for f in functions { + assert_eq!(f["tier"], "none", "P0 无判定层"); + assert_eq!(f["status"], "unverified"); + assert_eq!(f["claims"].as_array().map(Vec::len), Some(0)); + } + // lean 尚未接入(P0 判定在 P1)。 + assert!(v["lean"].is_null()); + // emitted 为空(report-only)。 + assert_eq!(v["emitted"].as_array().map(Vec::len), Some(0)); +} + +#[test] +fn p0_c_while_loop_rejected_with_code() { + let s = Scratch::new("c_while_rejected"); + s.write("countdown.mq.md", COUNTDOWN); + let r = s.run(&["prove", "countdown.mq.md", "--report-only", "--json"]); + // 拒绝是建议性(exit 0),不阻断 agent。 + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "rejected"); + let f = &v["functions"][0]; + assert_eq!(f["name"], "倒计时器.倒数"); + assert_eq!(f["status"], "rejected"); + let rejected = f["rejected"].as_array().expect("rejected array"); + assert!( + rejected + .iter() + .any(|d| d["code"] == "proof.while"), + "expected proof.while, got {rejected:?}" + ); + // 文本面也列出拒绝原因。 + let t = s.run(&["prove", "countdown.mq.md", "--report-only"]); + assert!(t.stdout.contains("proof.while"), "text: {}", t.stdout); +} + +#[test] +fn p0_d_side_effect_import_is_opaque_op() { + let s = Scratch::new("d_opaque_op"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/approval_mq.lean"); + // 工程外部调用:Op 构造器 + Env 查询 + 追踪,不展开。 + assert!(lean.contains("«调用:工程.送审»"), "op ctor missing:\n{lean}"); + assert!(lean.contains("env (Op.«调用:工程.送审»"), "env query missing"); + assert!(lean.contains("[Op.«调用:工程.送审»"), "trace append missing"); + // result.ok 内联为 Val 构造器,不是 Op。 + assert!(!lean.contains("result.ok»"), "result.ok must inline, not be an Op"); + assert!(lean.contains("mqResultOk"), "result.ok → mqResultOk"); +} + +#[test] +fn p0_e_allow_opaque_downgrades_whole_function() { + let s = Scratch::new("e_allow_opaque"); + s.write("countdown.mq.md", COUNTDOWN); + let r = s.run(&[ + "prove", + "countdown.mq.md", + "--report-only", + "--json", + "--allow-opaque", + "倒计时器.倒数", + ]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "unverified"); + let f = &v["functions"][0]; + assert_eq!(f["status"], "unverified"); + let ops = f["ops"].as_array().expect("ops"); + assert_eq!(ops.len(), 1, "整函数降级 = 单个 Op"); + assert_eq!(ops[0]["id"], "调用:倒计时器.倒数"); + assert_eq!(ops[0]["effect"], "opaque"); +} + +#[test] +fn p0_f_branch_continuation_not_swallowed() { + let s = Scratch::new("f_continuation"); + s.write("box.mq.md", BRANCH_THEN_RETURN); + let r = s.run(&["prove", "box.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/box_mq.lean"); + // 分支后的 return 必须出现在两个臂里(回归:此前续延被分支吞掉)。 + assert_eq!( + lean.matches("(输出, 轨迹)").count(), + 2, + "return must appear in both arms:\n{lean}" + ); + // 两臂各自绑定。 + assert!(lean.contains("let 输出 := (Val.text \"正\")"), "{lean}"); + assert!(lean.contains("let 输出 := (Val.text \"负\")"), "{lean}"); +} + +#[test] +fn p0_g_mq_line_comments_and_guillemets() { + let s = Scratch::new("g_comments"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/approval_mq.lean"); + assert!(lean.contains("-- mq: "), "溯源注释缺失"); + // 含点标识符用 guillemets。 + assert!(lean.contains("«审批台.审批»"), "{lean}"); + // 确定性来源:无时间戳、无绝对路径。 + assert!(!lean.contains("marqdo/prove/"), "must not leak default dir"); +} + +#[test] +fn p0_h_unknown_call_rejected() { + let s = Scratch::new("h_unknown"); + s.write("mystery.mq.md", UNKNOWN_CALL); + let r = s.run(&["prove", "mystery.mq.md", "--report-only", "--json"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "rejected"); + let rejected = v["functions"][0]["rejected"] + .as_array() + .expect("rejected array"); + assert!( + rejected.iter().any(|d| d["code"] == "proof.dynamic_call"), + "expected proof.dynamic_call, got {rejected:?}" + ); +} + +#[test] +fn p0_i_report_only_writes_nothing() { + let s = Scratch::new("i_report_only"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md", "--report-only"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + assert!( + !s.dir.join(".marqdo").exists(), + "report-only must not create artifacts" + ); + assert!(!r.stdout.contains("emitted:"), "no emitted lines"); +} + +#[test] +fn p0_j_clean_removes_default_dir() { + let s = Scratch::new("j_clean"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + assert!(s.dir.join(".marqdo/prove").exists(), "default emit dir"); + let r = s.run(&["prove", "clean", "--json"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + assert!(r.stdout.contains("\"ok\":true"), "{}", r.stdout); + assert!(!s.dir.join(".marqdo/prove").exists(), "clean must remove dir"); +} + +#[test] +fn p0_k_branch_type_conflict_is_error() { + let s = Scratch::new("k_type_conflict"); + s.write( + "conflict.mq.md", + r#"--- +markup: occlusion +--- + +# 冲突 + +## 挑选 ++ `n` + +| 参数 | 类型 | 说明 | +|---|---|---| +| n | int | 数值 | + +1. `n` > 0 + **输出 = `n`** +2. * + **输出 = "文字"** + +*输出* +"#, + ); + let r = s.run(&["prove", "conflict.mq.md", "--report-only", "--json"]); + // error → exit 1(§3.3)。 + assert_eq!(r.code, 1, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "error"); + let codes: Vec<&str> = v["diagnostics"] + .as_array() + .expect("diagnostics") + .iter() + .filter_map(|d| d["code"].as_str()) + .collect(); + assert!( + codes.iter().any(|c| *c == "proof.type_mismatch"), + "expected proof.type_mismatch, got {codes:?}" + ); +} + +#[test] +fn p0_l_only_filters_report() { + let s = Scratch::new("l_only"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&[ + "prove", + "approval.mq.md", + "--report-only", + "--json", + "--only", + "审批台.人工审核", + ]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + let functions = v["functions"].as_array().expect("functions"); + assert_eq!(functions.len(), 1); + assert_eq!(functions[0]["name"], "审批台.人工审核"); +} + +// ============================================================ P1 · 定理表与 check --proof + +/// 提取后的定理表:claims 非空、body 无该表(roadmap §3 第 1 周验收)。 +#[test] +fn p1_a_claim_table_extracted_and_removed_from_body() { + let s = Scratch::new("p1_extract"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL_WITH_CLAIMS); + let r = s.run(&["prove", "approval.mq.md", "--report-only", "--json"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + let f = &v["functions"][0]; + assert_eq!(f["name"], "审批台.审批"); + let claims = f["claims"].as_array().expect("claims array"); + assert_eq!(claims.len(), 2, "{claims:?}"); + assert_eq!(claims[0]["id"], "大额必经人工"); + assert_eq!(claims[0]["premise"], "金额 > 10000"); + assert_eq!(claims[0]["conclusion"], "包含(轨迹, \"人工审核\")"); + assert_eq!(claims[1]["id"], "恒有结果"); + assert!(claims[1]["premise"].is_null(), "空前提 = 全称命题"); + // 表从 body 移除:plan 的 steps 里没有表(函数照常降级)。 + assert_eq!(f["status"], "unverified"); +} + +/// 定理脚手架进 Lean:受限文法命题 → theorem 陈述 + sorry 占位。 +#[test] +fn p1_b_emit_theorem_scaffold() { + let s = Scratch::new("p1_theorem"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL_WITH_CLAIMS); + let r = s.run(&["prove", "approval.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/approval_mq.lean"); + assert!( + lean.contains("theorem «审批台.审批.大额必经人工»"), + "{lean}" + ); + // 前提进绑定;包含(轨迹, …) 翻成操作名成员测试。 + assert!(lean.contains("(h_前提 : mqTruth (mqGt 金额 (Val.int 10000)))"), "{lean}"); + assert!( + lean.contains("((轨迹.map Op.name).contains \"人工审核\")"), + "{lean}" + ); + // 结果.ok → mqAccess 字段读取。 + assert!(lean.contains("(mqAccess 结果 \"ok\")"), "{lean}"); + // 策略脚本(§7.2):unfold → split → simp_all/omega。 + assert!(lean.contains("unfold «审批台.审批» at h_run"), "{lean}"); + assert!(lean.contains("split at h_run <;> simp_all <;> omega"), "{lean}"); +} + +/// check --proof(默认关):不传 --proof 时定理问题不报。 +#[test] +fn p1_c_check_proof_off_by_default() { + let s = Scratch::new("p1_default_off"); + s.write( + "bad.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `金额` + +| 定理 | 结论 | +|---|---| +| 引用未知 | 额度 > 0 | + +**x = `金额`** + +*x* +"#, + ); + let r = s.run(&["check", "bad.mq.md", "--json"]); + assert_eq!(r.code, 0, "默认关:{} {}", r.stdout, r.stderr); + assert!( + !r.stdout.contains("proof.claim_unknown_symbol"), + "默认必须不报:{}", + r.stdout + ); +} + +/// check --proof:unknown_symbol + duplicate + misplaced + malformed。 +#[test] +fn p1_d_check_proof_diagnostic_codes() { + let s = Scratch::new("p1_codes"); + s.write( + "bad.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 引用未知 | 长度(轨迹) = 额度 | 金额 > 0 | auto | +| 引用未知 | 长度(轨迹) = 额度 | 金额 > 0 | auto | +| 坏策略 | 结果.ok = True | | manual | + +**x = `金额`** + +| 定理 | 结论 | +|---|---| +| 错位表 | 结果.ok = True | + +*x* +"#, + ); + let r = s.run(&["check", "bad.mq.md", "--proof", "--json"]); + assert_eq!(r.code, 1, "error 级诊断 → 退出 1:{}", r.stdout); + assert!(r.stdout.contains("proof.claim_unknown_symbol"), "{}", r.stdout); + assert!(r.stdout.contains("proof.claim_duplicate"), "{}", r.stdout); + assert!(r.stdout.contains("proof.claim_misplaced"), "{}", r.stdout); + assert!(r.stdout.contains("proof.claim_malformed"), "{}", r.stdout); + // 不该误报:策略 auto/none 之外的 malformed 只出现一次(坏策略行)。 + assert_eq!(r.stdout.matches("proof.claim_malformed").count(), 1, "{}", r.stdout); +} + +/// check --proof:保留名遮蔽(§7.3.4)。 +#[test] +fn p1_e_check_proof_name_shadow() { + let s = Scratch::new("p1_shadow"); + s.write( + "shadow.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `结果` + +| 定理 | 结论 | +|---|---| +| 恒真 | 结果.ok = True | + +**x = `结果`** + +*x* +"#, + ); + let r = s.run(&["check", "shadow.mq.md", "--proof", "--json"]); + assert_eq!(r.code, 1, "{}", r.stdout); + assert!(r.stdout.contains("proof.name_shadow"), "{}", r.stdout); +} + +/// check --proof:歧义表(类型+结论)与谓词元数(§7.1 规则 5 / §7.3.5)。 +#[test] +fn p1_f_check_proof_ambiguous_and_unsupported() { + let s = Scratch::new("p1_amb"); + s.write( + "amb.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `金额` + +| 定理 | 类型 | 结论 | +|---|---|---| +| 歧义 | int | 结果.ok = True | + +**x = `金额`** + +*x* +"#, + ); + let r = s.run(&["check", "amb.mq.md", "--proof", "--json"]); + assert!(r.stdout.contains("proof.claim_ambiguous"), "{}", r.stdout); + + let s2 = Scratch::new("p1_unsupported"); + s2.write( + "bad2.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 元数错 | 包含(轨迹, "a", "b") | auto | + +**x = `金额`** + +*x* +"#, + ); + let r = s2.run(&["check", "bad2.mq.md", "--proof", "--json"]); + assert!(r.stdout.contains("proof.claim_unsupported"), "{}", r.stdout); +} + +/// 带定理的文件:emit 输出仍然确定性(plan.json + lean 两次一致)。 +#[test] +fn p1_g_emit_with_claims_is_deterministic() { + let s = Scratch::new("p1_det"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL_WITH_CLAIMS); + s.run(&["prove", "approval.mq.md", "--emit", "out1"]); + s.run(&["prove", "approval.mq.md", "--emit", "out2"]); + assert_eq!( + read(&s.dir, "out1/Generated/approval_mq.lean"), + read(&s.dir, "out2/Generated/approval_mq.lean") + ); + assert_eq!(read(&s.dir, "out1/plan.json"), read(&s.dir, "out2/plan.json")); + // plan.json 里定理声明带行号锚点。 + let plan = read(&s.dir, "out1/plan.json"); + assert!(plan.contains("\"claims\":[{"), "{plan}"); + assert!(plan.contains("\"line\":16"), "{plan}"); +}