prove: fix 4 review defects (honesty + compilability) + business validation

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.
This commit is contained in:
cflmy committed 2026-11-18 10:28:18 +08:00
1 parent a11b347659
commit 528a1f0dbc
5 files changed
+337 -113

No files matched your search

+85 -32
View File
@@ -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(&param.name));
}
let mut seen_theorem_names: BTreeSet<String> = 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<String> {
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<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::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<String> = 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<String> {
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)
}
}
}
+28 -8
View File
@@ -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<PureExpr> = 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<String>, 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());
+43 -73
View File
@@ -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<Diagnostic> {
let mut out = Vec::new();
let mut function_names: Vec<String> = 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<Diagnostic> {
// import 的库文件自带定理表也按同规则校验(诊断指向本文件行号即可)。
let mut out = Vec::new();
let mut function_names: Vec<String> = 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<Diagnostic>) {
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<String>) {
@@ -71,33 +74,17 @@ fn collect_function_names(module: &Module, out: &mut Vec<String>) {
}
}
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<Diagnostic>,
) {
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<Diagnostic>,
) {
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 里仍是定理形的表(默认关时解析器不提取它们)。