prove: P1 — Lean 判定接入 CLI(driver + 证书缓存 + CI)

- driver.rs:工具链发现(--lean → MARQDO_PROOF_LEAN → PATH;显式坏路径
  error[proof.lean_missing] 不回退);MarqdoProof 库内嵌进二进制,按内容
  哈希缓存、lean -o 直接构建(运行时零 lake/elan 依赖);lean 调用带超时
  (--timeout/--heartbeats);unsolved→unproved、error→error、
  sorry→unverified;-- mq: 注释 + 定理头注释 → 证据映射指回源行
- cache.rs:复合键证书(源码⊕plan⊕库sha256⊕lean版本⊕版本),
  命中跳判定(lean.cache: hit),--no-cache/MARQDO_PROOF_NO_CACHE 绕过
- mod.rs:per-claim 判定面(status/decided_by/evidence/source_line)、
  lean JSON 对象、proof.claim_failed 诊断;文件状态只聚合有定理与被拒函数
- main.rs:--lean/--timeout/--no-cache/--heartbeats 旗标;prove emit
  子命令只生成不判定;策略 none → sorry(绝不冒充 proved)
- tests/prove_lean.rs:A1/E1/E4/F2/F3/F4/G1/G2/G2b 矩阵,无工具链 SKIP、
  MARQDO_PROOF_REQUIRE_LEAN=1 硬性要求;实测抓出并修复错误行/列解析、
  逐定理记录缺失、含点函数名归因三处判定缺陷
- CI proof.yml:装 Lean 4.35.0 → 底座校验 → 判定矩阵(CI 不许静默降级)
- 设计文档 §12 记录 P1 落地与偏差(直接 lean -o,不经 lake)

实测:业务样例 3 定理 proved;假定理 unproved 退 1 指回定理表行;
缓存命中后跳判定(假 lean 计数器验证);全量 Rust 测试 508 通过
(仅剩 2 个已记录环境基线失败)。
This commit is contained in:
cflmy committed 2026-11-18 10:28:18 +08:00
1 parent fa832268b3
commit 44d2928c06
11 files changed
+1776 -27

No files matched your search

+28
View File
@@ -536,6 +536,22 @@ enum Commands {
/// CI strict mode: unjudged statuses exit 2 (P1+)
#[arg(long)]
require_lean: bool,
/// Explicit lean binary (else MARQDO_PROOF_LEAN, else PATH)
#[arg(long, value_name = "PATH")]
lean: Option<PathBuf>,
/// Per-lean-call timeout in seconds (default 120)
#[arg(long, value_name = "SEC", default_value_t = 120)]
timeout: u64,
/// Bypass the certificate cache (also MARQDO_PROOF_NO_CACHE)
#[arg(long)]
no_cache: bool,
/// maxHeartbeats for lean (default: lean's own)
#[arg(long, value_name = "N")]
heartbeats: Option<u64>,
},
}
@@ -1081,6 +1097,10 @@ fn try_main(cli: Cli) -> Result<i32> {
allow_opaque,
no_strict_types,
require_lean,
lean,
timeout,
no_cache,
heartbeats,
} => {
// 子命令参数覆盖顶层默认;默认动作 = emit + 报告。
let (file, action_json, action_emit, action_only, action_opaque, action_relax) =
@@ -1131,6 +1151,9 @@ fn try_main(cli: Cli) -> Result<i32> {
let emit_target = action_emit.flatten();
let report_only = matches!(action, Some(ProveAction::Audit { .. }))
|| (action.is_none() && report_only);
// emit 子命令只生成不判定(§8.2)。
let judge = !matches!(action, Some(ProveAction::Emit { .. }));
let no_cache = no_cache || std::env::var_os("MARQDO_PROOF_NO_CACHE").is_some();
let opts = marqdo::prove::ProveOptions {
entry: None,
only: action_only,
@@ -1139,6 +1162,11 @@ fn try_main(cli: Cli) -> Result<i32> {
strict_types: !action_relax,
require_lean,
report_only,
judge,
no_cache,
lean,
timeout: std::time::Duration::from_secs(timeout),
max_heartbeats: heartbeats,
};
let report = marqdo::prove::prove_path(&file, &opts)?;
for d in &report.diagnostics {
+245
View File
@@ -0,0 +1,245 @@
//! 证书缓存(设计 §8.3):复合键、命中跳判定、失效。
//!
//! 键 = sha256(源码 ⊕ plan.json ⊕ schema ⊕ 库 sha256 ⊕ lean --version ⊕ marqdo 版本)。
//! 证书落在产物目录(`.marqdo/prove/<srcKey8>/certificate.json`);键不合即失效。
use std::path::Path;
use anyhow::Result;
use sha2::{Digest, Sha256};
use crate::prove::Verdict;
pub const CERT_SCHEMA: u32 = 1;
/// 单条定理的判定记录。
#[derive(Debug, Clone, PartialEq)]
pub struct ClaimRecord {
pub id: String,
pub function: String,
pub status: Verdict,
pub source_line: Option<u32>,
}
/// 一份判定证书(复核收据,不是发布许可)。
#[derive(Debug, Clone)]
pub struct Certificate {
pub key: String,
pub status: Verdict,
pub tier: &'static str,
pub source_sha256: String,
pub library_sha256: String,
pub toolchain: String,
pub module_sha256: String,
pub claims: Vec<ClaimRecord>,
/// lean 行 → mq 行。
pub span_map: Vec<(u32, u32)>,
pub marqdo: String,
}
/// 复合缓存键。
pub fn cache_key(
source_sha256: &str,
plan_sha256: &str,
library_sha256: &str,
toolchain: &str,
marqdo_version: &str,
) -> String {
let mut hasher = Sha256::new();
hasher.update(source_sha256.as_bytes());
hasher.update(b"\x00");
hasher.update(plan_sha256.as_bytes());
hasher.update(b"\x00");
hasher.update(library_sha256.as_bytes());
hasher.update(b"\x00");
hasher.update(toolchain.as_bytes());
hasher.update(b"\x00");
hasher.update(marqdo_version.as_bytes());
hex(&hasher.finalize())
}
pub fn sha256_hex(data: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(data);
hex(&hasher.finalize())
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
impl Certificate {
pub fn to_json(&self) -> serde_json::Value {
serde_json::json!({
"schema": CERT_SCHEMA,
"key": self.key,
"status": self.status.as_str(),
"tier": self.tier,
"source_sha256": self.source_sha256,
"library_sha256": self.library_sha256,
"toolchain": self.toolchain,
"module_sha256": self.module_sha256,
"claims": self.claims.iter().map(|c| serde_json::json!({
"id": c.id,
"function": c.function,
"status": c.status.as_str(),
"source_line": c.source_line,
})).collect::<Vec<_>>(),
"span_map": self.span_map.iter().map(|(l, m)| serde_json::json!({
"lean_line": l, "mq_line": m,
})).collect::<Vec<_>>(),
"marqdo": self.marqdo,
})
}
fn from_json(value: &serde_json::Value) -> Option<Certificate> {
use serde_json::Value;
if value.get("schema")?.as_u64()? != CERT_SCHEMA as u64 {
return None;
}
let status = match value.get("status")?.as_str()? {
"proved" => Verdict::Proved,
"checked" => Verdict::Checked,
"unverified" => Verdict::Unverified,
"unproved" => Verdict::Unproved,
"rejected" => Verdict::Rejected,
"error" => Verdict::Error,
_ => return None,
};
let parse_line = |v: &Value| v.as_u64().map(|n| n as u32);
Some(Certificate {
key: value.get("key")?.as_str()?.to_string(),
status,
tier: match value.get("tier")?.as_str()? {
"lean" => "lean",
"offline" => "offline",
_ => "none",
},
source_sha256: value.get("source_sha256")?.as_str()?.to_string(),
library_sha256: value.get("library_sha256")?.as_str()?.to_string(),
toolchain: value.get("toolchain")?.as_str()?.to_string(),
module_sha256: value.get("module_sha256")?.as_str()?.to_string(),
claims: value
.get("claims")?
.as_array()?
.iter()
.map(|c| {
Some(ClaimRecord {
id: c.get("id")?.as_str()?.to_string(),
function: c.get("function")?.as_str()?.to_string(),
status: match c.get("status")?.as_str()? {
"proved" => Verdict::Proved,
"checked" => Verdict::Checked,
"unverified" => Verdict::Unverified,
"unproved" => Verdict::Unproved,
"rejected" => Verdict::Rejected,
"error" => Verdict::Error,
_ => return None,
},
source_line: c.get("source_line").and_then(parse_line),
})
})
.collect::<Option<Vec<_>>>()?,
span_map: value
.get("span_map")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|e| {
Some((
e.get("lean_line")?.as_u64()? as u32,
e.get("mq_line")?.as_u64()? as u32,
))
})
.collect()
})
.unwrap_or_default(),
marqdo: value.get("marqdo")?.as_str()?.to_string(),
})
}
}
/// 读证书:文件缺失/损坏/键不合 → None(调用方重判)。
pub fn load(artifact_dir: &Path, key: &str) -> Option<Certificate> {
let path = artifact_dir.join("certificate.json");
let raw = std::fs::read_to_string(path).ok()?;
let value: serde_json::Value = serde_json::from_str(&raw).ok()?;
let cert = Certificate::from_json(&value)?;
(cert.key == key).then_some(cert)
}
/// 写证书(原子:临时文件 + 改名)。
pub fn store(artifact_dir: &Path, cert: &Certificate) -> Result<()> {
std::fs::create_dir_all(artifact_dir)?;
let path = artifact_dir.join("certificate.json");
let tmp = artifact_dir.join(".certificate.json.tmp");
std::fs::write(&tmp, cert.to_json().to_string())?;
std::fs::rename(&tmp, &path)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cache_key_is_order_sensitive_and_stable() {
let a = cache_key("s", "p", "l", "lean 4", "2.8.0");
let b = cache_key("s", "p", "l", "lean 4", "2.8.0");
let c = cache_key("p", "s", "l", "lean 4", "2.8.0");
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn certificate_roundtrip_preserves_verdicts() {
let cert = Certificate {
key: "k".into(),
status: Verdict::Unproved,
tier: "lean",
source_sha256: "s".into(),
library_sha256: "l".into(),
toolchain: "lean 4.35.0".into(),
module_sha256: "m".into(),
claims: vec![ClaimRecord {
id: "大额必经人工".into(),
function: "审批".into(),
status: Verdict::Unproved,
source_line: Some(21),
}],
span_map: vec![(41, 21)],
marqdo: "2.8.0".into(),
};
let parsed = Certificate::from_json(&cert.to_json()).expect("roundtrip");
assert_eq!(parsed.status, Verdict::Unproved);
assert_eq!(parsed.claims.len(), 1);
assert_eq!(parsed.claims[0].status, Verdict::Unproved);
assert_eq!(parsed.claims[0].source_line, Some(21));
}
#[test]
fn load_rejects_wrong_key_and_corrupt_file() {
let dir = std::env::temp_dir().join(format!("mq-cache-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
assert!(load(&dir, "k").is_none());
let cert = Certificate {
key: "k1".into(),
status: Verdict::Proved,
tier: "lean",
source_sha256: "s".into(),
library_sha256: "l".into(),
toolchain: "t".into(),
module_sha256: "m".into(),
claims: vec![],
span_map: vec![],
marqdo: "2.8.0".into(),
};
store(&dir, &cert).unwrap();
assert!(load(&dir, "k1").is_some());
assert!(load(&dir, "k2").is_none(), "键不合必须失效");
std::fs::write(dir.join("certificate.json"), "{broken").unwrap();
assert!(load(&dir, "k1").is_none(), "坏证书必须失效,不 panic");
let _ = std::fs::remove_dir_all(&dir);
}
}
+509
View File
@@ -0,0 +1,509 @@
//! Lean 驱动(设计 §8.4 / roadmap P1):工具链发现、语义底座构建、
//! `lean` 调用(超时)、输出解析、`-- mq:` span 映射。
//!
//! 与设计的偏差(§12 记录):驱动直接用 `lean -o` 构建 `MarqdoProof.olean`,
//! 不经 `lake`——运行时只依赖 `lean` 一个二进制,库源内嵌于本二进制
//! (`include_str!`),按内容哈希落盘缓存;lakefile 仍保留给人/CI 使用。
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use crate::prove::Verdict;
/// 内嵌语义底座源(发布二进制自带;构建期校验见 scripts/check-proof-library.sh)。
pub const LIBRARY_SRC: &str = include_str!("../../doc/verification/skill-proof/MarqdoProof.lean");
/// 单条定理的判定结果。
#[derive(Debug, Clone)]
pub struct ClaimOutcome {
/// 定理名(生成文件里的 `«函数.定理id»`)。
pub theorem: String,
/// 归属函数显示名。
pub function: String,
/// 定理 id(定理表里的 id)。
pub claim: String,
pub status: Verdict,
/// 映射回 `.mq.md` 的行号(定理表所在行附近;找不到为 None)。
pub source_line: Option<u32>,
/// Lean 原始报错(unproved/lean-error 时)。
pub detail: String,
}
/// 一次模块级 Lean 判定。
#[derive(Debug, Clone)]
pub struct LeanOutcome {
pub status: Verdict,
pub claims: Vec<ClaimOutcome>,
/// 原始 stdout+stderr(诊断证据)。
pub log: String,
/// lean 行 → mq 行 的映射表(进证书)。
pub span_map: Vec<(u32, u32)>,
}
/// 已发现的工具链。
#[derive(Debug, Clone)]
pub struct Toolchain {
pub lean: PathBuf,
pub version: String,
}
impl Toolchain {
/// 发现顺序(§8.4):显式路径 → `MARQDO_PROOF_LEAN` → `PATH`。
/// 显式给出但不可用 → Err(**不**回退:避免"以为在跑 Lean 其实没有")。
pub fn discover(explicit: Option<&Path>) -> Result<Option<Toolchain>> {
if let Some(path) = explicit {
let t = Self::from_path(path)
.with_context(|| format!("proof.lean_missing:{}", path.display()))?;
return Ok(Some(t));
}
if let Ok(env_path) = std::env::var("MARQDO_PROOF_LEAN") {
if !env_path.trim().is_empty() {
let t = Self::from_path(Path::new(&env_path)).with_context(|| {
format!("proof.lean_missing:MARQDO_PROOF_LEAN={env_path}")
})?;
return Ok(Some(t));
}
}
for dir in std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) {
let candidate = dir.join("lean");
if candidate.is_file() {
return Self::from_path(&candidate).map(Some);
}
}
Ok(None)
}
fn from_path(path: &Path) -> Result<Toolchain> {
let out = Command::new(path)
.arg("--version")
.output()
.with_context(|| format!("执行 {}", path.display()))?;
if !out.status.success() {
anyhow::bail!("{} --version 失败", path.display());
}
let version = String::from_utf8_lossy(&out.stdout).trim().to_string();
Ok(Toolchain {
lean: path.to_path_buf(),
version,
})
}
}
/// 语义底座目录(按内容哈希缓存),返回(目录,库 sha256)。
pub fn ensure_library(cache_root: &Path, lean: &Toolchain) -> Result<(PathBuf, String)> {
let lib_sha = crate::prove::cache::sha256_hex(LIBRARY_SRC.as_bytes());
let dir = cache_root.join(format!("library-{}", &lib_sha[..8]));
let src = dir.join("MarqdoProof.lean");
let olean = dir.join("MarqdoProof.olean");
if !olean.exists() {
std::fs::create_dir_all(&dir)
.with_context(|| format!("创建 {}", dir.display()))?;
std::fs::write(&src, LIBRARY_SRC)
.with_context(|| format!("写入 {}", src.display()))?;
let out = Command::new(&lean.lean)
.arg("-o")
.arg(&olean)
.arg(&src)
.output()
.with_context(|| format!("构建 MarqdoProof.olean"))?;
if !out.status.success() || !olean.exists() {
anyhow::bail!(
"MarqdoProof 库构建失败:\n{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
}
}
Ok((dir, lib_sha))
}
/// 判定一个生成的 Lean 模块。
pub fn check_module(
lean: &Toolchain,
lib_dir: &Path,
generated: &Path,
generated_src: &str,
timeout: Duration,
max_heartbeats: Option<u64>,
) -> Result<LeanOutcome> {
let span_map = span_map_of(generated_src);
let mut cmd = Command::new(&lean.lean);
cmd.env("LEAN_PATH", lib_dir);
if let Some(hb) = max_heartbeats {
cmd.arg(format!("-DmaxHeartbeats={hb}"));
}
cmd.arg(generated);
let (log, code, timed_out) = run_with_timeout(&mut cmd, timeout)?;
if timed_out {
return Ok(LeanOutcome {
status: Verdict::Error,
claims: Vec::new(),
log: format!("timeout after {}s\n{log}", timeout.as_secs()),
span_map,
});
}
// 归因:错误行 → 所在定理;每条定理都给结论(无错 → proved / sorry → unverified)。
let theorems = theorem_spans(generated_src);
let mut claims: Vec<ClaimOutcome> = Vec::new();
let mut any_unproved = false;
let mut any_error = false;
for (line_no, kind, message) in parse_lean_errors(&log) {
let info = theorems
.iter()
.find(|t| line_no >= t.start && line_no <= t.end);
let (theorem, claim, source_line) = match info {
Some(t) => (
t.name.clone(),
t.claim.clone(),
t.source_line.or_else(|| map_to_source(line_no, &span_map)),
),
// 错误在函数体/模块级(如 def 编译失败):claim 留空,走整体 Error。
None => (
String::new(),
String::new(),
map_to_source(line_no, &span_map),
),
};
let function = if theorem.is_empty() {
String::new()
} else {
function_of_theorem(&theorem, &claim)
};
let status = match kind {
ErrorKind::Unsolved => {
any_unproved = true;
Verdict::Unproved
}
ErrorKind::Other => {
any_error = true;
Verdict::Error
}
};
claims.push(ClaimOutcome {
theorem,
function,
claim,
status,
source_line,
detail: message,
});
}
for t in &theorems {
if claims.iter().any(|c| c.theorem == t.name) {
continue;
}
let (status, detail) = if t.has_sorry {
(
Verdict::Unverified,
"策略 none:定理生成但不证明".to_string(),
)
} else {
(Verdict::Proved, String::new())
};
claims.push(ClaimOutcome {
theorem: t.name.clone(),
function: function_of_theorem(&t.name, &t.claim),
claim: t.claim.clone(),
status,
source_line: t.source_line,
detail,
});
}
claims.sort_by(|a, b| a.theorem.cmp(&b.theorem));
let status = if any_error || code.map(|c| c != 0).unwrap_or(false) && !any_unproved {
// 解析到其它编译错误,或退出码非 0 且没有可归属的未证目标 → 判定层错误。
Verdict::Error
} else if any_unproved {
Verdict::Unproved
} else {
Verdict::Proved
};
Ok(LeanOutcome {
status,
claims,
log,
span_map,
})
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum ErrorKind {
Unsolved,
Other,
}
/// 带超时的进程运行(无外部依赖:spawn + try_wait 轮询)。
fn run_with_timeout(
cmd: &mut Command,
timeout: Duration,
) -> Result<(String, Option<i32>, bool)> {
use std::io::Read;
let mut child = cmd
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.context("spawn lean")?;
let deadline = Instant::now() + timeout;
loop {
if let Some(status) = child.try_wait()? {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
if let Some(mut s) = child.stdout.take() {
let _ = s.read_to_end(&mut stdout);
}
if let Some(mut s) = child.stderr.take() {
let _ = s.read_to_end(&mut stderr);
}
let mut log = String::from_utf8_lossy(&stdout).to_string();
log.push_str(&String::from_utf8_lossy(&stderr));
return Ok((log, Some(status.code().unwrap_or(-1)), false));
}
if Instant::now() > deadline {
let _ = child.kill();
let _ = child.wait();
return Ok((String::new(), None, true));
}
std::thread::sleep(Duration::from_millis(20));
}
}
/// 解析 lean 输出里的 `<path>:LINE:COL: error…`;`unsolved goals` 单独归类。
/// lean 的报错头独占一行(`Generated/x.lean:41:0: error: unsolved goals`),
/// 后随目标上下文行;这里只取头行。
fn parse_lean_errors(log: &str) -> Vec<(u32, ErrorKind, String)> {
let mut out = Vec::new();
for line in log.lines() {
// 头行形如 `<file>:LINE:COL: error: ...`(COL 可能省略)。
let Some(col_idx) = line.find(": error") else {
continue;
};
let pos = &line[..col_idx];
let message = line[col_idx..].trim_start_matches(": ").to_string();
// pos 形如 `<file>:LINE:COL`(COL 可省略);取**倒数第二个**数字段。
let fields: Vec<&str> = pos.rsplit(':').collect();
let line_no: u32 = if let Ok(col) = fields[0].parse::<u32>() {
fields.get(1).and_then(|s| s.parse().ok()).unwrap_or(col)
} else if let Ok(n) = fields[0].parse::<u32>() {
n
} else {
continue;
};
let kind = if message.contains("unsolved goals") {
ErrorKind::Unsolved
} else {
ErrorKind::Other
};
out.push((line_no, kind, message));
}
out
}
/// 生成文件里的一条定理。
#[derive(Debug, Clone)]
pub struct TheoremInfo {
pub name: String,
pub start: u32,
pub end: u32,
/// 头注释里的定理 id:`-- 定理 <id>(策略 …;mq: N)`。
pub claim: String,
/// 头注释 `;mq: N` 的 N —— 定理表在 `.mq.md` 里的行。
pub source_line: Option<u32>,
pub has_sorry: bool,
}
/// 扫描生成文件:`-- 定理` 头注释 + `theorem` 行区间 + sorry 标记。
pub fn theorem_spans(src: &str) -> Vec<TheoremInfo> {
let lines: Vec<&str> = src.lines().collect();
let mut out: Vec<TheoremInfo> = Vec::new();
// (name, start, claim, mq_line)
let mut current: Option<(String, u32, String, Option<u32>)> = None;
// 头注释暂存(claim id, mq 行)——紧随其后的 `theorem` 行使用。
let mut pending: Option<(String, Option<u32>)> = None;
for (idx, line) in lines.iter().enumerate() {
let line_no = (idx + 1) as u32;
let trimmed = line.trim_start();
if let Some(rest) = trimmed.strip_prefix("-- 定理 ") {
let head = rest.split('(').next().unwrap_or(rest).trim().to_string();
let mq = rest
.rsplit_once("mq: ")
.and_then(|(_, n)| n.trim_end_matches(')').trim().parse().ok());
pending = Some((head, mq));
continue;
}
if let Some(rest) = trimmed.strip_prefix("theorem ") {
if let Some((name, start, claim, mq)) = current.take() {
out.push(theorem_info(src, name, start, line_no - 1, claim, mq));
}
if let Some(name) = rest.split_whitespace().next() {
let (claim, mq) = pending.take().unwrap_or_default();
current = Some((name.to_string(), line_no, claim, mq));
}
} else if current.is_some()
&& !trimmed.is_empty()
&& !line.starts_with(' ')
&& !line.starts_with('\t')
&& !trimmed.starts_with("--")
{
let (name, start, claim, mq) = current.take().unwrap();
out.push(theorem_info(src, name, start, line_no.saturating_sub(1), claim, mq));
}
}
if let Some((name, start, claim, mq)) = current {
out.push(theorem_info(src, name, start, lines.len() as u32, claim, mq));
}
out
}
fn theorem_info(
src: &str,
name: String,
start: u32,
end: u32,
claim: String,
source_line: Option<u32>,
) -> TheoremInfo {
let has_sorry = src
.lines()
.skip(start.saturating_sub(1) as usize)
.take(end.saturating_sub(start) as usize + 1)
.any(|l| l.contains("sorry"));
TheoremInfo {
name,
start,
end,
claim,
source_line,
has_sorry,
}
}
/// 定理名 → 归属函数:claim id 作后缀剥掉(函数名可含点,如 `台账.记录`)。
fn function_of_theorem(theorem: &str, claim: &str) -> String {
let inner = theorem
.trim_start_matches('«')
.trim_end_matches('»')
.to_string();
if !claim.is_empty() {
let suffix = format!(".{claim}");
if let Some(f) = inner.strip_suffix(&suffix) {
return f.to_string();
}
}
// 兜底:第一段(单段函数名)。
inner
.split('.')
.next()
.unwrap_or(&inner)
.to_string()
}
/// 生成文件的 `-- mq: LINE:COL` → (lean 行, mq 行)。
pub fn span_map_of(src: &str) -> Vec<(u32, u32)> {
let mut out = Vec::new();
for (idx, line) in src.lines().enumerate() {
let trimmed = line.trim_start();
if let Some(rest) = trimmed.strip_prefix("-- mq: ") {
if let Some((l, _)) = rest.split_once(':') {
if let Ok(mq_line) = l.trim().parse::<u32>() {
out.push(((idx + 1) as u32, mq_line));
}
}
}
}
out
}
/// lean 行号 → 最近的 `-- mq:` 注释对应的源行。
fn map_to_source(lean_line: u32, span_map: &[(u32, u32)]) -> Option<u32> {
span_map
.iter()
.filter(|(l, _)| *l <= lean_line)
.map(|(_, m)| *m)
.next_back()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_lean_errors_distinguishes_line_from_col() {
// `<file>:47:62: error: …` — 行 47,列 62;曾把列当行导致定理错配。
let log = "Generated/x.lean:47:62: error: unsolved goals\n «结果» = …\n";
let errs = parse_lean_errors(log);
assert_eq!(errs.len(), 1);
assert_eq!(errs[0].0, 47, "必须取行号而非列号");
assert_eq!(errs[0].1, ErrorKind::Unsolved);
let log2 = "Generated/x.lean:12:5: error: unknown identifier «Foo»\n";
let errs2 = parse_lean_errors(log2);
assert_eq!(errs2[0].0, 12);
assert_eq!(errs2[0].1, ErrorKind::Other);
}
#[test]
fn theorem_spans_reads_header_comment_claim_and_line() {
let src = "\
-- mq: 14:1
def «台账.记录» (env : Env) («金额» : Val) : Val × List Op :=
(«金额», [])
-- 定理 记过即记(策略 none;mq: 10)
theorem «台账.记录.记过即记» (env : Env) («金额» : Val) :
True := by
trivial
-- 定理 另一条(策略 auto;mq: 11)
theorem «台账.记录.另一条» (env : Env) : True := by
sorry
";
let ts = theorem_spans(src);
assert_eq!(ts.len(), 2);
assert_eq!(ts[0].name, "«台账.记录.记过即记»");
assert_eq!(ts[0].claim, "记过即记");
assert_eq!(ts[0].source_line, Some(10));
assert!(!ts[0].has_sorry);
assert_eq!(ts[1].claim, "另一条");
assert_eq!(ts[1].source_line, Some(11));
assert!(ts[1].has_sorry, "sorry 必须被识别为 unverified");
}
#[test]
fn function_of_theorem_strips_claim_suffix_not_first_segment() {
// 函数名可含点:台账.记录.记过即记 → 函数 = 台账.记录。
assert_eq!(
function_of_theorem("«台账.记录.记过即记»", "记过即记"),
"台账.记录"
);
assert_eq!(
function_of_theorem("«审批单.大额必经人工»", "大额必经人工"),
"审批单"
);
assert_eq!(function_of_theorem("«孤定理»", ""), "孤定理");
}
#[test]
fn span_map_pairs_lean_and_mq_lines() {
let src = "-- mq: 14:1\nlet x := 1\n-- mq: 16:1\nlet y := 2\n";
assert_eq!(span_map_of(src), vec![(1, 14), (3, 16)]);
}
#[test]
fn map_to_source_finds_nearest_preceding_comment() {
let map = vec![(21, 14), (24, 16), (40, 33)];
assert_eq!(map_to_source(21, &map), Some(14));
assert_eq!(map_to_source(47, &map), Some(33));
assert_eq!(map_to_source(1, &map), None);
}
#[test]
fn toolchain_discovery_rejects_explicit_missing_path() {
let err = Toolchain::discover(Some(Path::new("/nonexistent/lean-绝无仅有")))
.expect_err("显式坏路径必须报错(不回退)");
assert!(format!("{err:#}").contains("proof.lean_missing"));
}
}
+11 -1
View File
@@ -99,6 +99,16 @@ fn emit_theorems(out: &mut String, fun: &FnPlan) {
" ((«结果», «轨迹») = {fun_name} env [] {run_args}) →"
);
let _ = writeln!(out, " mqTruth {conclusion} := by");
if tactic == "none" {
// 策略 none:定理生成但不证明(E4:状态 unverified,
// driver 依 sorry 判 unverified,绝不冒充 proved)。
let _ = writeln!(out, " intro «结果» «轨迹» h_run");
let _ = writeln!(out, " unfold {fun_name} at h_run");
let _ = writeln!(out, " try split at h_run");
let _ = writeln!(out, " all_goals");
let _ = writeln!(out, " sorry");
continue;
}
let _ = writeln!(out, " intro «结果» «轨迹» h_run");
let _ = writeln!(out, " unfold {fun_name} at h_run");
// 每个分支:simp_all(完整默认集处理 List.map/contains/length 的
@@ -160,7 +170,7 @@ const LEAN_KEYWORDS: &[&str] = &[
"namespace", "end", "import", "by", "have", "show", "assume", "from", "at", "exists",
];
fn lean_ident(name: &str) -> String {
pub(crate) fn lean_ident(name: &str) -> String {
let ascii_safe = !name.is_empty()
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
&& !name.chars().next().is_some_and(|c| c.is_ascii_digit());
+414 -25
View File
@@ -9,6 +9,8 @@
//! 判定(离线 ⑤ / Lean ⑥)在 P1/P2 接入;状态只到 `unverified` / `rejected` /
//! `error`。
pub mod cache;
pub mod driver;
pub mod emit;
pub mod ir;
pub mod lower;
@@ -97,7 +99,7 @@ impl Verdict {
}
}
/// 选项(§8.2;P0 生效的子集见字段注释)。
/// 选项(§8.2)。
#[derive(Debug, Clone)]
pub struct ProveOptions {
pub entry: Option<String>,
@@ -107,6 +109,16 @@ pub struct ProveOptions {
pub strict_types: bool,
pub require_lean: bool,
pub report_only: bool,
/// 绕过证书缓存(`--no-cache` / `MARQDO_PROOF_NO_CACHE`)。
pub no_cache: bool,
/// 显式 lean 路径(`--lean` / `MARQDO_PROOF_LEAN`)。
pub lean: Option<PathBuf>,
/// 单次 lean 调用超时(默认 120s)。
pub timeout: std::time::Duration,
/// 是否执行判定(`prove emit`/`audit` 子命令 = false,只生成不证)。
pub judge: bool,
/// `maxHeartbeats`(默认随 lean)。
pub max_heartbeats: Option<u64>,
}
impl Default for ProveOptions {
@@ -119,10 +131,32 @@ impl Default for ProveOptions {
strict_types: true,
require_lean: false,
report_only: false,
no_cache: false,
lean: None,
timeout: std::time::Duration::from_secs(120),
judge: true,
max_heartbeats: None,
}
}
}
/// 单条定理的判定面(§3.5 claims)。
#[derive(Debug, Clone)]
pub struct ClaimReport {
pub id: String,
pub premise: Option<String>,
pub conclusion: String,
pub tactic: Option<String>,
/// `proved` / `unproved` / `unverified`(判定层给出前与函数一致)。
pub status: Verdict,
/// `trace`(P2 离线)/ `lean` / 空(未判定)。
pub decided_by: String,
/// 映射回 `.mq.md` 的行号(失败证据)。
pub source_line: Option<u32>,
/// Lean 原始报错片段(unproved 时)。
pub evidence: Option<String>,
}
/// 单函数报告。
#[derive(Debug, Clone)]
pub struct FunctionReport {
@@ -133,8 +167,18 @@ pub struct FunctionReport {
pub ops: Vec<(String, String)>,
/// 拒绝原因(code, message, line)。
pub rejected: Vec<(String, String, u32)>,
/// 定理声明(id, premise, conclusion, tactic)。
pub claims: Vec<(String, Option<String>, String, Option<String>)>,
/// 定理声明 + 判定。
pub claims: Vec<ClaimReport>,
}
/// Lean 判定信息(`lean: null` 表示没跑)。
#[derive(Debug, Clone)]
pub struct LeanInfo {
pub toolchain: String,
pub library_sha256: String,
pub module_sha256: String,
/// `hit` / `miss`。
pub cache: &'static str,
}
/// 整体报告。
@@ -142,15 +186,18 @@ pub struct FunctionReport {
pub struct Report {
pub file: String,
pub source_sha256: String,
/// 产物目录 id(`.marqdo/prove/<artifact_id>`)。
pub artifact_id: Option<String>,
pub status: Verdict,
pub functions: Vec<FunctionReport>,
pub diagnostics: Vec<Diagnostic>,
pub emitted: Vec<PathBuf>,
pub lean: Option<LeanInfo>,
pub duration_ms: u128,
}
impl Report {
/// JSON 面(§3.5;`status` 枚举稳定,`lean` 恒 null 直到 P1)。
/// JSON 面(§3.5;`status` 枚举稳定)。
pub fn to_json(&self) -> serde_json::Value {
use serde_json::json;
json!({
@@ -158,17 +205,33 @@ impl Report {
"status": self.status.as_str(),
"file": self.file,
"source_sha256": self.source_sha256,
"artifact_id": serde_json::Value::Null,
"artifact_id": match &self.artifact_id {
Some(id) => json!(format!("mq://prove/{id}")),
None => 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::<Vec<_>>(),
"claims": f.claims.iter().map(|c| {
let mut j = json!({
"id": c.id,
"premise": c.premise,
"conclusion": c.conclusion,
"tactic": c.tactic,
"status": c.status.as_str(),
});
if !c.decided_by.is_empty() {
j["decided_by"] = json!(c.decided_by);
}
if let Some(line) = c.source_line {
j["line"] = json!(line);
}
if let Some(ev) = &c.evidence {
j["evidence"] = json!(ev);
}
j
}).collect::<Vec<_>>(),
"obligations": [],
"ops": f.ops.iter().map(|(id, effect)| json!({
"id": id, "effect": effect,
@@ -177,7 +240,15 @@ impl Report {
"code": code, "message": message, "line": line,
})).collect::<Vec<_>>(),
})).collect::<Vec<_>>(),
"lean": serde_json::Value::Null,
"lean": match &self.lean {
Some(info) => json!({
"toolchain": info.toolchain,
"library_sha256": info.library_sha256,
"module_sha256": info.module_sha256,
"cache": info.cache,
}),
None => serde_json::Value::Null,
},
"assumptions": [],
"diagnostics": self.diagnostics.iter().map(|d| d.to_json()).collect::<Vec<_>>(),
"emitted": self.emitted.iter().map(|p| p.display().to_string()).collect::<Vec<_>>(),
@@ -196,14 +267,14 @@ impl Report {
.count();
let ops: usize = self.functions.iter().map(|f| f.ops.len()).sum();
out.push_str(&format!("prove: {}\n", self.file));
let cache_note = match &self.lean {
Some(info) => format!("(lean · cache: {})", info.cache),
None => String::new(),
};
out.push_str(&format!(
" status: {}{}\n",
self.status.as_str(),
if self.status == Verdict::Unverified {
"(P0:仅降级与生成,判定将在 P1 提供)"
} else {
""
}
cache_note
));
out.push_str(&format!(
" functions: {functions} · opaque ops: {ops} · rejected: {rejected}\n"
@@ -213,6 +284,29 @@ impl Report {
let codes: Vec<&str> = f.rejected.iter().map(|(c, _, _)| c.as_str()).collect();
out.push_str(&format!(" rejected: {} ({})\n", f.name, codes.join(", ")));
}
for c in &f.claims {
match (c.status, &c.evidence) {
(Verdict::Proved, _) => {
out.push_str(&format!(" proved: {}.{}\n", f.name, c.id));
}
(Verdict::Unproved, Some(ev)) => {
let line = c
.source_line
.map(|l| format!(":{l}"))
.unwrap_or_default();
out.push_str(&format!(
" unproved: {}.{line}{} — {}\n",
f.name,
c.id,
first_line(ev)
));
}
(Verdict::Unverified, _) => {
out.push_str(&format!(" unverified: {}.{}\n", f.name, c.id));
}
_ => {}
}
}
}
for p in &self.emitted {
out.push_str(&format!(" emitted: {}\n", p.display()));
@@ -221,6 +315,10 @@ impl Report {
}
}
fn first_line(s: &str) -> String {
s.lines().next().unwrap_or("").to_string()
}
/// P0 主入口:装载 → 降级 → 定型 → 生成。
pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
let started = Instant::now();
@@ -249,6 +347,8 @@ pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
// ④ 生成(--report-only 时跳过写盘)。
let mut emitted: Vec<PathBuf> = Vec::new();
let mut artifact_dir: Option<PathBuf> = None;
let mut generated_lean: Option<(PathBuf, String)> = None;
if !opts.report_only {
let dir = match &opts.emit_dir {
Some(dir) => dir.clone(),
@@ -266,13 +366,15 @@ pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
.with_context(|| format!("写入 {}", plan_path.display()))?;
emitted.push(relative_cwd(&lean_path));
emitted.push(relative_cwd(&plan_path));
artifact_dir = Some(dir.clone());
generated_lean = Some((lean_path, lean));
}
// 汇总:错误诊断 → 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 functions = summarize(&lowered, &opts.only);
let mut status = Verdict::Unverified;
if !functions.is_empty() {
status = functions
@@ -284,17 +386,302 @@ pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
status = Verdict::Error;
}
// ⑤ Lean 判定(P1):有定理、有产物、非 report-only 时进行。
let mut lean_info: Option<LeanInfo> = None;
let claims_present = plan.functions.iter().any(|f| !f.claims.is_empty());
if claims_present && opts.judge && !opts.report_only {
match judge_with_lean(
&plan,
&source_sha256,
artifact_dir.as_deref(),
&generated_lean,
opts,
&mut functions,
&mut diagnostics,
) {
Ok((verdict, info)) => {
lean_info = info;
if let Some(v) = verdict {
status = v;
}
}
Err(err) => {
diagnostics.push(
Diagnostic::new(None, crate::diagnostics::Span::new(0, 0), format!("{err:#}"))
.with_code("proof.lean_error"),
);
status = Verdict::Error;
}
}
} else if claims_present && opts.report_only {
// report-only:不判定、不写盘;未证状态如实保留(恒返回 0 由 exit_code 处理)。
}
// 函数级状态聚合(判定后重算):文件状态只看**有定理**的函数
// 与被拒绝的函数——无定理函数没有义务,不该拖低整体(但它们
// 自己的行如实保留 unverified / tier none)。
{
let relevant = functions.iter().filter(|f| {
!f.claims.is_empty() || f.verdict == Verdict::Rejected
});
for f in relevant {
status = Verdict::worst(status, f.verdict);
}
}
Ok(Report {
file: file_display,
source_sha256,
artifact_id: artifact_dir
.as_ref()
.map(|d| d.file_name().map(|n| n.to_string_lossy().to_string()))
.unwrap_or(None),
status,
functions,
diagnostics,
emitted,
lean: lean_info,
duration_ms: started.elapsed().as_millis(),
})
}
/// 单一判定来源:缓存证书 → Lean 现算。返回(整体判定,lean 信息)。
#[allow(clippy::too_many_arguments)]
fn judge_with_lean(
plan: &crate::prove::ir::Plan,
source_sha256: &str,
artifact_dir: Option<&Path>,
generated_lean: &Option<(PathBuf, String)>,
opts: &ProveOptions,
functions: &mut [FunctionReport],
diagnostics: &mut Vec<Diagnostic>,
) -> Result<(Option<Verdict>, Option<LeanInfo>)> {
use crate::diagnostics::Span;
let Some((lean_path, lean_src)) = generated_lean else {
return Ok((None, None));
};
// 缓存键素材:工具链版本先探测(没有工具链就谈不上判定)。
let toolchain = match driver::Toolchain::discover(opts.lean.as_deref()) {
Ok(t) => t,
Err(err) => {
if opts.require_lean {
return Err(err);
}
diagnostics.push(
Diagnostic::new(None, Span::new(0, 0), format!("{err:#}"))
.with_code("proof.lean_missing"),
);
return Ok((None, None));
}
};
let Some(toolchain) = toolchain else {
// 没找到工具链:保持 unverified(诚实:没跑就是没跑)。
// --require-lean 时退出码由 Verdict::exit_code 升到 2(§3.3 F3)。
if opts.require_lean {
diagnostics.push(
Diagnostic::new(
None,
Span::new(0, 0),
"--require-lean:未找到 Lean 工具链(PATH/MARQDO_PROOF_LEAN/--lean)",
)
.with_code("proof.lean_missing"),
);
}
return Ok((None, None));
};
// 库(内嵌源 → olean,按内容哈希缓存)。
let cache_root = Path::new(".marqdo/prove");
let (lib_dir, library_sha256) = driver::ensure_library(cache_root, &toolchain)?;
let module_sha256 = cache::sha256_hex(lean_src.as_bytes());
let plan_sha = cache::sha256_hex(plan.to_stable_json().as_bytes());
let key = cache::cache_key(
source_sha256,
&plan_sha,
&library_sha256,
&toolchain.version,
env!("CARGO_PKG_VERSION"),
);
let mut artifact_fallback: Option<PathBuf> = None;
let artifact: &Path = match artifact_dir {
Some(d) => d,
None => {
let d = default_emit_dir(source_sha256);
// 极少见:report-only 之外无产物目录(理论上不可达)——现建。
let _ = std::fs::create_dir_all(&d);
// 借用问题:把目录放成一个本地 owned 值,再取引用。
artifact_fallback.get_or_insert(d).as_path()
}
};
// ① 证书命中 → 跳过判定。
if !opts.no_cache {
if let Some(cert) = cache::load(artifact, &key) {
apply_claims(functions, &cert.claims, &cert.span_map, diagnostics);
let status = cert.status;
return Ok((
Some(status),
Some(LeanInfo {
toolchain: toolchain.version,
library_sha256,
module_sha256,
cache: "hit",
}),
));
}
}
// ② 现算:lake env lean 等价的直接 lean 调用(LEAN_PATH 指向底座 olean)。
let outcome = driver::check_module(
&toolchain,
&lib_dir,
lean_path,
lean_src,
opts.timeout,
opts.max_heartbeats,
)?;
// ③ 证据 → 诊断(proof.claim_failed,指回源码行)。
let claim_records: Vec<cache::ClaimRecord> = outcome
.claims
.iter()
.map(|c| cache::ClaimRecord {
id: c.claim.clone(),
function: c.function.clone(),
status: c.status,
source_line: c.source_line,
})
.collect();
apply_outcome(functions, &outcome.claims, diagnostics);
let cert = cache::Certificate {
key: key.clone(),
status: outcome.status,
tier: "lean",
source_sha256: source_sha256.to_string(),
library_sha256: library_sha256.clone(),
toolchain: toolchain.version.clone(),
module_sha256: module_sha256.clone(),
claims: claim_records,
span_map: outcome.span_map.clone(),
marqdo: env!("CARGO_PKG_VERSION").to_string(),
};
if let Err(err) = cache::store(artifact, &cert) {
diagnostics.push(
Diagnostic::new(
None,
Span::new(0, 0),
format!("证书写入失败(不阻塞判定):{err:#}"),
)
.with_code("proof.cache_write"),
);
}
Ok((
Some(outcome.status),
Some(LeanInfo {
toolchain: toolchain.version,
library_sha256,
module_sha256,
cache: "miss",
}),
))
}
/// 把判定结果按 (函数, 定理 id) 贴回函数报告。
fn apply_outcome(
functions: &mut [FunctionReport],
claims: &[driver::ClaimOutcome],
diagnostics: &mut Vec<Diagnostic>,
) {
use crate::diagnostics::Span;
for c in claims {
let matches_fn = |f: &FunctionReport| {
f.name == c.function
|| emit::lean_ident(&f.name)
.trim_matches('«')
.trim_matches('»')
== c.function
};
let Some(pos) = functions.iter().position(matches_fn) else {
continue;
};
let f = &mut functions[pos];
if let Some(claim) = f.claims.iter_mut().find(|x| x.id == c.claim) {
claim.status = c.status;
claim.decided_by = "lean".into();
claim.source_line = c.source_line;
claim.evidence = (!c.detail.is_empty()).then(|| c.detail.clone());
if c.status == Verdict::Unproved {
diagnostics.push(
Diagnostic::new(
None,
Span::new(c.source_line.unwrap_or(0), 0),
format!(
"定理 {}.{} 未证:{}",
c.function,
c.claim,
first_line(&c.detail)
),
)
.with_code("proof.claim_failed"),
);
}
f.verdict = f
.claims
.iter()
.map(|x| x.status)
.fold(Verdict::Proved, Verdict::worst);
f.tier = Tier::Lean;
}
}
}
/// 证书命中的同款贴回。
fn apply_claims(
functions: &mut [FunctionReport],
claims: &[cache::ClaimRecord],
span_map: &[(u32, u32)],
diagnostics: &mut Vec<Diagnostic>,
) {
use crate::diagnostics::Span;
for c in claims {
let source_line = c.source_line.or_else(|| {
span_map
.first()
.map(|(_, m)| *m)
});
if let Some(f) = functions
.iter_mut()
.find(|f| f.name == c.function)
{
if let Some(claim) = f.claims.iter_mut().find(|x| x.id == c.id) {
claim.status = c.status;
claim.decided_by = "lean".into();
claim.source_line = source_line;
if c.status == Verdict::Unproved {
diagnostics.push(
Diagnostic::new(
None,
Span::new(source_line.unwrap_or(0), 0),
format!("定理 {}.{} 未证(缓存)", f.name, c.id),
)
.with_code("proof.claim_failed"),
);
}
f.verdict = f
.claims
.iter()
.map(|x| x.status)
.fold(Verdict::Proved, Verdict::worst);
f.tier = Tier::Lean;
}
}
}
}
fn summarize(lowered: &[Lowered], only: &[String]) -> Vec<FunctionReport> {
lowered
.iter()
@@ -312,13 +699,15 @@ fn summarize(lowered: &[Lowered], only: &[String]) -> Vec<FunctionReport> {
Vec::new(),
plan.claims
.iter()
.map(|c| {
(
c.id.clone(),
c.premise.clone(),
c.conclusion.clone(),
c.tactic.clone(),
)
.map(|c| ClaimReport {
id: c.id.clone(),
premise: c.premise.clone(),
conclusion: c.conclusion.clone(),
tactic: c.tactic.clone(),
status: Verdict::Unverified,
decided_by: String::new(),
source_line: None,
evidence: None,
})
.collect(),
),