prove: add marqdo prove (P0 emit/audit + P1 claim tables & check --proof)

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).
This commit is contained in:
cflmy committed 2026-11-18 10:28:18 +08:00
1 parent 6d6f580d24
commit a11b347659
19 files changed
+6021 -13

No files matched your search

+16
View File
@@ -95,6 +95,22 @@ pub struct Function {
pub contract: Option<crate::contract::Contract>,
/// 集合契约(T2.1):变量名 → 字段契约(紧邻 `` `名` = `` 绑定之前的文档表)。
pub var_contracts: HashMap<String, crate::contract::Contract>,
/// 定理表(ADR 0010):函数级命题声明;首条可执行语句之前提取,不参与运行。
pub claims: Vec<Claim>,
}
/// 一条定理声明(设计 §7.1):`| 定理 | 结论 | 前提 | 策略 |` 的一行。
#[derive(Debug, Clone)]
pub struct Claim {
/// 定理 id(函数内唯一;重复由 `check --proof` 报 `proof.claim_duplicate`)。
pub id: String,
/// 受限表达式文本(参数、`结果`、`轨迹`、三个谓词、算术/比较/布尔)。
pub conclusion: String,
pub premise: Option<String>,
/// `auto`(默认)或 `none`;其他值由 `check --proof` 报 unsupported。
pub tactic: Option<String>,
/// 表行所在行号(锚定漂移检测)。
pub line: u32,
}
impl Function {
+13 -2
View File
@@ -23,14 +23,17 @@ use crate::load;
/// 读取文件 + 装载(含 import)后做全量契约互查。
pub fn check_path(path: &Path) -> Result<Vec<Diagnostic>> {
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<Vec<Diagnostic>> {
///
/// `proof` enables the theorem-table check (`check --proof`, ADR 0010,
/// 默认关):表形、名字、片段、遮蔽。
pub fn check_path_opts(path: &Path, implicit_labels: bool, proof: bool) -> Result<Vec<Diagnostic>> {
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<Vec<Diagnos
out.extend(crate::label::check_implicit(&module, &source, Some(path)));
}
}
if proof {
out.extend(crate::prove::proof_check::check_proofs(&module, Some(path)));
}
Ok(out)
}
@@ -213,6 +219,11 @@ fn edit_distance(a: &str, b: &str) -> usize {
prev[b.len()]
}
/// 供 `prove::proof_check` 复用的最近名建议(编辑距离 ≤ 2)。
pub fn suggest_closest(name: &str, known: &[String]) -> Option<String> {
suggest(name, known)
}
fn suggest(name: &str, known: &[String]) -> Option<String> {
let lower = name.to_ascii_lowercase();
let mut best: Option<(usize, String)> = None;
+162
View File
@@ -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<Result<Vec<crate::ast::Claim>, ClaimTableError>> {
let headers: Vec<String> = 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<Vec<String>> {
}
}
/// 定理表单元格取文本:标量直取;比较/算术/布尔表达式按 `a op b` 还原
/// (`金额 > 10000` 这类单元格会解析成 Binary,不能因为不是标量就丢行)。
/// 不认识的形状 → None(该行按缺失处理,`check --proof` 会报 unknown_symbol)。
fn claim_cell_text(e: &Expr) -> Option<String> {
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<String> {
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(),
+6 -2
View File
@@ -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");
+1
View File
@@ -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;
+166 -3
View File
@@ -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<ProveAction>,
/// Program path (.mq.md; default ./index.mq.md)
#[arg(value_name = "FILE")]
file: Option<PathBuf>,
/// 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<String>,
/// Output dir for emit (default .marqdo/prove/<key>/)
#[arg(long = "emit", short = 'o', value_name = "DIR")]
emit_dir: Option<PathBuf>,
/// 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<String>,
/// 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<PathBuf>,
#[arg(long = "emit", short = 'o', value_name = "DIR")]
emit_dir: Option<PathBuf>,
#[arg(long)]
json: bool,
#[arg(long = "only", value_name = "FN")]
only: Vec<String>,
#[arg(long = "allow-opaque", value_name = "FN")]
allow_opaque: Vec<String>,
#[arg(long = "no-strict-types")]
no_strict_types: bool,
},
/// Report inline/opaque/rejected classification (no judging)
Audit {
#[arg(value_name = "FILE")]
file: Option<PathBuf>,
#[arg(long)]
json: bool,
#[arg(long = "only", value_name = "FN")]
only: Vec<String>,
#[arg(long = "allow-opaque", value_name = "FN")]
allow_opaque: Vec<String>,
#[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<i32> {
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<i32> {
}
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/<key8>`。
// 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,
+18 -4
View File
@@ -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<String>, 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();
+684
View File
@@ -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(&param.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::<Vec<_>>()
.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::<Vec<_>>()
.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(&param.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::<Vec<_>>()
.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<String> = items.iter().map(emit_pure).collect();
format!("(Val.list [{}])", inner.join(", "))
}
PureExpr::Map(entries) => {
let inner: Vec<String> = 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<String> = 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<String> = 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<String> {
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<String> = 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())
}
+296
View File
@@ -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<PureExpr>,
right: Box<PureExpr>,
},
Un {
operator: UnOp,
expr: Box<PureExpr>,
},
/// 映射字段/下标读取:`` [键](映射) `` / `` `m`[^键] ``。
Index {
base: Box<PureExpr>,
key: String,
},
/// `access(base, key)`(含 `取`/`取值` 别名)。
Access {
base: Box<PureExpr>,
key: String,
},
/// `len(value)`(含 `长度` 别名)。
Len(Box<PureExpr>),
/// 文本插值拼接(`` "共 `n` 条" `` → append 序列)。
Interp(Vec<InterpPart>),
List(Vec<PureExpr>),
Map(Vec<(String, PureExpr)>),
/// 已内联的构造器调用(`result.success/failure`)。
Ctor {
name: String,
args: Vec<PureExpr>,
},
}
#[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<Step>,
otherwise: Vec<Step>,
line: u32,
},
/// 语句形式调用(`> 调用` / `*语句*`):值丢弃,但仍进轨迹。
Trace {
op: String,
args: Vec<PureExpr>,
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<PureExpr>,
},
/// `$$…$$` 公式:不透明值,不翻译。
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<String>,
pub conclusion: String,
pub tactic: Option<String>,
/// 定理表行号(锚定源码漂移)。
pub line: u32,
}
/// 假设表条目(T3;P0 恒为空)。
#[derive(Debug, Clone, Serialize)]
pub struct AssumptionPlan {
pub op: String,
pub premise: Option<String>,
pub postcondition: String,
}
/// 单个函数的 Plan。
#[derive(Debug, Clone, Serialize)]
pub struct FnPlan {
pub name: String,
pub params: Vec<ParamPlan>,
pub result_ty: PlanTy,
/// 该函数用到的不透明操作(按出现顺序,去重)。
pub ops: Vec<OpDecl>,
pub steps: Vec<Step>,
pub effects: Vec<String>,
pub claims: Vec<ClaimPlan>,
pub assumptions: Vec<AssumptionPlan>,
}
#[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<FnPlan>,
}
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<String> = 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<String> = keys
.into_iter()
.map(|k| {
format!(
"{}:{}",
serde_json::to_string(k).expect("key serializes"),
format_value(&map[k])
)
})
.collect();
format!("{{{}}}", inner.join(","))
}
}
}
+1241
View File
File diff suppressed because it is too large. Load diff
+382
View File
@@ -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<String>,
pub only: Vec<String>,
pub allow_opaque: Vec<String>,
pub emit_dir: Option<PathBuf>,
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>, String, Option<String>)>,
}
/// 整体报告。
#[derive(Debug, Clone)]
pub struct Report {
pub file: String,
pub source_sha256: String,
pub status: Verdict,
pub functions: Vec<FunctionReport>,
pub diagnostics: Vec<Diagnostic>,
pub emitted: Vec<PathBuf>,
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::<Vec<_>>(),
"obligations": [],
"ops": f.ops.iter().map(|(id, effect)| json!({
"id": id, "effect": effect,
})).collect::<Vec<_>>(),
"rejected": f.rejected.iter().map(|(code, message, line)| json!({
"code": code, "message": message, "line": line,
})).collect::<Vec<_>>(),
})).collect::<Vec<_>>(),
"lean": 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<_>>(),
"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<Report> {
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<Diagnostic> = Vec::new();
diagnostics.extend(types::typecheck_plan(&module, &lowered, opts.strict_types));
// ④ 生成(--report-only 时跳过写盘)。
let mut emitted: Vec<PathBuf> = 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<FunctionReport> {
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/<key8>/`(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<usize> {
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()
}
+842
View File
@@ -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<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));
}
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 collect_function_names(module: &Module, out: &mut Vec<String>) {
fn go(funs: &[Function], out: &mut Vec<String>) {
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<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 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<Diagnostic>) {
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<Diagnostic>,
) {
if fun.claims.is_empty() && !has_claims {
return;
}
for param in &fun.params {
if RESERVED_CLAIM_NAMES.contains(&param.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<Diagnostic>,
) {
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<Diagnostic>) {
if fun.claims.is_empty() {
return;
}
let params: Vec<String> = 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,
&params,
false,
out,
);
}
check_claim_expr(module, path, &claim.conclusion, claim, &params, 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<Diagnostic>,
) {
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<Vec<CTok>, String> {
let mut out = Vec::new();
let chars: Vec<char> = 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::<f64>().map_err(|_| "数字解析失败")?));
} else {
out.push(CTok::Int(s.parse::<i64>().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<ClaimAst> },
Bin { op: &'static str, left: Box<ClaimAst>, right: Box<ClaimAst> },
Un { op: &'static str, expr: Box<ClaimAst> },
}
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<CTok> {
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<CTok>, 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<ClaimAst, String> {
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<ClaimAst, String> {
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<ClaimAst, String> {
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<ClaimAst, String> {
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<ClaimAst, String> {
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<ClaimAst, String> {
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<ClaimAst, String> {
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<Diagnostic>,
) {
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:?}");
}
}
+251
View File
@@ -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<Diagnostic>,
}
/// 对一个函数的 steps 做类型检查。
///
/// `params`:形参类型(契约表)。返回收集到的诊断。
pub fn typecheck(
module: &crate::ast::Module,
params: &[(String, PlanTy)],
steps: &[Step],
strict: bool,
) -> Typed {
let mut env: BTreeMap<String, (PlanTy, u32)> = 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<String, (PlanTy, u32)>,
out: &mut Vec<Diagnostic>,
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<String, (PlanTy, u32)>) -> Option<PlanTy> {
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<String, (PlanTy, u32)>) -> Option<PlanTy> {
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 (&lt, &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<PlanTy> {
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<Diagnostic> {
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, &params, &plan.steps, strict);
out.extend(typed.diagnostics);
}
out
}
+6 -2
View File
@@ -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