prove: restricted formula, program models and verified Lean backend
- formula.rs: the only math parser — fixed EBNF, typed Int/Prop AST, bounds, exact diagnostics, Lean target generation and counterexample evaluation - model.rs: complete whitelist validation of the finite exact-integer program subset and deterministic @[expose] Lean model mapping - lean.rs: pinned backend discovery, trusted generated search template, stock lean4export proof payload, independent con-leche kernel replay, expected-proposition regeneration and axiom audit - Replay.lean: verifier executable (type alpha-equivalence, axiom closure, metavariable rejection) without importing any proof olean - prove.rs/main.rs: single check/replay orchestration, reports, exit codes - real E2E: algebra/vector/arithmetic fixtures verify and publish bundles
This commit is contained in:
1 parent
3a529b923d
commit
4e02da95a4
20 files changed
+9077
-27
No files matched your search
@@ -87,6 +87,13 @@ impl ModuleData {
|
||||
}
|
||||
}
|
||||
|
||||
/// Look up a function record by canonical FunctionId.
|
||||
pub fn function(&self, function_id: &str) -> Option<&Function> {
|
||||
self.functions
|
||||
.iter()
|
||||
.find(|function| function.id == function_id)
|
||||
}
|
||||
|
||||
/// Source slice for a span, if the span is valid for this module.
|
||||
pub fn slice(&self, span: Span) -> Option<&str> {
|
||||
if span.is_valid_in(&self.source) {
|
||||
|
||||
@@ -1 +1,611 @@
|
||||
//! Content-addressed proof bundles, manifests and replay (docs/DEVELOPMENT.md §8).
|
||||
//!
|
||||
//! One bundle is one directory with exactly two files: `manifest.json` and the
|
||||
//! Lean proof payload (`proof.ndjson`, the toolchain's own `lean4export`
|
||||
//! format). The manifest binds the current sources, Analysis bytes, target
|
||||
//! proposition, declared dependencies, program models, environment identity and
|
||||
//! the payload digest. A cached `verified: true` flag is never trusted on its
|
||||
//! own: every hit is replayed through the independent verifier before it is
|
||||
//! reported as current.
|
||||
//!
|
||||
//! Bundles are written through an exclusive temporary directory and an atomic
|
||||
//! rename; a failure never leaves a bundle-looking half result.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{codes, sha256_hex, Failure, Result, Span, PROOF_SCHEMA, PROOF_SCHEMA_VERSION};
|
||||
|
||||
/// Directory name of the tool-owned cache inside a project root.
|
||||
pub const CACHE_DIR: &str = ".marqdo/prove";
|
||||
|
||||
pub const MANIFEST_FILE: &str = "manifest.json";
|
||||
pub const PAYLOAD_FILE: &str = "proof.ndjson";
|
||||
|
||||
/// The allowed base axioms of the fixed Lean environment.
|
||||
pub const ALLOWED_AXIOMS: [&str; 3] = ["propext", "Classical.choice", "Quot.sound"];
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ToolIdentity {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SourceBinding {
|
||||
/// Portable package-relative locator of a document participating in the run.
|
||||
pub locator: String,
|
||||
pub module_id: String,
|
||||
pub source_digest: String,
|
||||
pub analysis_digest: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ModelBinding {
|
||||
pub unit_id: String,
|
||||
pub locator: String,
|
||||
pub function_id: String,
|
||||
pub lean_name: String,
|
||||
pub digest: String,
|
||||
pub module_name: String,
|
||||
pub semantics: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DeclaredDependency {
|
||||
pub kind: String,
|
||||
pub locator: String,
|
||||
pub unit_id: String,
|
||||
pub link_text: String,
|
||||
/// Cache key of the dependency bundle for theorem dependencies, or the
|
||||
/// model key for program model dependencies.
|
||||
pub binding: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TargetIdentity {
|
||||
/// Canonical unit id of the Knowledge H2 (never split for identity).
|
||||
pub unit_id: String,
|
||||
pub unit_path: Vec<String>,
|
||||
pub locator: String,
|
||||
/// `mathematical` or `program_model`.
|
||||
pub scope: String,
|
||||
/// `verified` or `refuted`.
|
||||
pub outcome: String,
|
||||
/// Raw display-math payload from the source document.
|
||||
pub statement_literal: String,
|
||||
/// Deterministic human-readable normalized proposition.
|
||||
pub statement_normalized: String,
|
||||
/// Lean source of the proposition as generated by the trusted frontend.
|
||||
pub statement_lean: String,
|
||||
pub goal_span: Span,
|
||||
pub goal_payload_span: Option<Span>,
|
||||
pub goal_digest: String,
|
||||
/// Display premises: the whole antecedent is preserved, never dropped.
|
||||
pub premises: Vec<String>,
|
||||
pub theorem_name: String,
|
||||
pub expected_name: String,
|
||||
/// Non-empty when the target depends on a program model.
|
||||
pub model_definitions: Vec<ModelBinding>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct EnvironmentIdentity {
|
||||
pub lean_toolchain: String,
|
||||
pub lean_version: String,
|
||||
pub mathlib_rev: String,
|
||||
pub lake_manifest_digest: String,
|
||||
pub replay_verifier_digest: String,
|
||||
pub con_leche_version: String,
|
||||
pub formula_compiler: String,
|
||||
pub semantic_mapping: String,
|
||||
/// Content identity over the fields above.
|
||||
pub environment_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProofPayload {
|
||||
pub file: String,
|
||||
pub bytes: u64,
|
||||
pub sha256: String,
|
||||
pub export_format: String,
|
||||
pub target_decl: String,
|
||||
pub expected_decl: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BundleManifest {
|
||||
pub schema: String,
|
||||
pub schema_version: u64,
|
||||
pub tool: ToolIdentity,
|
||||
pub target: TargetIdentity,
|
||||
pub sources: Vec<SourceBinding>,
|
||||
pub environment: EnvironmentIdentity,
|
||||
pub declared_dependencies: Vec<DeclaredDependency>,
|
||||
/// Actual direct project theorem/model declarations used by the proof term.
|
||||
pub used_dependencies: Vec<String>,
|
||||
/// Actual transitive project dependency closure in the payload.
|
||||
pub transitive_dependencies: Vec<String>,
|
||||
pub axioms: Vec<String>,
|
||||
pub proof: ProofPayload,
|
||||
/// Content address of this bundle: every participating identity is hashed.
|
||||
pub cache_key: String,
|
||||
}
|
||||
|
||||
impl BundleManifest {
|
||||
pub fn to_bytes(&self) -> Result<Vec<u8>> {
|
||||
serde_json::to_vec_pretty(self).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!("cannot serialize proof manifest: {error}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Strictly re-validate a manifest read from disk (untrusted data).
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.schema != PROOF_SCHEMA {
|
||||
return invalid(format!("unexpected proof schema `{}`", self.schema));
|
||||
}
|
||||
if self.schema_version != PROOF_SCHEMA_VERSION {
|
||||
return invalid(format!(
|
||||
"proof schema_version {} does not match required {PROOF_SCHEMA_VERSION}",
|
||||
self.schema_version
|
||||
));
|
||||
}
|
||||
if self.tool.name != crate::TOOL_NAME || self.tool.version != env!("CARGO_PKG_VERSION") {
|
||||
return invalid("proof bundle was produced by an incompatible tool version");
|
||||
}
|
||||
if self.target.outcome != "verified" && self.target.outcome != "refuted" {
|
||||
return invalid(format!(
|
||||
"proof target outcome `{}` is not a verifiable outcome",
|
||||
self.target.outcome
|
||||
));
|
||||
}
|
||||
if self.target.scope != "mathematical" && self.target.scope != "program_model" {
|
||||
return invalid(format!("unknown proof scope `{}`", self.target.scope));
|
||||
}
|
||||
if self.target.locator.is_empty() || self.target.unit_id.is_empty() {
|
||||
return invalid("proof target has an empty unit identity");
|
||||
}
|
||||
if !is_hex_sha256(&self.target.goal_digest) {
|
||||
return invalid("proof target goal_digest is not a canonical sha256 digest");
|
||||
}
|
||||
if self.proof.file != PAYLOAD_FILE {
|
||||
return invalid(format!("unexpected proof payload file `{}`", self.proof.file));
|
||||
}
|
||||
if !is_hex_sha256(&self.proof.sha256) {
|
||||
return invalid("proof payload sha256 is not a canonical digest");
|
||||
}
|
||||
if self.proof.target_decl != self.target.theorem_name
|
||||
|| self.proof.expected_decl != self.target.expected_name
|
||||
{
|
||||
return invalid("proof payload declaration names are not bound to the target identity");
|
||||
}
|
||||
if self.sources.is_empty() {
|
||||
return invalid("proof bundle has no source bindings");
|
||||
}
|
||||
for source in &self.sources {
|
||||
if source.locator.is_empty()
|
||||
|| !is_hex_sha256(&source.source_digest)
|
||||
|| !is_hex_sha256(&source.analysis_digest)
|
||||
{
|
||||
return invalid("proof source binding is malformed");
|
||||
}
|
||||
}
|
||||
let mut sorted = self.sources.clone();
|
||||
sorted.sort_by(|left, right| left.locator.cmp(&right.locator));
|
||||
if sorted
|
||||
.iter()
|
||||
.zip(&self.sources)
|
||||
.any(|(left, right)| left.locator != right.locator)
|
||||
{
|
||||
return invalid("proof sources are not sorted by locator");
|
||||
}
|
||||
for axiom in &self.axioms {
|
||||
if !ALLOWED_AXIOMS.contains(&axiom.as_str()) {
|
||||
return invalid(format!("proof bundle reports untrusted axiom `{axiom}`"));
|
||||
}
|
||||
}
|
||||
let mut sorted_axioms = self.axioms.clone();
|
||||
sorted_axioms.sort();
|
||||
sorted_axioms.dedup();
|
||||
if sorted_axioms != self.axioms {
|
||||
return invalid("proof axioms are not sorted and deduplicated");
|
||||
}
|
||||
if !is_hex_sha256(&self.cache_key) {
|
||||
return invalid("proof cache_key is not a canonical sha256 digest");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One loaded bundle: manifest plus payload bytes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Bundle {
|
||||
pub directory: PathBuf,
|
||||
pub manifest: BundleManifest,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Bundle {
|
||||
pub fn load(directory: &Path) -> Result<Bundle> {
|
||||
let manifest_path = directory.join(MANIFEST_FILE);
|
||||
let payload_path = directory.join(PAYLOAD_FILE);
|
||||
let manifest_bytes = std::fs::read(&manifest_path).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!("cannot read `{}`: {error}", manifest_path.display()),
|
||||
)
|
||||
})?;
|
||||
if manifest_bytes.len() > 4 * 1024 * 1024 {
|
||||
return invalid("proof manifest is unreasonably large");
|
||||
}
|
||||
let manifest: BundleManifest = serde_json::from_slice(&manifest_bytes).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!(
|
||||
"`{}` does not match the current marqdo.proof revision 1 shape: {error}",
|
||||
manifest_path.display()
|
||||
),
|
||||
)
|
||||
.with_hint("delete the generated cache entry and re-run `check`; there is no migration")
|
||||
})?;
|
||||
manifest.validate()?;
|
||||
let payload = std::fs::read(&payload_path).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!("cannot read proof payload `{}`: {error}", payload_path.display()),
|
||||
)
|
||||
})?;
|
||||
if payload.len() as u64 != manifest.proof.bytes {
|
||||
return invalid("proof payload byte count does not match the manifest");
|
||||
}
|
||||
if payload.len() as u64 > crate::limits::MAX_PROOF_BYTES {
|
||||
return invalid("proof payload is larger than the allowed limit");
|
||||
}
|
||||
let digest = sha256_hex(&payload);
|
||||
if digest != manifest.proof.sha256 {
|
||||
return invalid("proof payload SHA-256 does not match the manifest");
|
||||
}
|
||||
Ok(Bundle {
|
||||
directory: directory.to_path_buf(),
|
||||
manifest,
|
||||
payload,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_to(&self, directory: &Path) -> Result<()> {
|
||||
publish_manifest_and_payload(directory, &self.manifest, &self.payload)
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity inputs for a content-addressed cache key.
|
||||
pub struct CacheIdentity {
|
||||
pub target_locator: String,
|
||||
pub target_unit_id: String,
|
||||
pub goal_digest: String,
|
||||
pub scope: String,
|
||||
pub sources: Vec<(String, String, String)>,
|
||||
pub environment_id: String,
|
||||
pub declared: Vec<(String, String, String, String)>,
|
||||
pub models: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl CacheIdentity {
|
||||
/// Deterministic content address over every participating identity.
|
||||
pub fn cache_key(&self) -> String {
|
||||
let mut buffer = String::new();
|
||||
buffer.push_str("marqdo-prove/cache/v1\n");
|
||||
buffer.push_str(crate::TOOL_NAME);
|
||||
buffer.push('\n');
|
||||
buffer.push_str(env!("CARGO_PKG_VERSION"));
|
||||
buffer.push('\n');
|
||||
buffer.push_str(&self.environment_id);
|
||||
buffer.push('\n');
|
||||
buffer.push_str(&self.scope);
|
||||
buffer.push('\n');
|
||||
buffer.push_str(&self.target_locator);
|
||||
buffer.push('\n');
|
||||
buffer.push_str(&self.target_unit_id);
|
||||
buffer.push('\n');
|
||||
buffer.push_str(&self.goal_digest);
|
||||
buffer.push('\n');
|
||||
let mut sources = self.sources.clone();
|
||||
sources.sort();
|
||||
for (locator, source_digest, analysis_digest) in sources {
|
||||
buffer.push_str(&format!("source:{locator}\0{source_digest}\0{analysis_digest}\n"));
|
||||
}
|
||||
let mut declared = self.declared.clone();
|
||||
declared.sort();
|
||||
for (kind, locator, unit_id, binding) in declared {
|
||||
buffer.push_str(&format!("dep:{kind}\0{locator}\0{unit_id}\0{binding}\n"));
|
||||
}
|
||||
let mut models = self.models.clone();
|
||||
models.sort();
|
||||
for (function_id, digest) in models {
|
||||
buffer.push_str(&format!("model:{function_id}\0{digest}\n"));
|
||||
}
|
||||
sha256_hex(buffer.as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// Tool-owned, content-addressed cache under `<project>/.marqdo/prove/`.
|
||||
pub struct CacheStore {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl CacheStore {
|
||||
pub fn new(project_root: &Path) -> CacheStore {
|
||||
Self {
|
||||
root: project_root.join(CACHE_DIR),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub fn bundle_dir(&self, cache_key: &str) -> PathBuf {
|
||||
self.root.join("bundles").join(cache_key)
|
||||
}
|
||||
|
||||
pub fn artifacts_dir(&self) -> PathBuf {
|
||||
self.root.join("artifacts")
|
||||
}
|
||||
|
||||
pub fn work_dir(&self) -> PathBuf {
|
||||
self.root.join("work")
|
||||
}
|
||||
|
||||
/// Look up a bundle by content address. A mismatching manifest is not a
|
||||
/// cache hit; it is left in place for inspection but reported as stale.
|
||||
pub fn lookup(&self, cache_key: &str) -> Option<Bundle> {
|
||||
let directory = self.bundle_dir(cache_key);
|
||||
if !directory.is_dir() {
|
||||
return None;
|
||||
}
|
||||
match Bundle::load(&directory) {
|
||||
Ok(bundle) if bundle.manifest.cache_key == cache_key => Some(bundle),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish a bundle atomically. Returns the cache key it was stored under.
|
||||
pub fn publish(&self, manifest: &BundleManifest, payload: &[u8]) -> Result<PathBuf> {
|
||||
let directory = self.bundle_dir(&manifest.cache_key);
|
||||
if directory.is_dir() {
|
||||
// Replace only if the identity is identical; otherwise the caller
|
||||
// has a key collision, which is never acceptable.
|
||||
if let Ok(existing) = Bundle::load(&directory) {
|
||||
if existing.manifest.cache_key == manifest.cache_key
|
||||
&& existing.manifest.proof.sha256 == manifest.proof.sha256
|
||||
{
|
||||
return Ok(directory);
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&directory).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!("cannot replace stale cache entry `{}`: {error}", directory.display()),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
publish_manifest_and_payload(&directory, manifest, payload)?;
|
||||
Ok(directory)
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_manifest_and_payload(
|
||||
directory: &Path,
|
||||
manifest: &BundleManifest,
|
||||
payload: &[u8],
|
||||
) -> Result<()> {
|
||||
if directory.exists() {
|
||||
return invalid(format!(
|
||||
"refusing to overwrite existing bundle directory `{}`",
|
||||
directory.display()
|
||||
));
|
||||
}
|
||||
let parent = directory.parent().ok_or_else(|| {
|
||||
Failure::new(codes::CERTIFICATE_INVALID, "bundle directory has no parent")
|
||||
})?;
|
||||
std::fs::create_dir_all(parent).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!("cannot create bundle parent `{}`: {error}", parent.display()),
|
||||
)
|
||||
})?;
|
||||
let unique = format!(
|
||||
".tmp-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0)
|
||||
);
|
||||
let temporary = parent.join(unique);
|
||||
std::fs::create_dir(&temporary).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!("cannot create temporary bundle `{}`: {error}", temporary.display()),
|
||||
)
|
||||
})?;
|
||||
let result = (|| -> Result<()> {
|
||||
let manifest_bytes = manifest.to_bytes()?;
|
||||
write_file(&temporary.join(MANIFEST_FILE), &manifest_bytes)?;
|
||||
write_file(&temporary.join(PAYLOAD_FILE), payload)?;
|
||||
std::fs::rename(&temporary, directory).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!(
|
||||
"cannot publish bundle `{}` atomically: {error}",
|
||||
directory.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_dir_all(&temporary);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn write_file(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
use std::io::Write;
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(path).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!("cannot create `{}`: {error}", path.display()),
|
||||
)
|
||||
})?;
|
||||
file.write_all(bytes)
|
||||
.and_then(|()| file.sync_all())
|
||||
.map_err(|error| {
|
||||
Failure::new(
|
||||
codes::CERTIFICATE_INVALID,
|
||||
format!("cannot write `{}`: {error}", path.display()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn is_hex_sha256(value: &str) -> bool {
|
||||
value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
|
||||
}
|
||||
|
||||
fn invalid<T>(message: impl Into<String>) -> Result<T> {
|
||||
Err(Failure::new(codes::CERTIFICATE_INVALID, message.into()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn manifest() -> BundleManifest {
|
||||
BundleManifest {
|
||||
schema: PROOF_SCHEMA.to_string(),
|
||||
schema_version: PROOF_SCHEMA_VERSION,
|
||||
tool: ToolIdentity {
|
||||
name: crate::TOOL_NAME.to_string(),
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
},
|
||||
target: TargetIdentity {
|
||||
unit_id: "root:t::a.mq.md#A".to_string(),
|
||||
unit_path: vec!["A".to_string()],
|
||||
locator: "a.mq.md".to_string(),
|
||||
scope: "mathematical".to_string(),
|
||||
outcome: "verified".to_string(),
|
||||
statement_literal: "x = 1".to_string(),
|
||||
statement_normalized: "x = 1".to_string(),
|
||||
statement_lean: "(1 : Int) = (1 : Int)".to_string(),
|
||||
goal_span: Span::new(1, 2),
|
||||
goal_payload_span: None,
|
||||
goal_digest: sha256_hex(b"x = 1"),
|
||||
premises: vec![],
|
||||
theorem_name: "marqdoTarget_abc".to_string(),
|
||||
expected_name: "marqdoExpected_abc".to_string(),
|
||||
model_definitions: vec![],
|
||||
},
|
||||
sources: vec![SourceBinding {
|
||||
locator: "a.mq.md".to_string(),
|
||||
module_id: "root:t::a.mq.md".to_string(),
|
||||
source_digest: sha256_hex(b"# A\n"),
|
||||
analysis_digest: sha256_hex(b"{}"),
|
||||
}],
|
||||
environment: EnvironmentIdentity {
|
||||
lean_toolchain: "leanprover/lean4:v4.36.0".to_string(),
|
||||
lean_version: "4.36.0".to_string(),
|
||||
mathlib_rev: "fc4f59e".to_string(),
|
||||
lake_manifest_digest: sha256_hex(b"manifest"),
|
||||
replay_verifier_digest: sha256_hex(b"replay"),
|
||||
con_leche_version: "0.1".to_string(),
|
||||
formula_compiler: "marqdo-prove".to_string(),
|
||||
semantic_mapping: "int-exact-v1".to_string(),
|
||||
environment_id: sha256_hex(b"env"),
|
||||
},
|
||||
declared_dependencies: vec![],
|
||||
used_dependencies: vec![],
|
||||
transitive_dependencies: vec![],
|
||||
axioms: vec!["propext".to_string()],
|
||||
proof: ProofPayload {
|
||||
file: PAYLOAD_FILE.to_string(),
|
||||
bytes: 3,
|
||||
sha256: sha256_hex(b"abc"),
|
||||
export_format: "lean4export-3.1.0".to_string(),
|
||||
target_decl: "marqdoTarget_abc".to_string(),
|
||||
expected_decl: "marqdoExpected_abc".to_string(),
|
||||
},
|
||||
cache_key: sha256_hex(b"key"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_a_well_formed_manifest() {
|
||||
manifest().validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_untrusted_axioms_and_bad_revision() {
|
||||
let mut m = manifest();
|
||||
m.axioms = vec!["sorryAx".to_string()];
|
||||
assert_eq!(m.validate().unwrap_err().code, codes::CERTIFICATE_INVALID);
|
||||
let mut m = manifest();
|
||||
m.schema_version = 2;
|
||||
assert!(m.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_payload_digest_mismatch_when_loading() {
|
||||
let root = std::env::temp_dir().join(format!("marqdo-prove-cert-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let mut m = manifest();
|
||||
let payload = b"abc".to_vec();
|
||||
m.proof.bytes = payload.len() as u64;
|
||||
m.proof.sha256 = sha256_hex(&payload);
|
||||
let directory = root.join("bundle");
|
||||
m.cache_key = sha256_hex(b"k");
|
||||
publish_manifest_and_payload(&directory, &m, &payload).unwrap();
|
||||
let loaded = Bundle::load(&directory).unwrap();
|
||||
assert_eq!(loaded.payload, payload);
|
||||
// Tamper the payload on disk.
|
||||
std::fs::write(directory.join(PAYLOAD_FILE), b"abd").unwrap();
|
||||
let error = Bundle::load(&directory).unwrap_err();
|
||||
assert_eq!(error.code, codes::CERTIFICATE_INVALID);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_key_is_deterministic_and_identity_sensitive() {
|
||||
let mut identity = CacheIdentity {
|
||||
target_locator: "a.mq.md".to_string(),
|
||||
target_unit_id: "root:t::a.mq.md#A".to_string(),
|
||||
goal_digest: sha256_hex(b"goal"),
|
||||
scope: "mathematical".to_string(),
|
||||
sources: vec![("a.mq.md".to_string(), sha256_hex(b"s"), sha256_hex(b"a"))],
|
||||
environment_id: sha256_hex(b"env"),
|
||||
declared: vec![],
|
||||
models: vec![],
|
||||
};
|
||||
let first = identity.cache_key();
|
||||
assert_eq!(first, identity.cache_key());
|
||||
identity.goal_digest = sha256_hex(b"other goal");
|
||||
assert_ne!(first, identity.cache_key());
|
||||
}
|
||||
}
|
||||
+2780
-1
File diff suppressed because it is too large.
Load diff
+1211
File diff suppressed because it is too large.
Load diff
+863
@@ -1 +1,864 @@
|
||||
//! Controlled multi-entry catalog, exact link resolution and dependency DAG.
|
||||
//!
|
||||
//! The linker is the only component that decides *which* local documents are
|
||||
//! read besides the entry: every dependency link must resolve to a selected
|
||||
//! Knowledge H2 (a theorem) or to an Exec H2 declaring a function (a program
|
||||
//! model). It never guesses from names, never follows a link to an arbitrary
|
||||
//! file, never leaves the explicit root, and never reads raw Markdown itself —
|
||||
//! each new document is loaded through the real CLI's Analysis.
|
||||
//!
|
||||
//! Depth, breadth, file count and total source size are bounded. Cycles are
|
||||
//! detected with the exact reference chain.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::analysis::{
|
||||
AnalysisBackend, FragmentResolution, Function, ModuleData, Snapshot, Unit,
|
||||
};
|
||||
use crate::document::{self, DependencyLink, Extraction, ProofUnit};
|
||||
use crate::{codes, Diagnostic, Failure, Span};
|
||||
|
||||
/// A selected dependency target.
|
||||
#[derive(Clone)]
|
||||
pub enum DependencyTarget {
|
||||
/// Another selected Knowledge H2 that must itself be verified.
|
||||
Theorem {
|
||||
snapshot: Arc<Snapshot>,
|
||||
unit_id: String,
|
||||
proof_unit: Box<ProofUnit>,
|
||||
},
|
||||
/// An Exec H2 declaring a function used by formula model calls.
|
||||
Model {
|
||||
snapshot: Arc<Snapshot>,
|
||||
unit_id: String,
|
||||
function: Box<Function>,
|
||||
},
|
||||
}
|
||||
|
||||
impl DependencyTarget {
|
||||
pub fn kind_name(&self) -> &'static str {
|
||||
match self {
|
||||
DependencyTarget::Theorem { .. } => "theorem",
|
||||
DependencyTarget::Model { .. } => "model",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> &Arc<Snapshot> {
|
||||
match self {
|
||||
DependencyTarget::Theorem { snapshot, .. } | DependencyTarget::Model { snapshot, .. } => {
|
||||
snapshot
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unit_id(&self) -> &str {
|
||||
match self {
|
||||
DependencyTarget::Theorem { unit_id, .. } | DependencyTarget::Model { unit_id, .. } => {
|
||||
unit_id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Portable locator: `relative_path#fragment-of-unit`.
|
||||
pub fn locator(&self) -> String {
|
||||
let fragment = match self {
|
||||
DependencyTarget::Theorem { snapshot, unit_id, .. }
|
||||
| DependencyTarget::Model { snapshot, unit_id, .. } => snapshot
|
||||
.modules
|
||||
.values()
|
||||
.find_map(|module| module.unit(unit_id).map(|unit| (module, unit)))
|
||||
.map(|(module, unit)| format!("{}#{}", module.relative_path, unit.name))
|
||||
.unwrap_or_else(|| unit_id.clone()),
|
||||
};
|
||||
fragment
|
||||
}
|
||||
}
|
||||
|
||||
/// One dependency link resolved to its exact target.
|
||||
#[derive(Clone)]
|
||||
pub struct ResolvedDependency {
|
||||
pub link: DependencyLink,
|
||||
pub target: DependencyTarget,
|
||||
}
|
||||
|
||||
/// One proof unit together with its document and resolved dependencies.
|
||||
#[derive(Clone)]
|
||||
pub struct LoadedUnit {
|
||||
pub snapshot: Arc<Snapshot>,
|
||||
pub module: Arc<ModuleData>,
|
||||
pub proof_unit: ProofUnit,
|
||||
pub dependencies: Vec<ResolvedDependency>,
|
||||
/// Diagnostics raised while resolving this unit's declared links. A unit
|
||||
/// with any diagnostic is never a candidate for verification.
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
impl LoadedUnit {
|
||||
/// Stable in-run key: canonical physical path plus unit id.
|
||||
pub fn internal_key(&self) -> (PathBuf, String) {
|
||||
(self.snapshot.canonical_path.clone(), self.proof_unit.unit_id.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// The loaded dependency closure of one entry selection.
|
||||
pub struct Closure {
|
||||
pub root: PathBuf,
|
||||
/// Units in dependency-first (topological) order.
|
||||
pub units: Vec<LoadedUnit>,
|
||||
pub documents: BTreeMap<PathBuf, Arc<Snapshot>>,
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
/// Cycles as concrete reference chains.
|
||||
pub cycles: Vec<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Closure {
|
||||
pub fn unit(&self, path: &Path, unit_id: &str) -> Option<&LoadedUnit> {
|
||||
self.units
|
||||
.iter()
|
||||
.find(|unit| unit.snapshot.canonical_path == path && unit.proof_unit.unit_id == unit_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Multi-entry catalog bound to one controlled local root.
|
||||
pub struct Linker {
|
||||
backend: AnalysisBackend,
|
||||
root: PathBuf,
|
||||
documents: BTreeMap<PathBuf, Arc<Snapshot>>,
|
||||
extraction_cache: BTreeMap<PathBuf, BTreeMap<String, Extraction>>,
|
||||
stats: CatalogStats,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CatalogStats {
|
||||
documents: usize,
|
||||
source_bytes: u64,
|
||||
}
|
||||
|
||||
/// Limits for one catalog walk.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CatalogLimits {
|
||||
pub documents: usize,
|
||||
pub units: usize,
|
||||
pub depth: usize,
|
||||
pub source_bytes: u64,
|
||||
}
|
||||
|
||||
impl Default for CatalogLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
documents: crate::limits::MAX_DOCUMENTS,
|
||||
units: crate::limits::MAX_UNITS,
|
||||
depth: crate::limits::MAX_DEPTH,
|
||||
source_bytes: crate::limits::MAX_SOURCE_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Linker {
|
||||
pub fn new(backend: AnalysisBackend, root: PathBuf) -> Result<Self, Failure> {
|
||||
let root = std::fs::canonicalize(&root).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::LINK_OUTSIDE_ROOT,
|
||||
format!("cannot canonicalize the controlled root `{}`: {error}", root.display()),
|
||||
)
|
||||
})?;
|
||||
Ok(Self {
|
||||
backend,
|
||||
root,
|
||||
documents: BTreeMap::new(),
|
||||
extraction_cache: BTreeMap::new(),
|
||||
stats: CatalogStats::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub fn backend(&self) -> &AnalysisBackend {
|
||||
&self.backend
|
||||
}
|
||||
|
||||
/// Load the entry document (or `--root`-bounded path).
|
||||
pub fn load_document(&mut self, path: &Path) -> Result<Arc<Snapshot>, Failure> {
|
||||
let canonical = std::fs::canonicalize(path).map_err(|error| {
|
||||
Failure::new(
|
||||
codes::LINK_MISSING,
|
||||
format!("cannot resolve document `{}`: {error}", path.display()),
|
||||
)
|
||||
})?;
|
||||
if !canonical.starts_with(&self.root) {
|
||||
return Err(Failure::new(
|
||||
codes::LINK_OUTSIDE_ROOT,
|
||||
format!(
|
||||
"document `{}` is outside the controlled root `{}`",
|
||||
canonical.display(),
|
||||
self.root.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
if let Some(existing) = self.documents.get(&canonical) {
|
||||
return Ok(existing.clone());
|
||||
}
|
||||
let snapshot = self.backend.load(&canonical, &self.root)?;
|
||||
self.stats.documents += 1;
|
||||
self.stats.source_bytes += snapshot
|
||||
.modules
|
||||
.values()
|
||||
.map(|module| module.source.len() as u64)
|
||||
.sum::<u64>();
|
||||
if self.stats.documents > CatalogLimits::default().documents {
|
||||
return Err(Failure::new(
|
||||
codes::LINK_MISSING,
|
||||
format!(
|
||||
"catalog loaded more than {} documents",
|
||||
CatalogLimits::default().documents
|
||||
),
|
||||
));
|
||||
}
|
||||
if self.stats.source_bytes > CatalogLimits::default().source_bytes {
|
||||
return Err(Failure::new(
|
||||
codes::LINK_MISSING,
|
||||
format!(
|
||||
"catalog source bytes exceed the {} byte budget",
|
||||
CatalogLimits::default().source_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
self.documents.insert(canonical, snapshot.clone());
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// Extract proof units for one entry snapshot (public frontend for the
|
||||
/// orchestration layer; results include invalid candidates).
|
||||
pub fn extract_units(&mut self, snapshot: &Arc<Snapshot>) -> Vec<Extraction> {
|
||||
let path = snapshot.canonical_path.clone();
|
||||
let module = snapshot.entry().clone();
|
||||
document::extract(&module)
|
||||
.into_iter()
|
||||
.map(|extraction| {
|
||||
if let Extraction::Invalid(diagnostic) = &extraction {
|
||||
self.extraction_cache
|
||||
.entry(path.clone())
|
||||
.or_default()
|
||||
.insert(format!("invalid@{}", diagnostic.span.map(|s| s.start).unwrap_or(0)), extraction.clone());
|
||||
}
|
||||
extraction
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Extract proof units for one loaded module, cached per document.
|
||||
fn extraction(&mut self, module: &ModuleData, path: &Path) -> BTreeMap<String, Extraction> {
|
||||
if let Some(cached) = self.extraction_cache.get(path) {
|
||||
return cached.clone();
|
||||
}
|
||||
let mut map = BTreeMap::new();
|
||||
for extraction in document::extract(module) {
|
||||
let unit_id = match &extraction {
|
||||
Extraction::Unit(unit) => unit.unit_id.clone(),
|
||||
Extraction::Invalid(_) => continue,
|
||||
};
|
||||
map.insert(unit_id, extraction);
|
||||
}
|
||||
self.extraction_cache.insert(path.to_path_buf(), map.clone());
|
||||
map
|
||||
}
|
||||
|
||||
/// Resolve the transitive dependency closure for the selected entry units.
|
||||
///
|
||||
/// `selection` is the explicit list of entry unit ids (empty = every
|
||||
/// extracted proof unit). Returns units in dependency-first order.
|
||||
pub fn resolve_closure(
|
||||
&mut self,
|
||||
entry: &Arc<Snapshot>,
|
||||
selection: &[String],
|
||||
) -> Result<Closure, Failure> {
|
||||
let entry_path = entry.canonical_path.clone();
|
||||
let extraction = self.extraction(&entry.entry(), &entry_path);
|
||||
let mut diagnostics: Vec<Diagnostic> = Vec::new();
|
||||
|
||||
// Selected entry units.
|
||||
let mut roots: Vec<String> = Vec::new();
|
||||
if selection.is_empty() {
|
||||
for (unit_id, extraction) in &extraction {
|
||||
match extraction {
|
||||
Extraction::Unit(_) => roots.push(unit_id.clone()),
|
||||
Extraction::Invalid(diagnostic) => diagnostics.push(diagnostic.clone()),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let available: BTreeSet<&String> = extraction.keys().collect();
|
||||
for unit_id in selection {
|
||||
if available.contains(unit_id) {
|
||||
roots.push(unit_id.clone());
|
||||
} else {
|
||||
diagnostics.push(Diagnostic::error(
|
||||
codes::DOCUMENT_UNIT,
|
||||
format!("selected unit `{unit_id}` is not a valid proof unit of the entry"),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut loader = ClosureLoader {
|
||||
linker: self,
|
||||
documents: BTreeMap::new(),
|
||||
units: HashMap::new(),
|
||||
diagnostics,
|
||||
depth: 0,
|
||||
};
|
||||
loader.documents.insert(entry_path.clone(), entry.clone());
|
||||
for unit_id in roots {
|
||||
loader.load_unit(entry.clone(), &unit_id, 0)?;
|
||||
}
|
||||
let ClosureLoader {
|
||||
documents,
|
||||
units,
|
||||
mut diagnostics,
|
||||
..
|
||||
} = loader;
|
||||
let mut closure = Closure {
|
||||
root: self.root.clone(),
|
||||
units: Vec::new(),
|
||||
documents,
|
||||
diagnostics: Vec::new(),
|
||||
cycles: Vec::new(),
|
||||
};
|
||||
// Topological order with three-colour DFS over theorem dependencies.
|
||||
let mut order: Vec<(PathBuf, String)> = Vec::new();
|
||||
let mut state: HashMap<(PathBuf, String), u8> = HashMap::new();
|
||||
let mut stack: Vec<(PathBuf, String)> = Vec::new();
|
||||
let keys: Vec<(PathBuf, String)> = units.keys().cloned().collect();
|
||||
// Deterministic start order: document path, then unit id.
|
||||
let mut keys = keys;
|
||||
keys.sort();
|
||||
for key in keys {
|
||||
visit(
|
||||
&units,
|
||||
&key,
|
||||
&mut state,
|
||||
&mut order,
|
||||
&mut stack,
|
||||
&mut closure.cycles,
|
||||
);
|
||||
}
|
||||
let mut loaded: Vec<LoadedUnit> = Vec::new();
|
||||
for key in order {
|
||||
if let Some(unit) = units.get(&key) {
|
||||
loaded.push(unit.clone());
|
||||
}
|
||||
}
|
||||
// Any unit not reached by the DFS (should not happen) is appended in a
|
||||
// deterministic order rather than silently dropped.
|
||||
let mut remaining: Vec<(PathBuf, String)> = units.keys().cloned().collect();
|
||||
remaining.sort();
|
||||
for key in remaining {
|
||||
if !loaded.iter().any(|unit| unit.internal_key() == key) {
|
||||
if let Some(unit) = units.get(&key) {
|
||||
loaded.push(unit.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
diagnostics.extend(std::mem::take(&mut closure.cycles).into_iter().map(|cycle| {
|
||||
Diagnostic::error(
|
||||
codes::LINK_CYCLE,
|
||||
format!("dependency cycle: {}", cycle.join(" -> ")),
|
||||
)
|
||||
.with_hint(
|
||||
"remove the cycle; first-release knowledge is a DAG, mathematical induction is \
|
||||
not expressed through file dependencies",
|
||||
)
|
||||
}));
|
||||
closure.diagnostics.extend(diagnostics);
|
||||
closure.units = loaded;
|
||||
Ok(closure)
|
||||
}
|
||||
|
||||
/// Resolve one link in one loaded module.
|
||||
fn resolve_link(
|
||||
&mut self,
|
||||
source_path: &Path,
|
||||
source: &Arc<Snapshot>,
|
||||
module: &Arc<ModuleData>,
|
||||
link: &DependencyLink,
|
||||
) -> std::result::Result<ResolvedDependency, Diagnostic> {
|
||||
let reference = module
|
||||
.references
|
||||
.iter()
|
||||
.find(|reference| reference.span == link.link_span)
|
||||
.ok_or_else(|| {
|
||||
Diagnostic::error(
|
||||
codes::LINK_INVALID,
|
||||
format!(
|
||||
"link `{}` has no matching reference record in the current Analysis",
|
||||
link.url
|
||||
),
|
||||
)
|
||||
.at(link.link_span)
|
||||
})?;
|
||||
match reference.state.as_str() {
|
||||
"resolved" => {
|
||||
let target_module_id = reference.target_module.clone().ok_or_else(|| {
|
||||
link_error(link, codes::LINK_INVALID, "resolved link has no target module")
|
||||
})?;
|
||||
let target_module = source.modules.get(&target_module_id).cloned().ok_or_else(|| {
|
||||
link_error(
|
||||
link,
|
||||
codes::LINK_CONTEXT_CONFLICT,
|
||||
format!("link target module `{target_module_id}` is not in the loaded snapshot"),
|
||||
)
|
||||
})?;
|
||||
let Some(target_unit_id) = reference.target_unit.clone() else {
|
||||
return Err(link_error(
|
||||
link,
|
||||
codes::LINK_INVALID,
|
||||
"dependency link must address a Knowledge H2 or Exec H2, not the document root",
|
||||
));
|
||||
};
|
||||
let target = self.classify_target(
|
||||
source.clone(),
|
||||
target_module,
|
||||
&target_unit_id,
|
||||
link,
|
||||
source_path,
|
||||
)?;
|
||||
Ok(ResolvedDependency {
|
||||
link: link.clone(),
|
||||
target,
|
||||
})
|
||||
}
|
||||
"not_loaded" => {
|
||||
let candidate_path = reference.candidate_path.clone().ok_or_else(|| {
|
||||
link_error(link, codes::LINK_INVALID, "local link has no package-relative path")
|
||||
})?;
|
||||
validate_relative_path(&candidate_path)
|
||||
.map_err(|message| link_error(link, codes::LINK_INVALID, message))?;
|
||||
if reference.candidate_package_instance_id.as_deref()
|
||||
!= Some(module.package_instance_id.as_str())
|
||||
{
|
||||
return Err(link_error(
|
||||
link,
|
||||
codes::LINK_INVALID,
|
||||
"cross-package dependency links are not supported in the first release; \
|
||||
provide a local document inside the controlled root",
|
||||
));
|
||||
}
|
||||
let physical = self.root.join(&candidate_path);
|
||||
let snapshot = self.load_document(&physical).map_err(|failure| {
|
||||
link_error(link, failure.code, failure.message)
|
||||
})?;
|
||||
let target_module = snapshot
|
||||
.module_by_relative_path(&candidate_path)
|
||||
.cloned()
|
||||
.or_else(|| {
|
||||
snapshot
|
||||
.modules
|
||||
.values()
|
||||
.find(|candidate| candidate.relative_path == candidate_path)
|
||||
.cloned()
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
link_error(
|
||||
link,
|
||||
codes::LINK_CONTEXT_CONFLICT,
|
||||
format!("loaded document `{candidate_path}` does not expose that module path"),
|
||||
)
|
||||
})?;
|
||||
// Verify context compatibility (same root, same lock/manifest).
|
||||
if snapshot.project.identity_kind != source.project.identity_kind
|
||||
|| snapshot.project.lock_digest != source.project.lock_digest
|
||||
|| snapshot.project.manifest_digest != source.project.manifest_digest
|
||||
{
|
||||
return Err(link_error(
|
||||
link,
|
||||
codes::LINK_CONTEXT_CONFLICT,
|
||||
format!(
|
||||
"document `{candidate_path}` has an incompatible project context"
|
||||
),
|
||||
));
|
||||
}
|
||||
let fragment = reference.fragment.clone().unwrap_or_default();
|
||||
let target_unit_id = match target_module.resolve_fragment(&fragment) {
|
||||
FragmentResolution::Unit(unit_id) => unit_id,
|
||||
FragmentResolution::DocumentRoot => {
|
||||
return Err(link_error(
|
||||
link,
|
||||
codes::LINK_INVALID,
|
||||
"dependency link must include a non-empty heading fragment",
|
||||
))
|
||||
}
|
||||
FragmentResolution::Missing => {
|
||||
return Err(link_error(
|
||||
link,
|
||||
codes::LINK_MISSING,
|
||||
format!(
|
||||
"`{candidate_path}` has no anchor or exact heading name `{fragment}`"
|
||||
),
|
||||
))
|
||||
}
|
||||
FragmentResolution::Ambiguous(candidates) => {
|
||||
return Err(link_error(
|
||||
link,
|
||||
codes::LINK_AMBIGUOUS,
|
||||
format!(
|
||||
"fragment `{fragment}` in `{candidate_path}` matches multiple units: {}",
|
||||
candidates.join(", ")
|
||||
),
|
||||
))
|
||||
}
|
||||
};
|
||||
let target_path = snapshot.canonical_path.clone();
|
||||
let target = self.classify_target(
|
||||
snapshot,
|
||||
target_module,
|
||||
&target_unit_id,
|
||||
link,
|
||||
&target_path,
|
||||
)?;
|
||||
Ok(ResolvedDependency {
|
||||
link: link.clone(),
|
||||
target,
|
||||
})
|
||||
}
|
||||
"missing" => Err(link_error(
|
||||
link,
|
||||
codes::LINK_MISSING,
|
||||
format!("dependency target `{}` does not exist", link.url),
|
||||
)),
|
||||
"ambiguous" => Err(link_error(
|
||||
link,
|
||||
codes::LINK_AMBIGUOUS,
|
||||
format!(
|
||||
"dependency target `{}` matches multiple exact headings: {}",
|
||||
link.url,
|
||||
reference.candidates.join(", ")
|
||||
),
|
||||
)),
|
||||
"outside_scope" => Err(link_error(
|
||||
link,
|
||||
codes::LINK_OUTSIDE_ROOT,
|
||||
format!("dependency link `{}` escapes the controlled root", link.url),
|
||||
)),
|
||||
"invalid" => Err(link_error(
|
||||
link,
|
||||
codes::LINK_INVALID,
|
||||
format!("dependency link `{}` is not a valid local document link", link.url),
|
||||
)),
|
||||
"external" => Err(link_error(
|
||||
link,
|
||||
codes::LINK_INVALID,
|
||||
format!(
|
||||
"dependency link `{}` is external; Prove never fetches remote knowledge",
|
||||
link.url
|
||||
),
|
||||
)),
|
||||
other => Err(link_error(
|
||||
link,
|
||||
codes::LINK_INVALID,
|
||||
format!("link has unknown Analysis state `{other}`"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_target(
|
||||
&mut self,
|
||||
snapshot: Arc<Snapshot>,
|
||||
module: Arc<ModuleData>,
|
||||
target_unit_id: &str,
|
||||
link: &DependencyLink,
|
||||
target_path: &Path,
|
||||
) -> std::result::Result<DependencyTarget, Diagnostic> {
|
||||
let unit = module.unit(target_unit_id).ok_or_else(|| {
|
||||
link_error(
|
||||
link,
|
||||
codes::LINK_CONTEXT_CONFLICT,
|
||||
format!("resolved target unit `{target_unit_id}` is not in the target module"),
|
||||
)
|
||||
})?;
|
||||
if unit.kind == "function" {
|
||||
if unit.mode != "exec" || unit.level != 2 {
|
||||
return Err(link_error(
|
||||
link,
|
||||
codes::LINK_INVALID,
|
||||
format!("`{}` is an Exec section but not a function declaration", link.url),
|
||||
));
|
||||
}
|
||||
let function = module
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.unit_id == unit.id)
|
||||
.ok_or_else(|| {
|
||||
link_error(
|
||||
link,
|
||||
codes::LINK_CONTEXT_CONFLICT,
|
||||
format!("Exec H2 `{}` has no function record", link.url),
|
||||
)
|
||||
})?;
|
||||
return Ok(DependencyTarget::Model {
|
||||
snapshot,
|
||||
unit_id: unit.id.clone(),
|
||||
function: Box::new(function.clone()),
|
||||
});
|
||||
}
|
||||
if unit.kind != "knowledge" || unit.level != 2 {
|
||||
return Err(link_error(
|
||||
link,
|
||||
codes::LINK_INVALID,
|
||||
format!(
|
||||
"dependency link `{}` must select a Knowledge H2 (theorem) or an Exec H2 \
|
||||
(program model), not `{}`",
|
||||
link.url,
|
||||
unit.kind
|
||||
),
|
||||
));
|
||||
}
|
||||
let extraction = self.extraction(&module, target_path);
|
||||
match extraction.get(&unit.id) {
|
||||
Some(Extraction::Unit(proof_unit)) => Ok(DependencyTarget::Theorem {
|
||||
snapshot,
|
||||
unit_id: unit.id.clone(),
|
||||
proof_unit: Box::new(proof_unit.clone()),
|
||||
}),
|
||||
Some(Extraction::Invalid(diagnostic)) => Err(Diagnostic {
|
||||
severity: crate::Severity::Error,
|
||||
code: diagnostic.code,
|
||||
message: format!(
|
||||
"dependency target `{}` is not a valid proof unit: {}",
|
||||
link.url, diagnostic.message
|
||||
),
|
||||
span: Some(link.link_span),
|
||||
hint: diagnostic.hint.clone(),
|
||||
}),
|
||||
None => Err(link_error(
|
||||
link,
|
||||
codes::LINK_INVALID,
|
||||
format!(
|
||||
"dependency target `{}` is a Knowledge H2 without a direct `证明依赖` heading; \
|
||||
it is not a selected theorem",
|
||||
link.url
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ClosureLoader<'a> {
|
||||
linker: &'a mut Linker,
|
||||
documents: BTreeMap<PathBuf, Arc<Snapshot>>,
|
||||
units: HashMap<(PathBuf, String), LoadedUnit>,
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl<'a> ClosureLoader<'a> {
|
||||
fn load_unit(
|
||||
&mut self,
|
||||
snapshot: Arc<Snapshot>,
|
||||
unit_id: &str,
|
||||
depth: usize,
|
||||
) -> Result<(), Failure> {
|
||||
let key = (snapshot.canonical_path.clone(), unit_id.to_string());
|
||||
if self.units.contains_key(&key) {
|
||||
return Ok(());
|
||||
}
|
||||
let limits = CatalogLimits::default();
|
||||
if depth > limits.depth {
|
||||
self.diagnostics.push(Diagnostic::error(
|
||||
codes::PROOF_BUDGET,
|
||||
format!("dependency chain is deeper than {} levels", limits.depth),
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
if self.units.len() >= limits.units {
|
||||
self.diagnostics.push(Diagnostic::error(
|
||||
codes::PROOF_BUDGET,
|
||||
format!("catalog contains more than {} proof units", limits.units),
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
let path = snapshot.canonical_path.clone();
|
||||
let module = snapshot.entry().clone();
|
||||
let extraction = self.linker.extraction(&module, &path);
|
||||
let proof_unit = match extraction.get(unit_id) {
|
||||
Some(Extraction::Unit(unit)) => unit.clone(),
|
||||
Some(Extraction::Invalid(diagnostic)) => {
|
||||
self.diagnostics.push(diagnostic.clone());
|
||||
return Ok(());
|
||||
}
|
||||
None => {
|
||||
self.diagnostics.push(Diagnostic::error(
|
||||
codes::DOCUMENT_UNIT,
|
||||
format!(
|
||||
"unit `{unit_id}` is not a proof unit in `{}`",
|
||||
module.relative_path
|
||||
),
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
// Reserve the slot before recursing so cycles terminate.
|
||||
self.units.insert(
|
||||
key.clone(),
|
||||
LoadedUnit {
|
||||
snapshot: snapshot.clone(),
|
||||
module: module.clone(),
|
||||
proof_unit: proof_unit.clone(),
|
||||
dependencies: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
},
|
||||
);
|
||||
self.documents.insert(path.clone(), snapshot.clone());
|
||||
let mut resolved = Vec::new();
|
||||
let mut unit_diagnostics = Vec::new();
|
||||
for link in &proof_unit.dependencies.links {
|
||||
match self
|
||||
.linker
|
||||
.resolve_link(&path, &snapshot, &module, link)
|
||||
{
|
||||
Ok(dependency) => {
|
||||
let dependency_key = dependency.target.snapshot().canonical_path.clone();
|
||||
self.documents
|
||||
.insert(dependency_key.clone(), dependency.target.snapshot().clone());
|
||||
let recurse = match &dependency.target {
|
||||
DependencyTarget::Theorem {
|
||||
snapshot: target_snapshot,
|
||||
unit_id: target_unit_id,
|
||||
..
|
||||
} => Some((target_snapshot.clone(), target_unit_id.clone())),
|
||||
DependencyTarget::Model { .. } => None,
|
||||
};
|
||||
resolved.push(dependency);
|
||||
if let Some((target_snapshot, target_unit_id)) = recurse {
|
||||
self.load_unit(target_snapshot, &target_unit_id, depth + 1)?;
|
||||
}
|
||||
}
|
||||
Err(diagnostic) => {
|
||||
self.diagnostics.push(diagnostic.clone());
|
||||
unit_diagnostics.push(diagnostic);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(entry) = self.units.get_mut(&key) {
|
||||
entry.dependencies = resolved;
|
||||
entry.diagnostics = unit_diagnostics;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn visit(
|
||||
units: &HashMap<(PathBuf, String), LoadedUnit>,
|
||||
key: &(PathBuf, String),
|
||||
state: &mut HashMap<(PathBuf, String), u8>,
|
||||
order: &mut Vec<(PathBuf, String)>,
|
||||
stack: &mut Vec<(PathBuf, String)>,
|
||||
cycles: &mut Vec<Vec<String>>,
|
||||
) {
|
||||
match state.get(key) {
|
||||
Some(2) => return,
|
||||
Some(1) => {
|
||||
// Cycle: report the concrete chain from the first occurrence.
|
||||
if let Some(position) = stack.iter().position(|candidate| candidate == key) {
|
||||
let mut chain: Vec<String> = stack[position..]
|
||||
.iter()
|
||||
.map(|(_, unit_id)| unit_id.clone())
|
||||
.collect();
|
||||
chain.push(key.1.clone());
|
||||
if !cycles.contains(&chain) {
|
||||
cycles.push(chain);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
state.insert(key.clone(), 1);
|
||||
stack.push(key.clone());
|
||||
if let Some(unit) = units.get(key) {
|
||||
for dependency in &unit.dependencies {
|
||||
if let DependencyTarget::Theorem { snapshot, unit_id, .. } = &dependency.target {
|
||||
let child = (snapshot.canonical_path.clone(), unit_id.clone());
|
||||
visit(units, &child, state, order, stack, cycles);
|
||||
}
|
||||
}
|
||||
}
|
||||
stack.pop();
|
||||
state.insert(key.clone(), 2);
|
||||
order.push(key.clone());
|
||||
}
|
||||
|
||||
fn link_error(link: &DependencyLink, code: &'static str, message: impl Into<String>) -> Diagnostic {
|
||||
Diagnostic::error(code, message)
|
||||
.at(link.link_span)
|
||||
.with_hint("fix the dependency link so it points at exactly one selected unit inside the root")
|
||||
}
|
||||
|
||||
/// Validate one package-relative candidate path from an Analysis reference.
|
||||
pub fn validate_relative_path(path: &str) -> std::result::Result<(), String> {
|
||||
if path.is_empty() {
|
||||
return Err("link target path is empty".to_string());
|
||||
}
|
||||
if path.starts_with('/') || path.starts_with('\\') || path.contains('\\') {
|
||||
return Err(format!("link target path `{path}` is absolute or uses a platform separator"));
|
||||
}
|
||||
if let Some((before, _)) = path.split_once(':') {
|
||||
let scheme = before;
|
||||
if !scheme.contains('/')
|
||||
&& (scheme.len() == 1
|
||||
|| scheme
|
||||
.chars()
|
||||
.next()
|
||||
.is_some_and(|first| first.is_ascii_alphabetic()))
|
||||
{
|
||||
return Err(format!(
|
||||
"link target path `{path}` uses an absolute, drive or URI prefix"
|
||||
));
|
||||
}
|
||||
}
|
||||
if path.len() > 4096 {
|
||||
return Err("link target path is too long".to_string());
|
||||
}
|
||||
if path.contains('\0') {
|
||||
return Err("link target path contains a NUL byte".to_string());
|
||||
}
|
||||
for segment in path.split('/') {
|
||||
if segment.is_empty() || segment == "." || segment == ".." {
|
||||
return Err(format!(
|
||||
"link target path `{path}` contains an empty or traversal segment"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Human-readable reference to a unit for diagnostics/reports.
|
||||
pub fn display_unit(snapshot: &Snapshot, unit: &Unit) -> String {
|
||||
format!("{}#{}", snapshot.relative_path, unit.path.join("/"))
|
||||
}
|
||||
|
||||
/// Source span of a unit's heading for diagnostics.
|
||||
pub fn unit_span(unit: &Unit) -> Span {
|
||||
unit.heading_span.unwrap_or(unit.span)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn relative_path_validation_rejects_unsafe_candidates() {
|
||||
assert!(validate_relative_path("algebra.mq.md").is_ok());
|
||||
assert!(validate_relative_path("sub/notes.mq.md").is_ok());
|
||||
assert!(validate_relative_path("../outside.mq.md").is_err());
|
||||
assert!(validate_relative_path("sub/../x.mq.md").is_err());
|
||||
assert!(validate_relative_path("./x.mq.md").is_err());
|
||||
assert!(validate_relative_path("a//b.mq.md").is_err());
|
||||
assert!(validate_relative_path("/etc/passwd").is_err());
|
||||
assert!(validate_relative_path("C:/x.mq.md").is_err());
|
||||
assert!(validate_relative_path("x\\y.mq.md").is_err());
|
||||
assert!(validate_relative_path("x\u{0}y").is_err());
|
||||
}
|
||||
}
|
||||
+190
-2
@@ -1,5 +1,193 @@
|
||||
//! `marqdo-prove` executable: argument handling, presentation and exit codes.
|
||||
//!
|
||||
//! Two business commands only: `check` and `replay`. `--help` / `--version` are
|
||||
//! ordinary CLI metadata. No other sub-commands, compatibility flags or legacy
|
||||
//! protocols exist.
|
||||
|
||||
fn main() {
|
||||
std::process::exit(2);
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use marqdo_prove::prove::{self, CheckOptions, Invocation, ReplayOptions};
|
||||
|
||||
const USAGE: &str = "\
|
||||
marqdo-prove — static, link-driven mathematical proof checking for Marqdo documents
|
||||
|
||||
USAGE:
|
||||
marqdo-prove check ENTRY [--unit FRAGMENT] [--root DIR] [--out PATH] [--json]
|
||||
marqdo-prove replay ENTRY BUNDLE [--root DIR] [--json]
|
||||
marqdo-prove --version
|
||||
marqdo-prove --help
|
||||
|
||||
CHECK
|
||||
Extract every selected Knowledge H2 proof unit of ENTRY, load declared
|
||||
local theorem/program-model dependencies, prove the bounded integer
|
||||
propositions on the fixed Lean 4 + Mathlib backend, verify through an
|
||||
independent replay path and publish content-addressed proof bundles.
|
||||
|
||||
--unit FRAGMENT only the exact anchor/heading name FRAGMENT of ENTRY
|
||||
--root DIR explicit controlled local document root (must contain ENTRY)
|
||||
--out PATH export a verified proof bundle to PATH
|
||||
--json machine-readable single JSON object on stdout
|
||||
|
||||
REPLAY
|
||||
Re-verify a saved proof bundle against the current sources and the fixed
|
||||
environment without running proof search, without network access and
|
||||
without trusting any stored `.olean`.
|
||||
|
||||
EXIT CODES
|
||||
0 every requested target was verified (or there was no target)
|
||||
1 at least one requested target was not verified (refuted/unknown/
|
||||
unsupported/invalid/blocked/stale)
|
||||
2 engineering failure, command line error, upstream contract or backend
|
||||
unavailable
|
||||
";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let exit = match run(&args) {
|
||||
Ok(code) => code,
|
||||
Err(message) => {
|
||||
eprintln!("error: {message}");
|
||||
eprintln!();
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
ExitCode::from(exit)
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<u8, String> {
|
||||
let Some(command) = args.first() else {
|
||||
return Err("missing command".to_string());
|
||||
};
|
||||
match command.as_str() {
|
||||
"--version" | "-V" => {
|
||||
println!("{} {}", marqdo_prove::TOOL_NAME, env!("CARGO_PKG_VERSION"));
|
||||
Ok(0)
|
||||
}
|
||||
"--help" | "-h" | "help" => {
|
||||
print!("{USAGE}");
|
||||
Ok(0)
|
||||
}
|
||||
"check" => {
|
||||
let options = parse_check(&args[1..])?;
|
||||
let json = options.json;
|
||||
let report = prove::run(Invocation::Check(options));
|
||||
Ok(emit(report, json))
|
||||
}
|
||||
"replay" => {
|
||||
let options = parse_replay(&args[1..])?;
|
||||
let json = options.json;
|
||||
let report = prove::run(Invocation::Replay(options));
|
||||
Ok(emit(report, json))
|
||||
}
|
||||
other => Err(format!("unknown command `{other}`")),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit(report: prove::Report, json: bool) -> u8 {
|
||||
let status = report.status();
|
||||
if json {
|
||||
match serde_json::to_string(&report) {
|
||||
Ok(text) => println!("{text}"),
|
||||
Err(error) => {
|
||||
eprintln!("error: cannot serialize the result report: {error}");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
print!("{}", report.render_text());
|
||||
// Diagnostics are already part of the textual rendering; progress and
|
||||
// engineering detail stay on stderr without polluting JSON stdout.
|
||||
for diagnostic in &report.diagnostics {
|
||||
eprintln!(
|
||||
"{} [{}] {}",
|
||||
diagnostic.severity, diagnostic.code, diagnostic.message
|
||||
);
|
||||
}
|
||||
}
|
||||
status.exit_code() as u8
|
||||
}
|
||||
|
||||
fn parse_check(args: &[String]) -> Result<CheckOptions, String> {
|
||||
let mut entry: Option<PathBuf> = None;
|
||||
let mut unit = None;
|
||||
let mut root = None;
|
||||
let mut out = None;
|
||||
let mut json = false;
|
||||
let mut index = 0;
|
||||
while index < args.len() {
|
||||
let arg = &args[index];
|
||||
match arg.as_str() {
|
||||
"--unit" => {
|
||||
index += 1;
|
||||
unit = Some(require_value(args, index, "--unit")?);
|
||||
}
|
||||
"--root" => {
|
||||
index += 1;
|
||||
root = Some(PathBuf::from(require_value(args, index, "--root")?));
|
||||
}
|
||||
"--out" => {
|
||||
index += 1;
|
||||
out = Some(PathBuf::from(require_value(args, index, "--out")?));
|
||||
}
|
||||
"--json" => json = true,
|
||||
flag if flag.starts_with('-') => {
|
||||
return Err(format!("unknown check option `{flag}`"));
|
||||
}
|
||||
value => {
|
||||
if entry.is_some() {
|
||||
return Err(format!("unexpected extra argument `{value}`"));
|
||||
}
|
||||
entry = Some(PathBuf::from(value));
|
||||
}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
let entry = entry.ok_or_else(|| "check requires an ENTRY document".to_string())?;
|
||||
Ok(CheckOptions {
|
||||
entry,
|
||||
unit,
|
||||
root,
|
||||
out,
|
||||
json,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_replay(args: &[String]) -> Result<ReplayOptions, String> {
|
||||
let mut positional: Vec<String> = Vec::new();
|
||||
let mut root = None;
|
||||
let mut json = false;
|
||||
let mut index = 0;
|
||||
while index < args.len() {
|
||||
let arg = &args[index];
|
||||
match arg.as_str() {
|
||||
"--root" => {
|
||||
index += 1;
|
||||
root = Some(PathBuf::from(require_value(args, index, "--root")?));
|
||||
}
|
||||
"--json" => json = true,
|
||||
flag if flag.starts_with('-') => {
|
||||
return Err(format!("unknown replay option `{flag}`"));
|
||||
}
|
||||
value => positional.push(value.to_string()),
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
if positional.len() != 2 {
|
||||
return Err("replay requires ENTRY and BUNDLE positional arguments".to_string());
|
||||
}
|
||||
Ok(ReplayOptions {
|
||||
entry: PathBuf::from(&positional[0]),
|
||||
bundle: PathBuf::from(&positional[1]),
|
||||
root,
|
||||
json,
|
||||
})
|
||||
}
|
||||
|
||||
fn require_value(args: &[String], index: usize, flag: &str) -> Result<String, String> {
|
||||
args.get(index)
|
||||
.filter(|value| !value.starts_with('-') || value.as_str() == "-")
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("{flag} requires a value"))
|
||||
}
|
||||
+828
@@ -1 +1,829 @@
|
||||
//! Finite exact-integer program model mapping (docs/DEVELOPMENT.md §7).
|
||||
//!
|
||||
//! The program bridge is intentionally tiny. Given the Analysis typed IR of one
|
||||
//! Exec H2, this module either validates the *complete* function against the
|
||||
//! whitelist subset below, or rejects it. There is no partial acceptance, no
|
||||
//! regex/raw-Markdown parsing, no execution of the function, and no inference
|
||||
//! of a general property from examples:
|
||||
//!
|
||||
//! * explicit signature, every parameter required, typed `Int`, no defaults;
|
||||
//! * body = any number of plain local assignments followed by exactly one final
|
||||
//! `return`, all expressions built from Int literals, variables, unary minus
|
||||
//! and `+`, `-`, `*`;
|
||||
//! * one static single frame; a rebind creates a new immutable slot.
|
||||
//!
|
||||
//! The deterministic Lean mapping is a `public def marqdoModel_<key>` whose
|
||||
//! parameters are renamed `mqp0...` and whose assignments become nested `let`s
|
||||
//! over fresh slots `mql0...`. Original identifiers never reach generated Lean.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use num_bigint::BigInt;
|
||||
|
||||
use crate::analysis::{Expression, Function, ModuleData, Place, Statement};
|
||||
use crate::{codes, sha256_hex, Diagnostic, Severity, Span};
|
||||
|
||||
/// One validated model plus its deterministic Lean identity.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ModelDef {
|
||||
/// Canonical Analysis FunctionId of the modeled function.
|
||||
pub function_id: String,
|
||||
/// Canonical unit id of the Exec H2 that owns the function.
|
||||
pub unit_id: String,
|
||||
/// Module logical locator (module.relative_path) that declares it.
|
||||
pub locator: String,
|
||||
/// Stable content key: 20 lowercase hex chars derived from the function
|
||||
/// identity and the validated IR.
|
||||
pub key: String,
|
||||
/// Lean declaration name: `marqdoModel_<key>`.
|
||||
pub lean_name: String,
|
||||
/// Lean-safe parameter names in declaration order (`mqp0`, `mqp1`, ...).
|
||||
pub params: Vec<String>,
|
||||
/// SHA-256 of the deterministic canonical dump of the validated model.
|
||||
pub digest: String,
|
||||
/// Human-readable one-line summary for reports.
|
||||
pub source_summary: String,
|
||||
/// Supported semantic note; fixed text.
|
||||
pub semantics: String,
|
||||
/// Internal normalized program slots, used by `lean_definition`.
|
||||
slots: Vec<LeanSlot>,
|
||||
/// Rendered final return expression over slots.
|
||||
return_render: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct LeanSlot {
|
||||
slot: String,
|
||||
render: String,
|
||||
}
|
||||
|
||||
/// Lean module name that contains this model definition.
|
||||
pub fn lean_module_name(model: &ModelDef) -> String {
|
||||
format!("MarqdoProof.Generated.Model_{}", model.key)
|
||||
}
|
||||
|
||||
/// Fixed semantic scope note used in reports and manifests.
|
||||
pub const SEMANTICS: &str =
|
||||
"exact integer single-frame straight-line model returning Int; not a runtime refinement";
|
||||
|
||||
impl ModelDef {
|
||||
/// Lean 4 source of the model declaration (no module header/imports).
|
||||
pub fn lean_definition(&self) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("@[expose] public def ");
|
||||
out.push_str(&self.lean_name);
|
||||
for parameter in &self.params {
|
||||
out.push_str(&format!(" ({parameter} : Int)"));
|
||||
}
|
||||
out.push_str(" : Int");
|
||||
if self.slots.is_empty() {
|
||||
out.push_str(&format!(" := {}\n", self.return_render));
|
||||
return out;
|
||||
}
|
||||
out.push_str(" :=\n");
|
||||
for slot in &self.slots {
|
||||
out.push_str(&format!(" let {} := {};\n", slot.slot, slot.render));
|
||||
}
|
||||
out.push_str(&format!(" {}\n", self.return_render));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate one Analysis function against the supported subset.
|
||||
///
|
||||
/// `Ok` is returned only when every parameter, statement, expression and span
|
||||
/// is inside the whitelist. The first violation produces a `model.unsupported`
|
||||
/// diagnostic owned by the offending span.
|
||||
pub fn build_model(
|
||||
function: &Function,
|
||||
module: &ModuleData,
|
||||
) -> std::result::Result<ModelDef, Diagnostic> {
|
||||
validate_span(module, function.span, "function")?;
|
||||
if function.signature.kind != "explicit" {
|
||||
return Err(unsupported(
|
||||
function.heading_span,
|
||||
format!(
|
||||
"function `{}` uses an inferred parameter signature; the program bridge only \
|
||||
supports explicit typed parameters",
|
||||
function.local_name
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut parameter_names: Vec<String> = Vec::new();
|
||||
for parameter in &function.signature.params {
|
||||
validate_span(module, parameter.span, "parameter")?;
|
||||
if !parameter.required {
|
||||
return Err(unsupported(
|
||||
parameter.span,
|
||||
format!(
|
||||
"parameter `{}` of `{}` is optional; the program bridge requires every \
|
||||
parameter to be required",
|
||||
parameter.name, function.local_name
|
||||
),
|
||||
));
|
||||
}
|
||||
if parameter.default.is_some() {
|
||||
return Err(unsupported(
|
||||
parameter.span,
|
||||
format!(
|
||||
"parameter `{}` of `{}` has a default value, which the program bridge does \
|
||||
not support",
|
||||
parameter.name, function.local_name
|
||||
),
|
||||
));
|
||||
}
|
||||
if parameter.ty.as_deref() != Some("Int") {
|
||||
return Err(unsupported(
|
||||
parameter.span,
|
||||
format!(
|
||||
"parameter `{}` of `{}` has type `{}`; every program-model parameter must be \
|
||||
exactly `Int`",
|
||||
parameter.name,
|
||||
function.local_name,
|
||||
parameter.ty.as_deref().unwrap_or("<untyped>")
|
||||
),
|
||||
));
|
||||
}
|
||||
if parameter_names.contains(¶meter.name) {
|
||||
return Err(unsupported(
|
||||
parameter.span,
|
||||
format!("duplicate parameter name `{}`", parameter.name),
|
||||
));
|
||||
}
|
||||
parameter_names.push(parameter.name.clone());
|
||||
}
|
||||
|
||||
// Validate the straight-line body shape: assignments..., one final return.
|
||||
let mut statements = function.body.iter();
|
||||
let mut assignments: Vec<(&str, &Expression)> = Vec::new();
|
||||
let mut returned: Option<&Expression> = None;
|
||||
let mut index = 0usize;
|
||||
while let Some(statement) = statements.next() {
|
||||
validate_span(module, statement.span(), "statement")?;
|
||||
if returned.is_some() {
|
||||
return Err(unsupported(
|
||||
statement.span(),
|
||||
format!(
|
||||
"function `{}` has a statement after `return`; the program bridge requires \
|
||||
exactly one final return",
|
||||
function.local_name
|
||||
),
|
||||
));
|
||||
}
|
||||
match statement {
|
||||
Statement::Assign { target, value, .. } => {
|
||||
let Place::Local(name) = target else {
|
||||
return Err(unsupported(
|
||||
statement.span(),
|
||||
format!(
|
||||
"function `{}` assigns to a memory/index place; only local \
|
||||
rebinding is supported",
|
||||
function.local_name
|
||||
),
|
||||
));
|
||||
};
|
||||
if name.is_empty() {
|
||||
return Err(unsupported(statement.span(), "empty local assignment target"));
|
||||
}
|
||||
assignments.push((name.as_str(), value));
|
||||
}
|
||||
Statement::Return { value, .. } => returned = Some(value),
|
||||
Statement::Expression { .. } => {
|
||||
return Err(unsupported(
|
||||
statement.span(),
|
||||
format!(
|
||||
"function `{}` has an expression statement; only local assignments and \
|
||||
one final return are supported",
|
||||
function.local_name
|
||||
),
|
||||
))
|
||||
}
|
||||
Statement::Branch { .. } => {
|
||||
return Err(unsupported(
|
||||
statement.span(),
|
||||
format!(
|
||||
"function `{}` uses a branch; the first release does not model branching",
|
||||
function.local_name
|
||||
),
|
||||
))
|
||||
}
|
||||
Statement::Loop { .. } => {
|
||||
return Err(unsupported(
|
||||
statement.span(),
|
||||
format!(
|
||||
"function `{}` uses a loop; the first release does not model loops",
|
||||
function.local_name
|
||||
),
|
||||
))
|
||||
}
|
||||
Statement::Break { .. } => {
|
||||
return Err(unsupported(
|
||||
statement.span(),
|
||||
format!("function `{}` uses `break` outside a supported loop", function.local_name),
|
||||
))
|
||||
}
|
||||
Statement::Continue { .. } => {
|
||||
return Err(unsupported(
|
||||
statement.span(),
|
||||
format!(
|
||||
"function `{}` uses `continue` outside a supported loop",
|
||||
function.local_name
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
index += 1;
|
||||
if index > 4096 {
|
||||
return Err(unsupported(
|
||||
function.span,
|
||||
"function body is too large for the program bridge".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let Some(return_expression) = returned else {
|
||||
return Err(unsupported(
|
||||
function.span,
|
||||
format!(
|
||||
"function `{}` has no final `return`; the program bridge requires exactly one \
|
||||
final Int return",
|
||||
function.local_name
|
||||
),
|
||||
));
|
||||
};
|
||||
|
||||
// Build the slot environment. Parameters occupy mqp0..; assignments create
|
||||
// fresh mql slots in statement order.
|
||||
let params: Vec<String> = (0..parameter_names.len())
|
||||
.map(|index| format!("mqp{index}"))
|
||||
.collect();
|
||||
let mut environment: HashMap<String, String> = HashMap::new();
|
||||
for (index, name) in parameter_names.iter().enumerate() {
|
||||
environment.insert(name.clone(), params[index].clone());
|
||||
}
|
||||
let mut slots: Vec<LeanSlot> = Vec::new();
|
||||
let mut canonical = String::new();
|
||||
canonical.push_str("marqdo-prove/model-dump/v1\n");
|
||||
canonical.push_str(&function.id);
|
||||
canonical.push('\n');
|
||||
canonical.push_str(&format!("params:{}\n", parameter_names.join(",")));
|
||||
for (name, value) in &assignments {
|
||||
let render = render_lean(value, &environment, module, function)?;
|
||||
canonical.push_str(&format!(
|
||||
"assign:{name}={}\n",
|
||||
render_original(value, &environment, module, function)?
|
||||
));
|
||||
let slot = format!("mql{}", slots.len());
|
||||
slots.push(LeanSlot {
|
||||
slot: slot.clone(),
|
||||
render,
|
||||
});
|
||||
environment.insert((*name).to_string(), slot);
|
||||
}
|
||||
let return_render = render_lean(return_expression, &environment, module, function)?;
|
||||
canonical.push_str(&format!(
|
||||
"return:{}\n",
|
||||
render_original(return_expression, &environment, module, function)?
|
||||
));
|
||||
let digest = sha256_hex(canonical.as_bytes());
|
||||
let key = model_key(&function.id, &module.relative_path, &digest);
|
||||
let lean_name = format!("marqdoModel_{key}");
|
||||
let summary_def = format!(
|
||||
"def {}({}) : Int := {}",
|
||||
function.local_name,
|
||||
parameter_names
|
||||
.iter()
|
||||
.map(|name| format!("{name}: Int"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
render_summary(return_expression, &assignments, &environment, module, function)?
|
||||
);
|
||||
Ok(ModelDef {
|
||||
function_id: function.id.clone(),
|
||||
unit_id: function.unit_id.clone(),
|
||||
locator: module.relative_path.clone(),
|
||||
key,
|
||||
lean_name,
|
||||
params,
|
||||
digest,
|
||||
source_summary: summary_def,
|
||||
semantics: SEMANTICS.to_string(),
|
||||
slots,
|
||||
return_render,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stable key of a model definition (20 lowercase hex).
|
||||
fn model_key(function_id: &str, locator: &str, digest: &str) -> String {
|
||||
let material = format!("marqdo-prove/model/v2\u{0}{function_id}\u{0}{locator}\u{0}{digest}");
|
||||
sha256_hex(material.as_bytes())[..20].to_string()
|
||||
}
|
||||
|
||||
fn render_lean(
|
||||
expression: &Expression,
|
||||
environment: &HashMap<String, String>,
|
||||
module: &ModuleData,
|
||||
function: &Function,
|
||||
) -> std::result::Result<String, Diagnostic> {
|
||||
validate_span(module, expression.span(), "expression")?;
|
||||
match expression {
|
||||
Expression::Literal { ty, value, span } => {
|
||||
if ty != "int" {
|
||||
return Err(unsupported(
|
||||
*span,
|
||||
format!(
|
||||
"function `{}` uses a `{ty}` literal; only Int literals are supported",
|
||||
function.local_name
|
||||
),
|
||||
));
|
||||
}
|
||||
let Some(serde_json::Value::String(text)) = value else {
|
||||
return Err(unsupported(*span, "integer literal has a non-string Analysis value"));
|
||||
};
|
||||
if text.len() > crate::limits::MAX_LITERAL_DIGITS {
|
||||
return Err(unsupported(
|
||||
*span,
|
||||
format!(
|
||||
"integer literal exceeds the {} digit budget",
|
||||
crate::limits::MAX_LITERAL_DIGITS
|
||||
),
|
||||
));
|
||||
}
|
||||
let normalized = normalize_integer_literal(text).ok_or_else(|| {
|
||||
unsupported(
|
||||
*span,
|
||||
format!("`{text}` is not a canonical decimal integer literal"),
|
||||
)
|
||||
})?;
|
||||
Ok(render_int_literal(&normalized))
|
||||
}
|
||||
Expression::Variable { name, span } => match environment.get(name) {
|
||||
Some(slot) => Ok(slot.clone()),
|
||||
None => Err(unsupported(
|
||||
*span,
|
||||
format!(
|
||||
"function `{}` reads local `{name}` before it is defined; the program bridge \
|
||||
has no defaults or ambient values",
|
||||
function.local_name
|
||||
),
|
||||
)),
|
||||
},
|
||||
Expression::Unary { op, operand, span } => {
|
||||
if op != "neg" {
|
||||
return Err(unsupported(
|
||||
*span,
|
||||
format!(
|
||||
"function `{}` uses unsupported unary operator `{op}`; only integer \
|
||||
negation is supported",
|
||||
function.local_name
|
||||
),
|
||||
));
|
||||
}
|
||||
let inner = render_lean(operand, environment, module, function)?;
|
||||
Ok(format!("(- {inner})"))
|
||||
}
|
||||
Expression::Binary {
|
||||
op,
|
||||
left,
|
||||
right,
|
||||
span,
|
||||
} => {
|
||||
let operator = match op.as_str() {
|
||||
"add" => "+",
|
||||
"sub" => "-",
|
||||
"mul" => "*",
|
||||
other => {
|
||||
return Err(unsupported(
|
||||
*span,
|
||||
format!(
|
||||
"function `{}` uses unsupported binary operator `{other}`; the \
|
||||
program bridge supports only `+`, `-`, `*`",
|
||||
function.local_name
|
||||
),
|
||||
))
|
||||
}
|
||||
};
|
||||
let left = render_lean(left, environment, module, function)?;
|
||||
let right = render_lean(right, environment, module, function)?;
|
||||
Ok(format!("({left} {operator} {right})"))
|
||||
}
|
||||
Expression::List { span, .. }
|
||||
| Expression::Record { span, .. }
|
||||
| Expression::Member { span, .. }
|
||||
| Expression::Index { span, .. }
|
||||
| Expression::Call { span, .. } => Err(unsupported(
|
||||
*span,
|
||||
format!(
|
||||
"function `{}` uses an unsupported expression form `{}`",
|
||||
function.local_name,
|
||||
expression_kind(expression)
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_original(
|
||||
expression: &Expression,
|
||||
environment: &HashMap<String, String>,
|
||||
module: &ModuleData,
|
||||
function: &Function,
|
||||
) -> std::result::Result<String, Diagnostic> {
|
||||
let _ = environment;
|
||||
render_pretty(expression, module, function)
|
||||
}
|
||||
|
||||
fn render_pretty(
|
||||
expression: &Expression,
|
||||
module: &ModuleData,
|
||||
function: &Function,
|
||||
) -> std::result::Result<String, Diagnostic> {
|
||||
match expression {
|
||||
Expression::Literal { ty, value, .. } => {
|
||||
let Some(serde_json::Value::String(text)) = value else {
|
||||
return Err(unsupported(expression.span(), "non-string integer literal"));
|
||||
};
|
||||
let normalized = normalize_integer_literal(text).ok_or_else(|| {
|
||||
unsupported(expression.span(), "invalid integer literal")
|
||||
})?;
|
||||
Ok(normalized)
|
||||
}
|
||||
Expression::Variable { name, .. } => Ok(name.clone()),
|
||||
Expression::Unary { operand, .. } => Ok(format!(
|
||||
"-{}",
|
||||
render_pretty(operand, module, function)?
|
||||
)),
|
||||
Expression::Binary {
|
||||
op, left, right, ..
|
||||
} => {
|
||||
let operator = match op.as_str() {
|
||||
"add" => "+",
|
||||
"sub" => "-",
|
||||
"mul" => "*",
|
||||
other => {
|
||||
return Err(unsupported(
|
||||
expression.span(),
|
||||
format!("unsupported operator `{other}`"),
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(format!(
|
||||
"({} {operator} {})",
|
||||
render_pretty(left, module, function)?,
|
||||
render_pretty(right, module, function)?
|
||||
))
|
||||
}
|
||||
other => Err(unsupported(
|
||||
other.span(),
|
||||
format!(
|
||||
"function `{}` uses an unsupported expression form `{}`",
|
||||
function.local_name,
|
||||
expression_kind(other)
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_summary(
|
||||
return_expression: &Expression,
|
||||
assignments: &[(&str, &Expression)],
|
||||
environment: &HashMap<String, String>,
|
||||
module: &ModuleData,
|
||||
function: &Function,
|
||||
) -> std::result::Result<String, Diagnostic> {
|
||||
let returned = render_original(return_expression, environment, module, function)?;
|
||||
if assignments.is_empty() {
|
||||
return Ok(returned);
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
for (name, value) in assignments {
|
||||
parts.push(format!(
|
||||
"let {name} = {}",
|
||||
render_original(value, environment, module, function)?
|
||||
));
|
||||
}
|
||||
parts.push(returned);
|
||||
Ok(parts.join("; "))
|
||||
}
|
||||
|
||||
fn normalize_integer_literal(text: &str) -> Option<String> {
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let digits = text.strip_prefix('-').unwrap_or(text);
|
||||
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
if digits.len() > crate::limits::MAX_LITERAL_DIGITS {
|
||||
return None;
|
||||
}
|
||||
let value: BigInt = text.parse().ok()?;
|
||||
Some(value.to_string())
|
||||
}
|
||||
|
||||
fn render_int_literal(normalized: &str) -> String {
|
||||
if let Some(rest) = normalized.strip_prefix('-') {
|
||||
format!("(- {rest} : Int)")
|
||||
} else {
|
||||
format!("({normalized} : Int)")
|
||||
}
|
||||
}
|
||||
|
||||
fn expression_kind(expression: &Expression) -> &'static str {
|
||||
match expression {
|
||||
Expression::Literal { .. } => "literal",
|
||||
Expression::Variable { .. } => "variable",
|
||||
Expression::List { .. } => "list",
|
||||
Expression::Record { .. } => "record",
|
||||
Expression::Unary { .. } => "unary",
|
||||
Expression::Binary { .. } => "binary",
|
||||
Expression::Member { .. } => "member",
|
||||
Expression::Index { .. } => "index",
|
||||
Expression::Call { .. } => "call",
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_span(
|
||||
module: &ModuleData,
|
||||
span: Span,
|
||||
owner: &str,
|
||||
) -> std::result::Result<(), Diagnostic> {
|
||||
if span.is_valid_in(&module.source) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(unsupported(
|
||||
span,
|
||||
format!("{owner} span is outside the module source"),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported(span: Span, message: impl Into<String>) -> Diagnostic {
|
||||
Diagnostic {
|
||||
severity: Severity::Error,
|
||||
code: codes::MODEL_UNSUPPORTED,
|
||||
message: message.into(),
|
||||
span: Some(span),
|
||||
hint: Some(
|
||||
"the program-model bridge supports only explicit Int parameters, local `+ - *` \
|
||||
assignments and a final Int return; keep the rest of the knowledge document as \
|
||||
ordinary readable knowledge"
|
||||
.to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::analysis::ModuleData;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
fn module(source_len: usize) -> ModuleData {
|
||||
ModuleData {
|
||||
id: "root:t::arith.mq.md".to_string(),
|
||||
package_instance_id: "root:t".to_string(),
|
||||
relative_path: "arith.mq.md".to_string(),
|
||||
source: " ".repeat(source_len),
|
||||
source_digest: sha256_hex(b"x"),
|
||||
document: crate::analysis::Node::default(),
|
||||
units: vec![],
|
||||
anchors: BTreeMap::new(),
|
||||
functions: vec![],
|
||||
references: vec![],
|
||||
resources: vec![],
|
||||
unit_by_id: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn expression(json: serde_json::Value) -> Expression {
|
||||
serde_json::from_value(json).expect("expression fixture")
|
||||
}
|
||||
|
||||
fn function_fixture(body: serde_json::Value, params: serde_json::Value, kind: &str) -> Function {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "root:t::arith.mq.md::整数计算.square",
|
||||
"unit_id": "root:t::arith.mq.md#整数计算/square",
|
||||
"local_name": "square",
|
||||
"namespace": "整数计算",
|
||||
"span": {"start": 0, "end": 100},
|
||||
"heading_span": {"start": 0, "end": 20},
|
||||
"signature": {"kind": kind, "params": params},
|
||||
"effects": ["unknown"],
|
||||
"body": body
|
||||
}))
|
||||
.expect("function fixture")
|
||||
}
|
||||
|
||||
fn int_param(name: &str, span_start: usize, span_end: usize) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"name": name,
|
||||
"required": true,
|
||||
"type": "Int",
|
||||
"default": null,
|
||||
"span": {"start": span_start, "end": span_end}
|
||||
})
|
||||
}
|
||||
|
||||
fn variable(name: &str) -> serde_json::Value {
|
||||
serde_json::json!({"kind": "variable", "name": name, "span": {"start": 0, "end": 10}})
|
||||
}
|
||||
|
||||
fn int_literal(value: &str) -> serde_json::Value {
|
||||
serde_json::json!({"kind": "literal", "type": "int", "value": value, "span": {"start": 0, "end": 10}})
|
||||
}
|
||||
|
||||
fn binary(op: &str, left: serde_json::Value, right: serde_json::Value) -> serde_json::Value {
|
||||
serde_json::json!({"kind": "binary", "op": op, "left": left, "right": right,
|
||||
"span": {"start": 0, "end": 30}})
|
||||
}
|
||||
|
||||
fn return_stmt(value: serde_json::Value) -> serde_json::Value {
|
||||
serde_json::json!({"kind": "return", "value": value, "span": {"start": 50, "end": 80}})
|
||||
}
|
||||
|
||||
fn assign(target: &str, value: serde_json::Value) -> serde_json::Value {
|
||||
serde_json::json!({"kind": "assign", "target": target, "value": value,
|
||||
"span": {"start": 20, "end": 45}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn square_model_maps_to_exact_lean_definition() {
|
||||
let function = function_fixture(serde_json::json!([return_stmt(binary("mul", variable("x"), variable("x")))]),
|
||||
serde_json::json!([int_param("x", 20, 30)]),
|
||||
"explicit",
|
||||
);
|
||||
let model = build_model(&function, &module(200)).expect("square model");
|
||||
assert_eq!(model.params, vec!["mqp0".to_string()]);
|
||||
assert_eq!(model.key.len(), 20);
|
||||
assert!(model.lean_name.starts_with("marqdoModel_"));
|
||||
assert_eq!(
|
||||
model.lean_definition(),
|
||||
"@[expose] public def marqdoModel_".to_string() + &model.key + " (mqp0 : Int) : Int := (mqp0 * mqp0)\n"
|
||||
);
|
||||
assert_eq!(model.digest.len(), 64);
|
||||
assert!(model.source_summary.starts_with("def square(x: Int) : Int := (x * x)"));
|
||||
assert_eq!(lean_module_name(&model), format!("MarqdoProof.Generated.Model_{}", model.key));
|
||||
// deterministic
|
||||
let again = build_model(&function, &module(200)).expect("square model");
|
||||
assert_eq!(model.key, again.key);
|
||||
assert_eq!(model.digest, again.digest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_parameter_constant_model() {
|
||||
let function = function_fixture(serde_json::json!([return_stmt(int_literal("42"))]),
|
||||
serde_json::json!([]),
|
||||
"explicit",
|
||||
);
|
||||
let model = build_model(&function, &module(200)).expect("constant model");
|
||||
assert!(model.lean_definition().contains("(42 : Int)"));
|
||||
assert!(!model.lean_definition().contains("let "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebinding_creates_fresh_slots() {
|
||||
let function = function_fixture(serde_json::json!([
|
||||
assign("y", binary("add", variable("x"), int_literal("1"))),
|
||||
assign("y", binary("mul", variable("y"), variable("y"))),
|
||||
return_stmt(variable("y"))
|
||||
]),
|
||||
serde_json::json!([int_param("x", 20, 30)]),
|
||||
"explicit",
|
||||
);
|
||||
let model = build_model(&function, &module(400)).expect("rebinding model");
|
||||
let definition = model.lean_definition();
|
||||
assert!(definition.contains("let mql0 := (mqp0 + (1 : Int));"));
|
||||
assert!(definition.contains("let mql1 := (mql0 * mql0);"));
|
||||
assert!(definition.contains(" mql1\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_literals_and_unary_minus_render_exactly() {
|
||||
let function = function_fixture(serde_json::json!([return_stmt(serde_json::json!({
|
||||
"kind": "unary", "op": "neg", "operand": int_literal("-7"),
|
||||
"span": {"start": 0, "end": 20}
|
||||
}))]),
|
||||
serde_json::json!([]),
|
||||
"explicit",
|
||||
);
|
||||
let model = build_model(&function, &module(200)).expect("neg model");
|
||||
assert!(
|
||||
model.lean_definition().contains("(- (- 7 : Int))"),
|
||||
"{}",
|
||||
model.lean_definition()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsupported_shapes() {
|
||||
let cases: Vec<(Function, &str)> = vec![
|
||||
(
|
||||
function_fixture(serde_json::json!([return_stmt(variable("x"))]),
|
||||
serde_json::json!([int_param("x", 20, 30)]),
|
||||
"inferred",
|
||||
),
|
||||
"inferred",
|
||||
),
|
||||
(
|
||||
function_fixture(serde_json::json!([return_stmt(variable("x"))]),
|
||||
serde_json::json!([{
|
||||
"name": "x", "required": true, "type": "Float",
|
||||
"default": null, "span": {"start": 20, "end": 30}
|
||||
}]),
|
||||
"explicit",
|
||||
),
|
||||
"type",
|
||||
),
|
||||
(
|
||||
function_fixture(serde_json::json!([return_stmt(int_literal("1.5"))]),
|
||||
serde_json::json!([]),
|
||||
"explicit",
|
||||
),
|
||||
"literal",
|
||||
),
|
||||
(
|
||||
function_fixture(serde_json::json!([return_stmt(binary("div", variable("x"), int_literal("2")))]),
|
||||
serde_json::json!([int_param("x", 20, 30)]),
|
||||
"explicit",
|
||||
),
|
||||
"operator",
|
||||
),
|
||||
(
|
||||
function_fixture(serde_json::json!([return_stmt(variable("y"))]),
|
||||
serde_json::json!([int_param("x", 20, 30)]),
|
||||
"explicit",
|
||||
),
|
||||
"before it is defined",
|
||||
),
|
||||
(
|
||||
function_fixture(serde_json::json!([assign("x", int_literal("1"))]),
|
||||
serde_json::json!([]),
|
||||
"explicit",
|
||||
),
|
||||
"return",
|
||||
),
|
||||
(
|
||||
function_fixture(serde_json::json!([
|
||||
return_stmt(int_literal("1")),
|
||||
assign("x", int_literal("2"))
|
||||
]),
|
||||
serde_json::json!([]),
|
||||
"explicit",
|
||||
),
|
||||
"after",
|
||||
),
|
||||
(
|
||||
function_fixture(serde_json::json!([{
|
||||
"kind": "branch",
|
||||
"arms": [{"condition": int_literal("1"), "condition_span": {"start": 0, "end": 1},
|
||||
"body": [], "span": {"start": 0, "end": 1}}],
|
||||
"span": {"start": 0, "end": 10}
|
||||
}]),
|
||||
serde_json::json!([]),
|
||||
"explicit",
|
||||
),
|
||||
"branch",
|
||||
),
|
||||
];
|
||||
for (function, needle) in cases {
|
||||
let error = build_model(&function, &module(400)).expect_err(needle);
|
||||
assert_eq!(error.code, codes::MODEL_UNSUPPORTED);
|
||||
let whole = format!("{error:?}");
|
||||
assert!(
|
||||
whole.contains(needle),
|
||||
"expected {needle:?} in {whole:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_literal_is_rejected_and_leading_zeros_normalized() {
|
||||
let huge = "9".repeat(5000);
|
||||
let function = function_fixture(serde_json::json!([return_stmt(int_literal(&huge))]),
|
||||
serde_json::json!([]),
|
||||
"explicit",
|
||||
);
|
||||
assert!(build_model(&function, &module(200)).is_err());
|
||||
let function = function_fixture(serde_json::json!([return_stmt(int_literal("00042"))]),
|
||||
serde_json::json!([]),
|
||||
"explicit",
|
||||
);
|
||||
let model = build_model(&function, &module(200)).expect("literal");
|
||||
assert!(model.lean_definition().contains("(42 : Int)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_place_assignment_is_rejected() {
|
||||
let function = function_fixture(serde_json::json!([{
|
||||
"kind": "assign",
|
||||
"target": {"kind": "index", "base": variable("x"),
|
||||
"index": int_literal("0"), "span": {"start": 0, "end": 10}},
|
||||
"value": int_literal("1"),
|
||||
"span": {"start": 0, "end": 20}
|
||||
}, return_stmt(int_literal("1"))]),
|
||||
serde_json::json!([int_param("x", 20, 30)]),
|
||||
"explicit",
|
||||
);
|
||||
let error = build_model(&function, &module(300)).expect_err("index");
|
||||
assert!(format!("{error:?}").contains("index"));
|
||||
}
|
||||
}
|
||||
+1992
-1
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user