From 528a1f0dbcbe45474f9c1aa0bc273b1196922710 Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 13 Nov 2026 17:29:14 +0800 Subject: [PATCH] prove: fix 4 review defects (honesty + compilability) + business validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Code review after the initial prove commit found and fixed: 1. Calls inside table/list literals were silently dropped — a function with side-effectful cells lowered to "no ops" and claimed purity in Lean. lower_expr's fallback now rejects with proof.unsupported (author must bind the call to a variable first). 2. Same-callee call sites with different arities (optional params) shared one Op whose ctor declared the first-seen arity, emitting uncompilable Lean. register_op now suffixes `/N` per arity. 3. proof.name_shadow fired once per walked function (N functions → N duplicates) and checked params of claim-free functions. Predicate check runs once per module; param check only for functions that carry claims. 4. 长度(轨迹) = 2 emitted mqEq (Nat) (Val) — type-mismatched Lean. Nat-context detection renders trace-length comparisons natively; untranslatable shapes become comments instead of broken Lean. Hardening: lean_ident reserves 轨迹₀ / h_前提 (theorem binder collision); emit_theorems dedups repeated claim ids. Tests: +4 integration regressions (p2_a..p2_d), 23 prove tests total; full suite green except the documented env-limited failures (one host::foreign_session flake passes standalone). Business validation (doc §12): e-commerce order-approval SKILL with 3 theorems cross-checked against the real interpreter — 5000 → auto (1-step trace), 20000/60000 → manual ticket T-20000/T-60000 (需人工→创建, exactly 2 steps); corrupted claim tables hit check --proof codes while staying default-off; double emit byte-identical. --- doc/design/prove-cli.md | 17 ++++ src/prove/emit.rs | 117 ++++++++++++++++++++-------- src/prove/lower.rs | 36 +++++++-- src/prove/proof_check.rs | 116 ++++++++++----------------- tests/prove.rs | 164 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 337 insertions(+), 113 deletions(-) diff --git a/doc/design/prove-cli.md b/doc/design/prove-cli.md index 333a6f7..9c3bdfb 100644 --- a/doc/design/prove-cli.md +++ b/doc/design/prove-cli.md @@ -774,3 +774,20 @@ pub fn audit_path(path: &Path) -> Result; // 不判定 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)。 + +### 审查修复(同日代码审查发现,均有回归测试) + +| 缺陷 | 后果 | 修复 | +|---|---|---| +| 表格单元格里的调用被静默丢弃 | 含副作用调用的函数在 Lean 里伪装成"无操作"——违反诚实性契约 | `lower_expr` 回退分支检测容器内的调用 → `proof.unsupported` 拒绝整个函数 | +| 同名不同元数的调用点共享一个 Op | 构造器按首现声明元数,另一调用点生成非法 Lean(无法编译) | `register_op` 对不同元数加 `/N` 后缀,各自独立声明(轨迹名诚实区分) | +| `name_shadow` 每层遍历重复报告 | 模块有 N 个函数就报 N 次,噪声淹没真实问题 | 谓词名检查只跑一次(模块级事实);形参检查只看自带定理表的函数 | +| `长度(轨迹) = 2` 生成 `mqEq (Nat) (Val)` | Nat 与 Val 类型不匹配,Lean 无法编译 | Nat 语境检测:轨迹长度与整数字面量的比较走原生 Nat 运算;不可译形状 → 注释占位 | + +另有防护加固:`lean_ident` 保留 `轨迹₀`/`h_前提`(定理 binder 撞名防御);emit 对重复定理 id 去重(`check --proof` 未跑时也不产出重复声明)。 + +### 审查时的业务级验证(/tmp/biz,电商大额订单审批流) + +- `审批.mq.md`(审批单 + 人工审核)+ `风控.mq.md`(风险分级)+ `lib/工单.mq.md`(建单):三条定理(大额必经人工 / 恰两步轨迹 / 必有回执)提取成功 +- 真实解释器三场景交叉验证:5000 元 → `auto`(1 步轨迹);20000/60000 元 → 人工建单 `T-20000`/`T-60000`(`需人工 → 创建` 恰两步)——与定理表逐条吻合 +- 负例:破坏定理表(未知符号 + 重复 id + 谓词元数错)→ `check --proof` 各报一码且默认关静默;emit 仍 advisory 可用;双次 emit 字节一致 diff --git a/src/prove/emit.rs b/src/prove/emit.rs index 5802d89..16e82fe 100644 --- a/src/prove/emit.rs +++ b/src/prove/emit.rs @@ -6,6 +6,7 @@ //! P0 形态:参数统一 `Val`(P1 起按契约提升为 `Int`/`String` 等以配合 //! `structure Params` 与定理表);`result.ok/error` 内联为库构造器。 +use std::collections::BTreeSet; use std::fmt::Write as _; use crate::prove::ir::{ @@ -54,7 +55,17 @@ fn emit_theorems(out: &mut String, fun: &FnPlan) { for param in &fun.params { let _ = write!(binders, " ({} : Val)", lean_ident(¶m.name)); } + let mut seen_theorem_names: BTreeSet = BTreeSet::new(); for claim in &fun.claims { + let theorem_name = lean_ident(&format!("{}.{}", fun.name, claim.id)); + if !seen_theorem_names.insert(theorem_name.clone()) { + let _ = writeln!( + out, + "-- 定理 {} 重复(同 id 的定理只生成一次;check --proof 会给 proof.claim_duplicate)", + claim.id + ); + continue; + } let premise_lean = claim .premise .as_deref() @@ -68,11 +79,7 @@ fn emit_theorems(out: &mut String, fun: &FnPlan) { 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, "theorem {theorem_name} {binders}{premise_text} :"); let _ = writeln!( out, " ∀ (结果 : Val) (轨迹 : List Op)," @@ -128,7 +135,13 @@ const LEAN_KEYWORDS: &[&str] = &[ ]; fn lean_ident(name: &str) -> String { - if LEAN_KEYWORDS.contains(&name) || name == "env" || name == "轨迹" || name == "结果" { + if LEAN_KEYWORDS.contains(&name) + || name == "env" + || name == "轨迹" + || name == "结果" + || name == "轨迹₀" + || name == "h_前提" + { 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()) @@ -591,22 +604,33 @@ mod tests { /// 语义映射(§7.2): /// - `结果.ok / 结果.value / 结果.error` → `mqAccess 结果 "ok"` 等; /// - `包含(轨迹, s)` → `(轨迹.map Op.name).contains s`; -/// - `长度(轨迹)` → `(轨迹.length : Nat)`(与自然数比较); +/// - `长度(轨迹)` → `(轨迹.length : Nat)`,与整数比较走 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)) + claim_term(&ast) } -fn claim_term(ast: &super::proof_check::ClaimAst) -> String { +/// `长度(轨迹)`:Nat 语境的锚点(轨迹长度与整数比较必须走 Nat 运算, +/// 否则 `mqEq : Val → Val → Bool` 类型不匹配)。 +fn is_trace_len(ast: &super::proof_check::ClaimAst) -> bool { + matches!( + ast, + super::proof_check::ClaimAst::Call { name, args } + if name == "长度" + && matches!(args.first(), Some(super::proof_check::ClaimAst::Var(v)) if v == "轨迹") + ) +} + +fn claim_term(ast: &super::proof_check::ClaimAst) -> Option { 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::Lit(CTok::Int(i)) => Some(format!("(Val.int {i})")), + A::Lit(CTok::Num(n)) => Some(format!("(Val.num {n:?})")), + A::Lit(CTok::Bool(b)) => Some(format!("(Val.bool {b})")), + A::Lit(CTok::Text(s)) => Some(format!("(Val.text {})", lean_string(s))), + A::Lit(_) => None, A::Var(name) => { // 定理作用域里 `结果`/`轨迹` 是 ∀ 绑定的输出名(不加 v_ 前缀); // `根.字段` → mqAccess 字段读取;其余按标识符规则(形参等)。 @@ -614,41 +638,68 @@ fn claim_term(ast: &super::proof_check::ClaimAst) -> String { Some((r, f)) => (r, Some(f)), None => (name.as_str(), None), }; - match (root, field) { + let term = 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), - } + }; + Some(term) } 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])) - ) + let item = strip_val_text(&claim_term(&args[1])?); + Some(format!("((轨迹.map Op.name).contains {item})")) } - ("长度", 1, true) => "(轨迹.length : Nat)".to_string(), + ("长度", 1, true) => Some("(轨迹.length : Nat)".to_string()), _ => { - let rendered: Vec = args.iter().map(claim_term).collect(); - match (name.as_str(), rendered.as_slice()) { + let mut rendered = Vec::with_capacity(args.len()); + for arg in args { + rendered.push(claim_term(arg)?); + } + let term = 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(" ")), - } + }; + Some(term) } } } A::Bin { op, left, right } => { - let (l, r) = (claim_term(left), claim_term(right)); - match *op { + // Nat 语境:操作数是 `长度(轨迹)` 或整数字面量 → 原生 Nat 运算。 + if is_trace_len(left) || is_trace_len(right) { + let nat = |a: &A| -> Option { + if is_trace_len(a) { + Some("(轨迹.length : Nat)".to_string()) + } else if let A::Lit(CTok::Int(i)) = a { + Some(i.to_string()) + } else { + None + } + }; + let (l, r) = (nat(left)?, nat(right)?); + return match *op { + "=" => Some(format!("({l} = {r})")), + "≠" => Some(format!("({l} ≠ {r})")), + "<" => Some(format!("({l} < {r})")), + "≤" => Some(format!("({l} ≤ {r})")), + ">" => Some(format!("({l} > {r})")), + "≥" => Some(format!("({l} ≥ {r})")), + "+" => Some(format!("({l} + {r})")), + "-" => Some(format!("({l} - {r})")), + _ => None, + }; + } + let (l, r) = (claim_term(left)?, claim_term(right)?); + let term = match *op { "+" => format!("(mqAdd {l} {r})"), "-" => format!("(mqSub {l} {r})"), "*" => format!("(mqMul {l} {r})"), @@ -661,16 +712,18 @@ fn claim_term(ast: &super::proof_check::ClaimAst) -> String { "≥" => format!("(mqGe {l} {r})"), "且" => format!("(mqAnd {l} {r})"), "或" => format!("(mqOr {l} {r})"), - other => format!("-- 未知算子 {other}"), - } + _ => return None, + }; + Some(term) } A::Un { op, expr } => { - let e = claim_term(expr); - match *op { + let e = claim_term(expr)?; + let term = match *op { "非" => format!("(mqNot {e})"), "-" => format!("(mqNeg {e})"), - other => format!("-- 未知一元算子 {other}"), - } + _ => return None, + }; + Some(term) } } } diff --git a/src/prove/lower.rs b/src/prove/lower.rs index e7ca523..05a1ccc 100644 --- a/src/prove/lower.rs +++ b/src/prove/lower.rs @@ -442,7 +442,7 @@ impl<'m> Lowerer<'m> { } Stmt::Call { call, span } => { // 语句形式调用:值丢弃,但有效应的调用必须留下轨迹。 - if let IrExpr::Op { id, args } = self.lower_call_expr(call, fun, body) { + if let IrExpr::Op { id, args } = self.lower_call_expr(call, fun, span.line, body) { body.steps.push(Step::Trace { op: id, args, @@ -523,7 +523,7 @@ impl<'m> Lowerer<'m> { 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::Call(call) => self.lower_call_expr(call, fun, line, body), Expr::Occluded { payload, .. } => match payload { Some(payload) => self.lower_expr(payload, fun, line, body), None => IrExpr::Pure(PureExpr::None), @@ -543,20 +543,33 @@ impl<'m> Lowerer<'m> { ); IrExpr::Op { id, args: Vec::new() } } - _ => IrExpr::Pure(PureExpr::None), + _ => { + // 诚实边界(审查修复):字面量容器(列表/映射/插值)里的调用 + // 不能变成纯片段的一部分,也不许静默丢弃——静默丢弃会让 + // 含副作用调用的函数伪装成"无操作"。拒绝并提示改写。 + if !collect_calls(other).is_empty() { + body.rejected.push(reject( + self.module, + Span::new(line, 1), + "proof.unsupported", + "列表/映射字面量里的调用不在 P0 纯片段:先把调用绑定到变量(`x` = [调用](…)`),再放进字面量", + )); + } + IrExpr::Pure(PureExpr::None) + } }, }, } } /// 调用 → 内联构造器 / 纯内建 / 不透明 Op。 - fn lower_call_expr(&self, call: &CallExpr, fun: &Function, body: &mut Body) -> IrExpr { + fn lower_call_expr(&self, call: &CallExpr, fun: &Function, line: u32, 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)); + args.push(self.lower_arg(value, fun, line, body)); } match resolve_for_exec(self.module, fun, call) { Target::Builtin(name) => lower_builtin(name, args, body), @@ -626,11 +639,11 @@ impl<'m> Lowerer<'m> { /// 实参降级:纯表达式直接用;不透明子调用先绑定临时变量再引用。 /// 临时名全局递增(`实参N`),避免内联展开时遮蔽调用者的同名变量。 - fn lower_arg(&self, value: &Expr, fun: &Function, body: &mut Body) -> PureExpr { + fn lower_arg(&self, value: &Expr, fun: &Function, line: u32, body: &mut Body) -> PureExpr { if let Some(pure) = self.lower_pure(value, fun, body) { return pure; } - match self.lower_expr(value, fun, 0, body) { + match self.lower_expr(value, fun, line, body) { // 嵌套纯调用(lower_pure 因解析上下文失败的回退路径)。 IrExpr::Pure(pure) => pure, IrExpr::Op { id, args } => { @@ -1176,7 +1189,14 @@ struct Body { impl Body { fn register_op(&mut self, display: &str, effect: impl Into, arity: usize) -> String { - let id = format!("调用:{display}"); + let base = format!("调用:{display}"); + // 同名不同元数的调用点(可选参数等)→ 加 `/元数` 后缀:构造器声明与 + // 每个使用点的实参个数保持一致,否则生成的 Lean 无法编译。 + let id = match self.ops.iter().find(|o| o.id == base) { + Some(o) if o.arity == arity => base, + Some(_) => format!("{base}/{arity}"), + None => base, + }; if self.op_ids.insert(id.clone()) { let effect = effect.into(); self.op_effects.insert(effect.clone()); diff --git a/src/prove/proof_check.rs b/src/prove/proof_check.rs index 2b43802..70eff21 100644 --- a/src/prove/proof_check.rs +++ b/src/prove/proof_check.rs @@ -21,41 +21,44 @@ pub const RESERVED_CLAIM_NAMES: &[&str] = &["结果", "轨迹"]; /// 谓词封闭集合(§7.3.5:改集合需重新评审 ADR)。 pub const PREDICATES: &[(&str, usize)] = &[("包含", 2), ("长度", 1), ("下标", 2)]; -/// 入口:对整个模块做定理表校验。 +/// 入口:对整个模块做定理表校验(只看主文件;与契约检查同一范围, +/// import 库文件不重复校验——诊断的行号锚在主文件上才有意义)。 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)); + // 谓词名遮蔽是模块级事实(与单个函数无关),整个模块只报一次; + // 诊断锚在被遮蔽的函数上(任意深度)。 + for pred in PREDICATES { + if function_names.iter().any(|n| n == pred.0) { + let Some(fun) = find_by_name(&module.functions, pred.0) else { + continue; + }; + out.push(proof_diag( + module, + path, + fun.span, + "proof.name_shadow", + format!( + "函数名 `{}` 与定理谓词 `{}` 同名(谓词集合封闭:包含/长度/下标)", + fun.name, pred.0 + ), + format!("把函数 `{}` 改名,避免定理表里的 `{}` 歧义", fun.name, pred.0), + )); + } } + walk_checks(module, &module.functions, path, &mut out); 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 walk_checks(module: &Module, funs: &[Function], path: Option<&Path>, out: &mut Vec) { + for fun in funs { + check_claim_duplicates(module, fun, path, out); + check_name_shadow(module, fun, path, out); + check_misplaced_and_malformed(module, fun, path, out); + check_claim_symbols(module, fun, path, out); + walk_checks(module, &fun.children, path, out); + } } fn collect_function_names(module: &Module, out: &mut Vec) { @@ -71,33 +74,17 @@ fn collect_function_names(module: &Module, out: &mut Vec) { } } -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 find_by_name<'a>(funs: &'a [Function], name: &str) -> Option<&'a Function> { + for f in funs { + if f.name == name { + return Some(f); + } + if let Some(inner) = find_by_name(&f.children, name) { + return Some(inner); + } } + None } fn proof_diag( @@ -134,17 +121,15 @@ fn check_claim_duplicates(module: &Module, fun: &Function, path: Option<&Path>, } } -/// 遮蔽检查(§7.3.4):保留名 `结果`/`轨迹` 不得被形参占用; -/// 谓词名 `包含/长度/下标` 不得与用户函数同名(有定理表时才有意义)。 +/// 遮蔽检查(§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 { + if fun.claims.is_empty() { return; } for param in &fun.params { @@ -163,21 +148,6 @@ fn check_name_shadow( )); } } - 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 里仍是定理形的表(默认关时解析器不提取它们)。 diff --git a/tests/prove.rs b/tests/prove.rs index 1d7d70c..b29b426 100644 --- a/tests/prove.rs +++ b/tests/prove.rs @@ -668,3 +668,167 @@ fn p1_g_emit_with_claims_is_deterministic() { assert!(plan.contains("\"claims\":[{"), "{plan}"); assert!(plan.contains("\"line\":16"), "{plan}"); } + +// ============================================================ 审查修复的回归测试 + +/// 缺陷 1:表格单元格里的副作用调用必须被拒绝,不许静默丢弃 +/// (静默丢弃会让含副作用的函数在 Lean 里伪装成"无操作")。 +#[test] +fn p2_a_impure_call_in_table_cell_is_rejected() { + let s = Scratch::new("p2_impure_tbl"); + s.write( + "record.mq.md", + r#"--- +markup: occlusion +--- + +# 副作用实验 + +## 记录 ++ `名` + +**数据 =** +| 步骤 | +|---| +| [落笔](工程.写(名=`名`)) | +| [收笔](工程.收(名=`名`)) | + +**x = [取值](access(`数据`, "步骤"))** + +*x* +"#, + ); + let r = s.run(&["prove", "record.mq.md", "--report-only", "--json"]); + assert_eq!(r.code, 0, "拒绝是 advisory,exit 0:{}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "rejected", "{v}"); + let rejected = serde_json::to_string(&v["functions"][0]["rejected"]).unwrap(); + assert!( + rejected.contains("proof.unsupported"), + "必须有 proof.unsupported:{v}" + ); + // 关键:函数里没有任何 Op(调用没被当作不透明操作处理)→ 整个函数拒绝。 + assert_eq!(v["functions"][0]["ops"].as_array().map(Vec::len), Some(0)); +} + +/// 缺陷 2:同名不同元数的调用点 → `/元数` 后缀的独立 Op,构造器与使用一致。 +#[test] +fn p2_b_op_arity_mismatch_gets_suffixed_ctor() { + let s = Scratch::new("p2_arity"); + s.write( + "machine.mq.md", + r#"--- +markup: occlusion +--- + +# 机器 + +## 可选参数 ++ `a` ++ `b` = 1 + +**r = [加一](自身.加一(a=`a`))** +**s = [加一](自身.加一(a=`a`, b=`b`))** + +*r* + +## 加一 ++ `a` ++ `b` = 1 + +**t = `a` + `b`** + +*t* +"#, + ); + let r = s.run(&["prove", "machine.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/machine_mq.lean"); + // 两个构造器,元数各自正确。 + assert!( + lean.contains("| «调用:自身.加一» (参数1 : Val)"), + "{lean}" + ); + assert!( + lean.contains("| «调用:自身.加一/2» (参数1 : Val) (参数2 : Val)"), + "{lean}" + ); + // 使用点各自带对个数的实参。 + assert!(lean.contains("Op.«调用:自身.加一» a)"), "{lean}"); + assert!(lean.contains("Op.«调用:自身.加一/2» a b)"), "{lean}"); +} + +/// 缺陷 3:`长度(轨迹) = 2` 必须生成 Nat 比较,不是 mqEq(Nat≠Val)。 +#[test] +fn p2_c_trace_length_claim_uses_nat_operators() { + let s = Scratch::new("p2_len"); + s.provision_lib(); + s.write( + "count.mq.md", + r#"--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 轨迹计数 + +## 两步 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 恰两步 | 长度(轨迹) = 2 | auto | + +**a = [一步](result.ok(value=1))** +**b = [两步](result.ok(value=2))** + +*b* +"#, + ); + let r = s.run(&["prove", "count.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/count_mq.lean"); + assert!( + lean.contains("((轨迹.length : Nat) = 2)"), + "Nat 比较:{lean}" + ); + assert!(!lean.contains("mqEq (轨迹.length"), "不许出现类型不匹配:{lean}"); +} + +/// 缺陷 4:谓词名遮蔽整个模块只报一次;无关函数的形参不误报。 +#[test] +fn p2_d_name_shadow_reported_once() { + let s = Scratch::new("p2_shadow"); + s.write( + "audit.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 包含 ++ `n` + +**y = `n`** + +*y* + +## 核对 ++ `金额` + +| 定理 | 结论 | +|---|---| +| 恒真 | 结果.ok = True | + +**x = `金额`** + +*x* +"#, + ); + let r = s.run(&["check", "audit.mq.md", "--proof", "--json"]); + assert_eq!(r.code, 1, "{}", r.stdout); + let count = r.stdout.matches("proof.name_shadow").count(); + assert_eq!(count, 1, "只报一次:{}", r.stdout); +}