tests+docs: contract fixtures, Lean-backed acceptance suite and executed status

- document_contract: negative path coverage through the real CLI (selection,
  shape errors, formula unsupported/invalid, missing/external links, cycles,
  --unit, upstream static failure, root escape) with exit-code assertions
- e2e: algebra, vector composition (declared == used), program model scope,
  refutation, export+replay, cache reuse, tampered payload rejection
- report fixes: declared/used locator consistency, diagnostic-only exit status,
  unsupported vs invalid formula outcomes
- clippy -D warnings and cargo fmt clean; docs/STATUS records pinned identities,
  executed commands, measured backend limits and known gaps
This commit is contained in:
marqdo-prove committed 2026-11-26 11:10:42 +08:00
1 parent 4e02da95a4
commit bd7e46b208
46 files changed
+390180 -460

No files matched your search

+164 -63
View File
@@ -51,7 +51,9 @@ pub struct ModuleData {
impl ModuleData {
pub fn unit(&self, unit_id: &str) -> Option<&Unit> {
self.unit_by_id.get(unit_id).map(|index| &self.units[*index])
self.unit_by_id
.get(unit_id)
.map(|index| &self.units[*index])
}
/// Direct child units of `parent_id`, in document order.
@@ -184,7 +186,10 @@ impl AnalysisBackend {
if !marqdo_bin.is_absolute() {
return Err(Failure::new(
codes::BACKEND_UNAVAILABLE,
format!("MARQDO_BIN must be an absolute path, got `{}`", marqdo_bin.display()),
format!(
"MARQDO_BIN must be an absolute path, got `{}`",
marqdo_bin.display()
),
));
}
if !marqdo_bin.is_file() {
@@ -197,7 +202,10 @@ impl AnalysisBackend {
std::fs::create_dir_all(&work_dir).map_err(|error| {
Failure::new(
codes::BACKEND_UNAVAILABLE,
format!("cannot create private work directory `{}`: {error}", work_dir.display()),
format!(
"cannot create private work directory `{}`: {error}",
work_dir.display()
),
)
})?;
if let Ok(revision) = std::env::var("MARQDO_API_REVISION") {
@@ -252,7 +260,10 @@ impl AnalysisBackend {
}
None => {
let mut directory = entry.parent().map(Path::to_path_buf).ok_or_else(|| {
Failure::new(codes::DOCUMENT_UNIT, "entry document has no parent directory")
Failure::new(
codes::DOCUMENT_UNIT,
"entry document has no parent directory",
)
})?;
let start = directory.clone();
loop {
@@ -306,9 +317,7 @@ impl AnalysisBackend {
}
let bytes = self.emit_analysis(&canonical, &root)?;
let snapshot = Arc::new(parse_and_validate(&bytes, &canonical, &root)?);
self.cache
.borrow_mut()
.insert(canonical, snapshot.clone());
self.cache.borrow_mut().insert(canonical, snapshot.clone());
Ok(snapshot)
}
@@ -511,6 +520,10 @@ struct AnalysisFile {
#[serde(deny_unknown_fields)]
struct Producer {
name: String,
/// Contract field: the CLI version is recorded in the upstream contract but
/// Prove binds through the environment identity instead of the producer
/// string, so the value is validated for presence and then unused.
#[allow(dead_code)]
version: String,
markdown_profile: String,
}
@@ -523,12 +536,18 @@ struct Project {
entry_module_id: String,
lock_digest: String,
manifest_digest: String,
/// Contract field validated by the upstream schema; Prove never uses stdlib.
#[allow(dead_code)]
stdlib: Option<StdlibIdentity>,
/// Contract field validated by the upstream schema; Prove never loads
/// extensions through Analysis.
#[allow(dead_code)]
extensions: Vec<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
struct StdlibIdentity {
version: String,
digest: String,
@@ -549,6 +568,9 @@ struct RawModule {
functions: Vec<Function>,
imports: Vec<Import>,
references: Vec<Reference>,
/// Inert call-binding projection; the program-model bridge does not use
/// cross-function calls in the first release.
#[allow(dead_code)]
calls: Vec<serde_json::Value>,
resources: Vec<Resource>,
}
@@ -661,10 +683,7 @@ pub enum Statement {
#[serde(rename = "expression")]
Expression { value: Expression, span: Span },
#[serde(rename = "branch")]
Branch {
arms: Vec<BranchArm>,
span: Span,
},
Branch { arms: Vec<BranchArm>, span: Span },
#[serde(rename = "loop")]
Loop {
condition: Expression,
@@ -728,10 +747,7 @@ pub enum Expression {
#[serde(rename = "variable")]
Variable { name: String, span: Span },
#[serde(rename = "list")]
List {
items: Vec<Expression>,
span: Span,
},
List { items: Vec<Expression>, span: Span },
#[serde(rename = "record")]
Record {
entries: Vec<RecordEntry>,
@@ -843,6 +859,7 @@ pub struct Resource {
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
struct RawDiagnostic {
module: String,
relative_path: String,
@@ -896,10 +913,16 @@ fn parse_and_validate(bytes: &[u8], entry_path: &Path, root: &Path) -> Result<Sn
file.producer.markdown_profile
));
}
if !file.diagnostics.iter().all(|diagnostic| diagnostic.severity != "error") {
if !file
.diagnostics
.iter()
.all(|diagnostic| diagnostic.severity != "error")
{
return contract("Analysis contains error diagnostics despite a successful check");
}
if file.project.identity_kind != "manifest" && file.project.identity_kind != "workspace_snapshot" {
if file.project.identity_kind != "manifest"
&& file.project.identity_kind != "workspace_snapshot"
{
return contract(format!(
"unexpected project identity kind `{}`",
file.project.identity_kind
@@ -931,7 +954,11 @@ fn parse_and_validate(bytes: &[u8], entry_path: &Path, root: &Path) -> Result<Sn
.map_err(|_| {
Failure::new(
codes::LINK_OUTSIDE_ROOT,
format!("entry `{}` is not below root `{}`", entry_path.display(), root.display()),
format!(
"entry `{}` is not below root `{}`",
entry_path.display(),
root.display()
),
)
})?
.to_string_lossy()
@@ -968,9 +995,11 @@ fn parse_and_validate(bytes: &[u8], entry_path: &Path, root: &Path) -> Result<Sn
),
));
}
if let Some(previous) = instance_roots.insert(data.package_instance_id.clone(), canonical.clone())
if let Some(previous) =
instance_roots.insert(data.package_instance_id.clone(), canonical.clone())
{
if previous != canonical && data.package_instance_id != entry_matches[0].package_instance_id
if previous != canonical
&& data.package_instance_id != entry_matches[0].package_instance_id
{
// Distinct packages are allowed; equal instance ids are not.
}
@@ -1014,7 +1043,10 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
if raw.relative_path.is_empty()
|| raw.relative_path.starts_with('/')
|| raw.relative_path.contains('\\')
|| raw.relative_path.split('/').any(|segment| segment.is_empty() || segment == "." || segment == "..")
|| raw
.relative_path
.split('/')
.any(|segment| segment.is_empty() || segment == "." || segment == "..")
{
return contract(format!(
"module.relative_path `{}` is not a safe package-relative path",
@@ -1035,7 +1067,10 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
if raw.units.len() > max_units {
return Err(Failure::new(
codes::DOCUMENT_UNIT,
format!("module has {} units, above the {max_units} unit limit", raw.units.len()),
format!(
"module has {} units, above the {max_units} unit limit",
raw.units.len()
),
));
}
let mut unit_by_id = HashMap::new();
@@ -1047,11 +1082,17 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
return contract(format!("duplicate unit id `{}`", unit.id));
}
if !unit.span.is_valid_in(&raw.source) {
return contract(format!("unit `{}` has an out-of-range section span", unit.id));
return contract(format!(
"unit `{}` has an out-of-range section span",
unit.id
));
}
if let Some(heading_span) = unit.heading_span {
if !heading_span.is_valid_in(&raw.source) {
return contract(format!("unit `{}` has an out-of-range heading span", unit.id));
return contract(format!(
"unit `{}` has an out-of-range heading span",
unit.id
));
}
}
match unit.mode.as_str() {
@@ -1064,7 +1105,11 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
}
// Exactly one root unit, and a well-formed parent tree.
let roots: Vec<&Unit> = raw.units.iter().filter(|unit| unit.kind == "root").collect();
let roots: Vec<&Unit> = raw
.units
.iter()
.filter(|unit| unit.kind == "root")
.collect();
if roots.len() != 1 {
return contract("module must contain exactly one root unit");
}
@@ -1085,10 +1130,12 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
if unit.path.is_empty() {
return contract(format!("unit `{}` has an empty path", unit.id));
}
let parent_id = unit
.parent_id
.as_deref()
.ok_or_else(|| Failure::new(codes::UPSTREAM_CONTRACT, format!("unit `{}` has no parent", unit.id)))?;
let parent_id = unit.parent_id.as_deref().ok_or_else(|| {
Failure::new(
codes::UPSTREAM_CONTRACT,
format!("unit `{}` has no parent", unit.id),
)
})?;
let parent = raw
.units
.iter()
@@ -1108,9 +1155,14 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
));
}
if unit.span.start < parent.span.start || unit.span.end > parent.span.end {
return contract(format!("unit `{}` span is not nested in its parent", unit.id));
return contract(format!(
"unit `{}` span is not nested in its parent",
unit.id
));
}
if unit.mode_source_unit_id != unit.id && !is_ancestor(raw, &unit.mode_source_unit_id, &unit.id) {
if unit.mode_source_unit_id != unit.id
&& !is_ancestor(raw, &unit.mode_source_unit_id, &unit.id)
{
return contract(format!(
"unit `{}` mode_source_unit_id is not itself or an ancestor",
unit.id
@@ -1124,18 +1176,29 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
return contract("empty anchor name in Analysis");
}
if !unit_by_id.contains_key(&anchor.unit_id) {
return contract(format!("anchor `{}` points at an unknown unit", anchor.anchor));
return contract(format!(
"anchor `{}` points at an unknown unit",
anchor.anchor
));
}
if anchors.insert(anchor.anchor.clone(), anchor.unit_id.clone()).is_some() {
if anchors
.insert(anchor.anchor.clone(), anchor.unit_id.clone())
.is_some()
{
return contract(format!("duplicate anchor `{}`", anchor.anchor));
}
}
for function in &raw.functions {
if !unit_by_id.contains_key(&function.unit_id) {
return contract(format!("function `{}` points at an unknown unit", function.id));
return contract(format!(
"function `{}` points at an unknown unit",
function.id
));
}
if !function.span.is_valid_in(&raw.source) || !function.heading_span.is_valid_in(&raw.source) {
if !function.span.is_valid_in(&raw.source)
|| !function.heading_span.is_valid_in(&raw.source)
{
return contract(format!("function `{}` has out-of-range spans", function.id));
}
validate_statements(&function.body, &raw.source)?;
@@ -1146,7 +1209,10 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
return contract("reference.source does not match its module");
}
if !reference.span.is_valid_in(&raw.source) {
return contract(format!("reference `{}` has an out-of-range span", reference.url));
return contract(format!(
"reference `{}` has an out-of-range span",
reference.url
));
}
if !unit_by_id.contains_key(&reference.source_unit) {
return contract("reference.source_unit points at an unknown unit");
@@ -1166,17 +1232,26 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
for resource in &raw.resources {
if !resource.span.is_valid_in(&raw.source) {
return contract(format!("resource `{}` has an out-of-range span", resource.id));
return contract(format!(
"resource `{}` has an out-of-range span",
resource.id
));
}
if !unit_by_id.contains_key(&resource.unit_id) {
return contract(format!("resource `{}` points at an unknown unit", resource.id));
return contract(format!(
"resource `{}` points at an unknown unit",
resource.id
));
}
match resource.kind.as_str() {
"formula" => {
let payload = find_payload(&raw.document, resource.span).ok_or_else(|| {
Failure::new(
codes::UPSTREAM_CONTRACT,
format!("formula resource `{}` has no matching math node", resource.id),
format!(
"formula resource `{}` has no matching math node",
resource.id
),
)
})?;
let literal = math_literal(payload).ok_or_else(|| {
@@ -1259,7 +1334,10 @@ fn validate_node_spans(node: &Node, source: &str, depth: usize) -> Result<()> {
if depth > crate::limits::MAX_AST_DEPTH {
return Err(Failure::new(
codes::DOCUMENT_UNIT,
format!("document AST is deeper than {} levels", crate::limits::MAX_AST_DEPTH),
format!(
"document AST is deeper than {} levels",
crate::limits::MAX_AST_DEPTH
),
));
}
if !node.span.is_valid_in(source) {
@@ -1278,12 +1356,12 @@ fn validate_node_spans(node: &Node, source: &str, depth: usize) -> Result<()> {
validate_node_spans(child, source, depth + 1)?;
}
match node.kind.as_str() {
"math_block" | "math" | "text" | "code" | "code_block" | "front_matter" | "html_block"
| "html_inline" => {
if node.literal.is_none() && node.kind != "html_inline" {
"math_block" | "math" | "text" | "code" | "code_block" | "front_matter" | "html_block" => {
if node.literal.is_none() {
return contract(format!("document node `{}` has no literal", node.kind));
}
}
"html_inline" => {}
_ => {}
}
Ok(())
@@ -1305,7 +1383,9 @@ fn validate_statements(statements: &[Statement], source: &str) -> Result<()> {
validate_statements(&arm.body, source)?;
}
}
Statement::Loop { condition, body, .. } => {
Statement::Loop {
condition, body, ..
} => {
validate_expression(condition, source)?;
validate_statements(body, source)?;
}
@@ -1352,7 +1432,7 @@ fn validate_expression(expression: &Expression, source: &str) -> Result<()> {
}
/// Find the node whose span equals the resource span.
fn find_payload<'a>(node: &'a Node, span: Span) -> Option<&'a Node> {
fn find_payload(node: &Node, span: Span) -> Option<&Node> {
if node.span == span {
return Some(node);
}
@@ -1378,14 +1458,19 @@ fn is_sha256_digest(value: &str) -> bool {
let Some(hex) = value.strip_prefix("sha256:") else {
return false;
};
hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
hex.len() == 64
&& hex
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
}
fn contract<T>(message: impl Into<String>) -> Result<T> {
Err(Failure::new(codes::UPSTREAM_CONTRACT, message.into()).with_hint(
"install and build a Marqdo CLI that emits the current `marqdo.analysis` revision 3 \
Err(
Failure::new(codes::UPSTREAM_CONTRACT, message.into()).with_hint(
"install and build a Marqdo CLI that emits the current `marqdo.analysis` revision 3 \
contract; Prove has no compatibility reader",
))
),
)
}
// ---------------------------------------------------------------------------
@@ -1449,30 +1534,43 @@ mod tests {
#[test]
fn rejects_wrong_schema_revision() {
let json = analysis_json(&simple_module()).replace("\"schema_version\": 3", "\"schema_version\": 2");
let error = parse_and_validate(json.as_bytes(), Path::new("/tmp/index.mq.md"), Path::new("/tmp"))
.unwrap_err();
let json = analysis_json(&simple_module())
.replace("\"schema_version\": 3", "\"schema_version\": 2");
let error = parse_and_validate(
json.as_bytes(),
Path::new("/tmp/index.mq.md"),
Path::new("/tmp"),
)
.unwrap_err();
assert_eq!(error.code, codes::UPSTREAM_CONTRACT);
}
#[test]
fn rejects_source_digest_mismatch() {
let json = analysis_json(&simple_module()).replace(
&sha256_hex("# 标题\n".as_bytes()),
&sha256_hex(b"tampered"),
);
let error = parse_and_validate(json.as_bytes(), Path::new("/tmp/index.mq.md"), Path::new("/tmp"))
.unwrap_err();
let json = analysis_json(&simple_module())
.replace(&sha256_hex("# 标题\n".as_bytes()), &sha256_hex(b"tampered"));
let error = parse_and_validate(
json.as_bytes(),
Path::new("/tmp/index.mq.md"),
Path::new("/tmp"),
)
.unwrap_err();
assert_eq!(error.code, codes::UPSTREAM_CONTRACT);
assert!(error.message.contains("source_digest"));
}
#[test]
fn rejects_escaping_relative_path() {
let json = analysis_json(&simple_module())
.replace("\"relative_path\": \"index.mq.md\"", "\"relative_path\": \"../index.mq.md\"");
let error = parse_and_validate(json.as_bytes(), Path::new("/tmp/index.mq.md"), Path::new("/tmp"))
.unwrap_err();
let json = analysis_json(&simple_module()).replace(
"\"relative_path\": \"index.mq.md\"",
"\"relative_path\": \"../index.mq.md\"",
);
let error = parse_and_validate(
json.as_bytes(),
Path::new("/tmp/index.mq.md"),
Path::new("/tmp"),
)
.unwrap_err();
assert_eq!(error.code, codes::UPSTREAM_CONTRACT);
}
@@ -1513,6 +1611,9 @@ mod tests {
unit_by_id: HashMap::new(),
};
assert_eq!(module.resolve_fragment("缺失"), FragmentResolution::Missing);
assert_eq!(module.resolve_fragment(""), FragmentResolution::DocumentRoot);
assert_eq!(
module.resolve_fragment(""),
FragmentResolution::DocumentRoot
);
}
}
+42 -18
View File
@@ -181,7 +181,10 @@ impl BundleManifest {
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));
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");
@@ -250,21 +253,27 @@ impl Bundle {
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")
})?;
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()),
format!(
"cannot read proof payload `{}`: {error}",
payload_path.display()
),
)
})?;
if payload.len() as u64 != manifest.proof.bytes {
@@ -323,7 +332,9 @@ impl CacheIdentity {
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"));
buffer.push_str(&format!(
"source:{locator}\0{source_digest}\0{analysis_digest}\n"
));
}
let mut declared = self.declared.clone();
declared.sort();
@@ -396,7 +407,10 @@ impl CacheStore {
std::fs::remove_dir_all(&directory).map_err(|error| {
Failure::new(
codes::CERTIFICATE_INVALID,
format!("cannot replace stale cache entry `{}`: {error}", directory.display()),
format!(
"cannot replace stale cache entry `{}`: {error}",
directory.display()
),
)
})?;
}
@@ -422,7 +436,10 @@ fn publish_manifest_and_payload(
std::fs::create_dir_all(parent).map_err(|error| {
Failure::new(
codes::CERTIFICATE_INVALID,
format!("cannot create bundle parent `{}`: {error}", parent.display()),
format!(
"cannot create bundle parent `{}`: {error}",
parent.display()
),
)
})?;
let unique = format!(
@@ -437,7 +454,10 @@ fn publish_manifest_and_payload(
std::fs::create_dir(&temporary).map_err(|error| {
Failure::new(
codes::CERTIFICATE_INVALID,
format!("cannot create temporary bundle `{}`: {error}", temporary.display()),
format!(
"cannot create temporary bundle `{}`: {error}",
temporary.display()
),
)
})?;
let result = (|| -> Result<()> {
@@ -487,7 +507,10 @@ fn write_file(path: &Path, bytes: &[u8]) -> Result<()> {
}
fn is_hex_sha256(value: &str) -> bool {
value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
}
fn invalid<T>(message: impl Into<String>) -> Result<T> {
@@ -573,7 +596,8 @@ mod tests {
#[test]
fn rejects_payload_digest_mismatch_when_loading() {
let root = std::env::temp_dir().join(format!("marqdo-prove-cert-test-{}", std::process::id()));
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();
+227 -40
View File
@@ -165,7 +165,9 @@ pub fn resolve_selection(module: &ModuleData, fragment: &str) -> Result<String,
candidates.join(", ")
),
)
.with_hint("copy the exact heading anchor from the document; Prove never picks the first match")),
.with_hint(
"copy the exact heading anchor from the document; Prove never picks the first match",
)),
FragmentResolution::DocumentRoot => Err(Diagnostic::error(
codes::DOCUMENT_UNIT,
"`--unit` must address one Knowledge H2, not the document root",
@@ -181,7 +183,10 @@ fn build_unit(
if unit.mode != "knowledge" {
return Err(Diagnostic::error(
codes::DOCUMENT_UNIT,
format!("proof target `{}` is not in effective Knowledge mode", display_path(unit)),
format!(
"proof target `{}` is not in effective Knowledge mode",
display_path(unit)
),
)
.at(unit.heading_span.unwrap_or(unit.span)));
}
@@ -198,7 +203,10 @@ fn build_unit(
if dependency_unit.path.last().map(String::as_str) != Some(DEPENDENCIES_HEADING) {
return Err(Diagnostic::error(
codes::DOCUMENT_DEPENDENCIES_SHAPE,
format!("dependency heading of `{}` is not canonical", display_path(unit)),
format!(
"dependency heading of `{}` is not canonical",
display_path(unit)
),
)
.at(dependency_unit.heading_span.unwrap_or(dependency_unit.span)));
}
@@ -211,7 +219,10 @@ fn build_unit(
let dependency_heading_span = dependency_unit.heading_span.ok_or_else(|| {
Diagnostic::error(
codes::DOCUMENT_DEPENDENCIES_SHAPE,
format!("`{DEPENDENCIES_HEADING}` of `{}` has no heading span", display_path(unit)),
format!(
"`{DEPENDENCIES_HEADING}` of `{}` has no heading span",
display_path(unit)
),
)
})?;
@@ -241,7 +252,10 @@ fn build_unit(
let literal = math_block.literal.clone().ok_or_else(|| {
Diagnostic::error(
codes::DOCUMENT_GOAL_COUNT,
format!("selected math block of `{}` has no literal", display_path(unit)),
format!(
"selected math block of `{}` has no literal",
display_path(unit)
),
)
.at(math_block.span)
})?;
@@ -266,7 +280,8 @@ fn build_unit(
}
let payload_span = locate_payload(&module.source, math_block, &literal);
let dependencies = extract_dependencies(module, unit, dependency_unit, dependency_heading_span)?;
let dependencies =
extract_dependencies(module, unit, dependency_unit, dependency_heading_span)?;
Ok(ProofUnit {
module_id: module.id.clone(),
@@ -290,9 +305,7 @@ fn direct_dependency_units<'a>(module: &'a ModuleData, unit: &'a Unit) -> Vec<&'
module
.children_of(&unit.id)
.filter(|child| {
child.level == 3
&& child.name == DEPENDENCIES_HEADING
&& child.kind == "section"
child.level == 3 && child.name == DEPENDENCIES_HEADING && child.kind == "section"
})
.collect()
}
@@ -347,7 +360,10 @@ fn extract_dependencies(
if dependency_unit.span.start > unit.span.end || dependency_unit.span.end > unit.span.end {
return Err(Diagnostic::error(
codes::DOCUMENT_DEPENDENCIES_SHAPE,
format!("`{DEPENDENCIES_HEADING}` section of `{}` is not inside the H2", display_path(unit)),
format!(
"`{DEPENDENCIES_HEADING}` section of `{}` is not inside the H2",
display_path(unit)
),
)
.at(dependency_heading_span));
}
@@ -407,7 +423,10 @@ fn extract_dependencies(
return Err(shape_error(
unit,
item.span,
format!("`{DEPENDENCIES_HEADING}` contains a non-item node `{}`", item.kind),
format!(
"`{DEPENDENCIES_HEADING}` contains a non-item node `{}`",
item.kind
),
"the dependency list must contain only bullet items",
));
}
@@ -495,12 +514,7 @@ fn locate_payload(source: &str, math_block: &Node, literal: &str) -> Option<Span
}
}
fn shape_error(
unit: &Unit,
span: Span,
message: String,
hint: &'static str,
) -> Diagnostic {
fn shape_error(unit: &Unit, span: Span, message: String, hint: &'static str) -> Diagnostic {
Diagnostic::error(
codes::DOCUMENT_DEPENDENCIES_SHAPE,
format!("{}: {message}", display_path(unit)),
@@ -523,7 +537,17 @@ mod tests {
use crate::analysis::ModuleData;
use std::collections::{BTreeMap, HashMap};
fn unit(id: &str, path: &[&str], parent: Option<&str>, kind: &str, name: &str, level: u32, heading: Span, span: Span) -> Unit {
#[allow(clippy::too_many_arguments)]
fn unit(
id: &str,
path: &[&str],
parent: Option<&str>,
kind: &str,
name: &str,
level: u32,
heading: Span,
span: Span,
) -> Unit {
serde_json::from_value(serde_json::json!({
"id": id,
"path": path,
@@ -541,7 +565,14 @@ mod tests {
.expect("unit fixture")
}
fn node(kind: &str, span: Span, literal: Option<&str>, level: Option<u32>, url: Option<&str>, children: Vec<Node>) -> Node {
fn node(
kind: &str,
span: Span,
literal: Option<&str>,
level: Option<u32>,
url: Option<&str>,
children: Vec<Node>,
) -> Node {
Node {
kind: kind.to_string(),
span,
@@ -583,8 +614,26 @@ mod tests {
// 29..38 "### 证明依赖"
let root_id = "root:test::doc.mq.md#";
let units = vec![
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 15), Span::new(0, source.len())),
unit(
root_id,
&[],
None,
"root",
"",
0,
Span::new(0, 0),
Span::new(0, source.len()),
),
unit(
"root:test::doc.mq.md#A",
&["A"],
Some(root_id),
"knowledge",
"A",
2,
Span::new(0, 15),
Span::new(0, source.len()),
),
unit(
"root:test::doc.mq.md#A/证明依赖",
&["A", "证明依赖"],
@@ -604,7 +653,14 @@ mod tests {
None,
vec![
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
node("math_block", Span::new(17, 25), Some("x=1"), None, None, vec![]),
node(
"math_block",
Span::new(17, 25),
Some("x=1"),
None,
None,
vec![],
),
node("heading", Span::new(29, 38), None, Some(3), None, vec![]),
],
);
@@ -631,8 +687,26 @@ mod tests {
let source = "## @knowledge A\n\n$$x=1$$\n";
let root_id = "root:test::doc.mq.md#";
let units = vec![
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 15), Span::new(0, source.len())),
unit(
root_id,
&[],
None,
"root",
"",
0,
Span::new(0, 0),
Span::new(0, source.len()),
),
unit(
"root:test::doc.mq.md#A",
&["A"],
Some(root_id),
"knowledge",
"A",
2,
Span::new(0, 15),
Span::new(0, source.len()),
),
];
let document = node(
"document",
@@ -642,7 +716,14 @@ mod tests {
None,
vec![
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
node("math_block", Span::new(17, 22), Some("x=1"), None, None, vec![]),
node(
"math_block",
Span::new(17, 22),
Some("x=1"),
None,
None,
vec![],
),
],
);
assert!(extract(&module_with(source, units, document)).is_empty());
@@ -653,8 +734,26 @@ mod tests {
let source = "## @knowledge A\n\n$$x=1$$\n\n$$y=2$$\n\n### 证明依赖\n";
let root_id = "root:test::doc.mq.md#";
let units = vec![
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 15), Span::new(0, source.len())),
unit(
root_id,
&[],
None,
"root",
"",
0,
Span::new(0, 0),
Span::new(0, source.len()),
),
unit(
"root:test::doc.mq.md#A",
&["A"],
Some(root_id),
"knowledge",
"A",
2,
Span::new(0, 15),
Span::new(0, source.len()),
),
unit(
"root:test::doc.mq.md#A/证明依赖",
&["A", "证明依赖"],
@@ -674,8 +773,22 @@ mod tests {
None,
vec![
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
node("math_block", Span::new(17, 24), Some("x=1"), None, None, vec![]),
node("math_block", Span::new(26, 33), Some("y=2"), None, None, vec![]),
node(
"math_block",
Span::new(17, 24),
Some("x=1"),
None,
None,
vec![],
),
node(
"math_block",
Span::new(26, 33),
Some("y=2"),
None,
None,
vec![],
),
node("heading", Span::new(33, 44), None, Some(3), None, vec![]),
],
);
@@ -684,7 +797,9 @@ mod tests {
match &extracted[0] {
Extraction::Invalid(diagnostic) => {
assert_eq!(diagnostic.code, codes::DOCUMENT_GOAL_COUNT);
assert!(diagnostic.message.contains("exactly one display math block"));
assert!(diagnostic
.message
.contains("exactly one display math block"));
}
other => panic!("expected invalid, got {other:?}"),
}
@@ -692,11 +807,30 @@ mod tests {
#[test]
fn dependency_list_must_be_one_link_per_item() {
let source = "## @knowledge A\n\n$$x=1$$\n\n### 证明依赖\n\n- [x](other.mq.md#B) and text\n";
let source =
"## @knowledge A\n\n$$x=1$$\n\n### 证明依赖\n\n- [x](other.mq.md#B) and text\n";
let root_id = "root:test::doc.mq.md#";
let units = vec![
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 15), Span::new(0, source.len())),
unit(
root_id,
&[],
None,
"root",
"",
0,
Span::new(0, 0),
Span::new(0, source.len()),
),
unit(
"root:test::doc.mq.md#A",
&["A"],
Some(root_id),
"knowledge",
"A",
2,
Span::new(0, 15),
Span::new(0, source.len()),
),
unit(
"root:test::doc.mq.md#A/证明依赖",
&["A", "证明依赖"],
@@ -715,11 +849,32 @@ mod tests {
None,
None,
vec![
node("link", Span::new(42, 62), None, None, Some("other.mq.md#B"), vec![]),
node("text", Span::new(62, source.len() - 1), Some(" and text"), None, None, vec![]),
node(
"link",
Span::new(42, 62),
None,
None,
Some("other.mq.md#B"),
vec![],
),
node(
"text",
Span::new(62, source.len() - 1),
Some(" and text"),
None,
None,
vec![],
),
],
);
let item = node("item", Span::new(39, source.len() - 1), None, None, None, vec![paragraph]);
let item = node(
"item",
Span::new(39, source.len() - 1),
None,
None,
None,
vec![paragraph],
);
let list = Node {
kind: "list".to_string(),
span: Span::new(39, source.len() - 1),
@@ -736,7 +891,14 @@ mod tests {
None,
vec![
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
node("math_block", Span::new(17, 25), Some("x=1"), None, None, vec![]),
node(
"math_block",
Span::new(17, 25),
Some("x=1"),
None,
None,
vec![],
),
node("heading", Span::new(29, 38), None, Some(3), None, vec![]),
list,
],
@@ -756,8 +918,26 @@ mod tests {
let source = "## A\n";
let root_id = "root:test::doc.mq.md#";
let units = vec![
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 4), Span::new(0, source.len())),
unit(
root_id,
&[],
None,
"root",
"",
0,
Span::new(0, 0),
Span::new(0, source.len()),
),
unit(
"root:test::doc.mq.md#A",
&["A"],
Some(root_id),
"knowledge",
"A",
2,
Span::new(0, 4),
Span::new(0, source.len()),
),
];
let document = node(
"document",
@@ -765,7 +945,14 @@ mod tests {
None,
None,
None,
vec![node("heading", Span::new(0, 4), None, Some(2), None, vec![])],
vec![node(
"heading",
Span::new(0, 4),
None,
Some(2),
None,
vec![],
)],
);
let module = module_with(source, units, document);
let error = resolve_selection(&module, "A").unwrap_err();
+1 -1
View File
@@ -2031,7 +2031,7 @@ mod tests {
fn ten_pow(exponent: u32) -> BigInt {
let mut value = BigInt::from(1);
for _ in 0..exponent {
value = value * BigInt::from(10);
value *= BigInt::from(10);
}
value
}
+71 -35
View File
@@ -172,14 +172,15 @@ impl LeanBackend {
}
let mut command = self.lake_command()?;
command.args(["build", "marqdo-replay"]);
let output = self.run(command, Duration::from_secs(900), "lake build marqdo-replay")?;
let output = self.run(
command,
Duration::from_secs(900),
"lake build marqdo-replay",
)?;
if !output.status_success {
return Err(Failure::new(
codes::BACKEND_UNAVAILABLE,
format!(
"cannot build the fixed verifier: {}",
tail(&output.stderr)
),
format!("cannot build the fixed verifier: {}", tail(&output.stderr)),
));
}
if !self.config.replay_bin.is_file() {
@@ -193,18 +194,20 @@ impl LeanBackend {
fn compute_identity(&self) -> Result<EnvironmentIdentity> {
let lean_root = &self.config.lean_root;
let toolchain = std::fs::read_to_string(lean_root.join("lean-toolchain")).map_err(|error| {
Failure::new(
codes::BACKEND_UNAVAILABLE,
format!("cannot read lean-toolchain: {error}"),
)
})?;
let manifest_bytes = std::fs::read(lean_root.join("lake-manifest.json")).map_err(|error| {
Failure::new(
codes::BACKEND_UNAVAILABLE,
format!("cannot read lake-manifest.json: {error}"),
)
})?;
let toolchain =
std::fs::read_to_string(lean_root.join("lean-toolchain")).map_err(|error| {
Failure::new(
codes::BACKEND_UNAVAILABLE,
format!("cannot read lean-toolchain: {error}"),
)
})?;
let manifest_bytes =
std::fs::read(lean_root.join("lake-manifest.json")).map_err(|error| {
Failure::new(
codes::BACKEND_UNAVAILABLE,
format!("cannot read lake-manifest.json: {error}"),
)
})?;
let manifest: LakeManifest = serde_json::from_slice(&manifest_bytes).map_err(|error| {
Failure::new(
codes::BACKEND_UNAVAILABLE,
@@ -228,7 +231,10 @@ impl LeanBackend {
let lean_version = parse_lean_version(&version.stdout).ok_or_else(|| {
Failure::new(
codes::BACKEND_UNAVAILABLE,
format!("unexpected `lean --version` output: {}", tail(&version.stdout)),
format!(
"unexpected `lean --version` output: {}",
tail(&version.stdout)
),
)
})?;
let replay_digest = sha256_file(&self.config.replay_bin)?;
@@ -314,7 +320,10 @@ impl LeanBackend {
if let Err(failure) = compile {
let detail = failure.message.clone();
if std::env::var_os("MARQDO_PROVE_KEEP_GENERATED").is_some() {
eprintln!("marqdo-prove: kept failed generated module {}", target_path.display());
eprintln!(
"marqdo-prove: kept failed generated module {}",
target_path.display()
);
} else {
let _ = std::fs::remove_file(&target_path);
}
@@ -349,7 +358,8 @@ impl LeanBackend {
format!("cannot stage expected proposition: {error}"),
)
})?;
let verified = self.verify_staged(&payload_path, &expected_path, &theorem_name, &expected_name);
let verified =
self.verify_staged(&payload_path, &expected_path, &theorem_name, &expected_name);
let _ = std::fs::remove_file(&payload_path);
let _ = std::fs::remove_file(&expected_path);
let evidence = verified?;
@@ -367,6 +377,7 @@ impl LeanBackend {
/// This is the replay path: it never runs proof search, never imports the
/// payload's `.olean`, and accepts only a kernel-replayed proof whose type
/// matches the expected proposition.
#[allow(clippy::too_many_arguments)]
pub fn verify_payload(
&self,
key: &str,
@@ -427,7 +438,8 @@ impl LeanBackend {
format!("cannot stage expected proposition: {error}"),
)
})?;
let evidence = self.verify_staged(&payload_path, &expected_path, theorem_name, expected_name);
let evidence =
self.verify_staged(&payload_path, &expected_path, theorem_name, expected_name);
let _ = std::fs::remove_file(&payload_path);
let _ = std::fs::remove_file(&expected_path);
let evidence = evidence?;
@@ -462,7 +474,10 @@ impl LeanBackend {
if !output.status_success {
return Err(Failure::new(
codes::PROOF_REPLAY_FAILED,
format!("independent kernel replay rejected the payload: {}", tail(&output.stderr)),
format!(
"independent kernel replay rejected the payload: {}",
tail(&output.stderr)
),
));
}
// Statement/axiom verifier.
@@ -492,7 +507,10 @@ impl LeanBackend {
let report: ReplayReport = serde_json::from_str(&report_text).map_err(|error| {
Failure::new(
codes::PROOF_REPLAY_FAILED,
format!("verifier produced an unreadable report: {error}: {}", tail(&output.stdout)),
format!(
"verifier produced an unreadable report: {error}: {}",
tail(&output.stdout)
),
)
})?;
if !report.ok {
@@ -589,7 +607,10 @@ impl LeanBackend {
std::fs::write(&path, source).map_err(|error| {
Failure::new(
codes::BACKEND_UNAVAILABLE,
format!("cannot write generated Lean source `{}`: {error}", path.display()),
format!(
"cannot write generated Lean source `{}`: {error}",
path.display()
),
)
})?;
Ok(path)
@@ -883,12 +904,11 @@ fn render_target_module(
source.push_str(" exact absurd hypothesis (by decide)\n");
}
} else {
source.push_str(&format!("public theorem {theorem_name} : {statement} := by\n"));
source.push_str(&format!(
"public theorem {theorem_name} : {statement} := by\n"
));
if !attempt.variable_names.is_empty() {
source.push_str(&format!(
" intros {}\n",
attempt.variable_names.join(" ")
));
source.push_str(&format!(" intros {}\n", attempt.variable_names.join(" ")));
}
source.push_str(" intros\n");
if !attempt.model_sources.is_empty() {
@@ -934,7 +954,9 @@ fn render_expected_module(
"public def {expected_name} : Prop := ¬ ({statement})\n"
));
} else {
source.push_str(&format!("public def {expected_name} : Prop := {statement}\n"));
source.push_str(&format!(
"public def {expected_name} : Prop := {statement}\n"
));
}
let _ = module_name;
source
@@ -1014,7 +1036,11 @@ fn parse_lean_version(stdout: &[u8]) -> Option<String> {
if version.is_empty() {
None
} else {
Some(version.trim_matches(|c: char| !c.is_ascii_digit() && c != '.').to_string())
Some(
version
.trim_matches(|c: char| !c.is_ascii_digit() && c != '.')
.to_string(),
)
}
}
@@ -1034,7 +1060,10 @@ fn spawn_pipe_reader<T: Read + Send + 'static>(pipe: Option<T>) -> Option<PipeRe
pipe.map(|mut pipe| {
std::thread::spawn(move || {
let mut buffer = Vec::new();
let _ = pipe.by_ref().take(64 * 1024 * 1024).read_to_end(&mut buffer);
let _ = pipe
.by_ref()
.take(64 * 1024 * 1024)
.read_to_end(&mut buffer);
buffer
})
})
@@ -1140,7 +1169,8 @@ mod tests {
hint_terms: vec!["sq_nonneg mqx0".to_string()],
variable_names: vec!["mqx0".to_string()],
};
let source = render_target_module("m", "marqdoTarget_abc", &attempt.statement_source, &attempt);
let source =
render_target_module("m", "marqdoTarget_abc", &attempt.statement_source, &attempt);
assert!(source.contains("public theorem marqdoTarget_abc : ∀ mqx0 : Int,"));
assert!(source.contains("public import MarqdoProof.Generated.Target_dep"));
assert!(source.contains("intros mqx0"));
@@ -1164,7 +1194,8 @@ mod tests {
hint_terms: vec![],
variable_names: vec!["mqx0".to_string(), "mqx1".to_string()],
};
let source = render_target_module("m", "marqdoTarget_abc", &attempt.statement_source, &attempt);
let source =
render_target_module("m", "marqdoTarget_abc", &attempt.statement_source, &attempt);
assert!(source.contains("¬ (∀ mqx0 : Int, ...)"));
assert!(source.contains("have counterexample := hypothesis (0 : Int) (-1 : Int)"));
assert!(source.contains("exact absurd counterexample (by decide)"));
@@ -1183,7 +1214,12 @@ mod tests {
hint_terms: vec![],
variable_names: vec![],
};
let source = render_expected_module("m", "marqdoExpected_abc", &attempt.statement_source, &attempt);
let source = render_expected_module(
"m",
"marqdoExpected_abc",
&attempt.statement_source,
&attempt,
);
assert!(source.contains("public def marqdoExpected_abc : Prop :="));
assert!(!source.contains("theorem"));
assert!(!source.contains("by "));
+78 -48
View File
@@ -14,9 +14,7 @@ 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::analysis::{AnalysisBackend, FragmentResolution, Function, ModuleData, Snapshot, Unit};
use crate::document::{self, DependencyLink, Extraction, ProofUnit};
use crate::{codes, Diagnostic, Failure, Span};
@@ -47,9 +45,8 @@ impl DependencyTarget {
pub fn snapshot(&self) -> &Arc<Snapshot> {
match self {
DependencyTarget::Theorem { snapshot, .. } | DependencyTarget::Model { snapshot, .. } => {
snapshot
}
DependencyTarget::Theorem { snapshot, .. }
| DependencyTarget::Model { snapshot, .. } => snapshot,
}
}
@@ -61,18 +58,25 @@ impl DependencyTarget {
}
}
/// Portable locator: `relative_path#fragment-of-unit`.
/// Portable locator: `<relative_path>#<canonical unit path joined by />`.
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()),
let (snapshot, unit_id) = match self {
DependencyTarget::Theorem {
snapshot, unit_id, ..
}
| DependencyTarget::Model {
snapshot, unit_id, ..
} => (snapshot, unit_id),
};
fragment
snapshot
.modules
.values()
.find_map(|module| {
module
.unit(unit_id)
.map(|unit| format!("{}#{}", module.relative_path, unit.path.join("/")))
})
.unwrap_or_else(|| unit_id.clone())
}
}
@@ -98,7 +102,10 @@ pub struct LoadedUnit {
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())
(
self.snapshot.canonical_path.clone(),
self.proof_unit.unit_id.clone(),
)
}
}
@@ -161,7 +168,10 @@ impl Linker {
let root = std::fs::canonicalize(&root).map_err(|error| {
Failure::new(
codes::LINK_OUTSIDE_ROOT,
format!("cannot canonicalize the controlled root `{}`: {error}", root.display()),
format!(
"cannot canonicalize the controlled root `{}`: {error}",
root.display()
),
)
})?;
Ok(Self {
@@ -238,14 +248,16 @@ impl Linker {
let module = snapshot.entry().clone();
document::extract(&module)
.into_iter()
.map(|extraction| {
if let Extraction::Invalid(diagnostic) = &extraction {
.inspect(|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());
.insert(
format!("invalid@{}", diagnostic.span.map(|s| s.start).unwrap_or(0)),
extraction.clone(),
);
}
extraction
})
.collect()
}
@@ -263,7 +275,8 @@ impl Linker {
};
map.insert(unit_id, extraction);
}
self.extraction_cache.insert(path.to_path_buf(), map.clone());
self.extraction_cache
.insert(path.to_path_buf(), map.clone());
map
}
@@ -277,7 +290,7 @@ impl Linker {
selection: &[String],
) -> Result<Closure, Failure> {
let entry_path = entry.canonical_path.clone();
let extraction = self.extraction(&entry.entry(), &entry_path);
let extraction = self.extraction(entry.entry(), &entry_path);
let mut diagnostics: Vec<Diagnostic> = Vec::new();
// Selected entry units.
@@ -308,7 +321,6 @@ impl Linker {
documents: BTreeMap::new(),
units: HashMap::new(),
diagnostics,
depth: 0,
};
loader.documents.insert(entry_path.clone(), entry.clone());
for unit_id in roots {
@@ -362,8 +374,11 @@ impl Linker {
}
}
}
diagnostics.extend(std::mem::take(&mut closure.cycles).into_iter().map(|cycle| {
Diagnostic::error(
diagnostics.extend(
std::mem::take(&mut closure.cycles)
.into_iter()
.map(|cycle| {
Diagnostic::error(
codes::LINK_CYCLE,
format!("dependency cycle: {}", cycle.join(" -> ")),
)
@@ -371,7 +386,8 @@ impl Linker {
"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)
@@ -402,7 +418,11 @@ impl Linker {
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")
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(
@@ -432,7 +452,11 @@ impl Linker {
}
"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")
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))?;
@@ -447,9 +471,9 @@ impl Linker {
));
}
let physical = self.root.join(&candidate_path);
let snapshot = self.load_document(&physical).map_err(|failure| {
link_error(link, failure.code, failure.message)
})?;
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()
@@ -475,9 +499,7 @@ impl Linker {
return Err(link_error(
link,
codes::LINK_CONTEXT_CONFLICT,
format!(
"document `{candidate_path}` has an incompatible project context"
),
format!("document `{candidate_path}` has an incompatible project context"),
));
}
let fragment = reference.fragment.clone().unwrap_or_default();
@@ -545,7 +567,10 @@ impl Linker {
"invalid" => Err(link_error(
link,
codes::LINK_INVALID,
format!("dependency link `{}` is not a valid local document link", link.url),
format!(
"dependency link `{}` is not a valid local document link",
link.url
),
)),
"external" => Err(link_error(
link,
@@ -583,7 +608,10 @@ impl Linker {
return Err(link_error(
link,
codes::LINK_INVALID,
format!("`{}` is an Exec section but not a function declaration", link.url),
format!(
"`{}` is an Exec section but not a function declaration",
link.url
),
));
}
let function = module
@@ -610,8 +638,7 @@ impl Linker {
format!(
"dependency link `{}` must select a Knowledge H2 (theorem) or an Exec H2 \
(program model), not `{}`",
link.url,
unit.kind
link.url, unit.kind
),
));
}
@@ -650,7 +677,6 @@ struct ClosureLoader<'a> {
documents: BTreeMap<PathBuf, Arc<Snapshot>>,
units: HashMap<(PathBuf, String), LoadedUnit>,
diagnostics: Vec<Diagnostic>,
depth: usize,
}
impl<'a> ClosureLoader<'a> {
@@ -714,10 +740,7 @@ impl<'a> ClosureLoader<'a> {
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)
{
match self.linker.resolve_link(&path, &snapshot, &module, link) {
Ok(dependency) => {
let dependency_key = dependency.target.snapshot().canonical_path.clone();
self.documents
@@ -779,7 +802,10 @@ fn visit(
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 {
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);
}
@@ -793,7 +819,9 @@ fn visit(
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")
.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.
@@ -802,7 +830,9 @@ pub fn validate_relative_path(path: &str) -> std::result::Result<(), String> {
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"));
return Err(format!(
"link target path `{path}` is absolute or uses a platform separator"
));
}
if let Some((before, _)) = path.split_once(':') {
let scheme = before;
+2 -8
View File
@@ -96,15 +96,9 @@ fn emit(report: prove::Report, json: bool) -> u8 {
}
}
} else {
print!("{}", report.render_text());
// Diagnostics are already part of the textual rendering; progress and
// Diagnostics are 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
);
}
print!("{}", report.render_text());
}
status.exit_code() as u8
}
+79 -45
View File
@@ -154,11 +154,11 @@ pub fn build_model(
}
// Validate the straight-line body shape: assignments..., one final return.
let mut statements = function.body.iter();
let 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() {
for statement in statements {
validate_span(module, statement.span(), "statement")?;
if returned.is_some() {
return Err(unsupported(
@@ -183,7 +183,10 @@ pub fn build_model(
));
};
if name.is_empty() {
return Err(unsupported(statement.span(), "empty local assignment target"));
return Err(unsupported(
statement.span(),
"empty local assignment target",
));
}
assignments.push((name.as_str(), value));
}
@@ -219,7 +222,10 @@ pub fn build_model(
Statement::Break { .. } => {
return Err(unsupported(
statement.span(),
format!("function `{}` uses `break` outside a supported loop", function.local_name),
format!(
"function `{}` uses `break` outside a supported loop",
function.local_name
),
))
}
Statement::Continue { .. } => {
@@ -295,7 +301,13 @@ pub fn build_model(
.map(|name| format!("{name}: Int"))
.collect::<Vec<_>>()
.join(", "),
render_summary(return_expression, &assignments, &environment, module, function)?
render_summary(
return_expression,
&assignments,
&environment,
module,
function
)?
);
Ok(ModelDef {
function_id: function.id.clone(),
@@ -337,7 +349,10 @@ fn render_lean(
));
}
let Some(serde_json::Value::String(text)) = value else {
return Err(unsupported(*span, "integer literal has a non-string Analysis value"));
return Err(unsupported(
*span,
"integer literal has a non-string Analysis value",
));
};
if text.len() > crate::limits::MAX_LITERAL_DIGITS {
return Err(unsupported(
@@ -428,29 +443,25 @@ fn render_original(
function: &Function,
) -> std::result::Result<String, Diagnostic> {
let _ = environment;
render_pretty(expression, module, function)
let _ = module;
render_pretty(expression, function)
}
fn render_pretty(
expression: &Expression,
module: &ModuleData,
function: &Function,
) -> std::result::Result<String, Diagnostic> {
match expression {
Expression::Literal { ty, value, .. } => {
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")
})?;
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::Unary { operand, .. } => Ok(format!("-{}", render_pretty(operand, function)?)),
Expression::Binary {
op, left, right, ..
} => {
@@ -467,8 +478,8 @@ fn render_pretty(
};
Ok(format!(
"({} {operator} {})",
render_pretty(left, module, function)?,
render_pretty(right, module, function)?
render_pretty(left, function)?,
render_pretty(right, function)?
))
}
other => Err(unsupported(
@@ -594,11 +605,11 @@ mod tests {
}
}
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 {
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",
@@ -647,7 +658,8 @@ mod tests {
#[test]
fn square_model_maps_to_exact_lean_definition() {
let function = function_fixture(serde_json::json!([return_stmt(binary("mul", variable("x"), variable("x")))]),
let function = function_fixture(
serde_json::json!([return_stmt(binary("mul", variable("x"), variable("x")))]),
serde_json::json!([int_param("x", 20, 30)]),
"explicit",
);
@@ -657,11 +669,18 @@ mod tests {
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"
"@[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));
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);
@@ -670,7 +689,8 @@ mod tests {
#[test]
fn zero_parameter_constant_model() {
let function = function_fixture(serde_json::json!([return_stmt(int_literal("42"))]),
let function = function_fixture(
serde_json::json!([return_stmt(int_literal("42"))]),
serde_json::json!([]),
"explicit",
);
@@ -681,7 +701,8 @@ mod tests {
#[test]
fn rebinding_creates_fresh_slots() {
let function = function_fixture(serde_json::json!([
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"))
@@ -698,7 +719,8 @@ mod tests {
#[test]
fn negative_literals_and_unary_minus_render_exactly() {
let function = function_fixture(serde_json::json!([return_stmt(serde_json::json!({
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}
}))]),
@@ -717,14 +739,16 @@ mod tests {
fn rejects_unsupported_shapes() {
let cases: Vec<(Function, &str)> = vec![
(
function_fixture(serde_json::json!([return_stmt(variable("x"))]),
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"))]),
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}
@@ -734,35 +758,44 @@ mod tests {
"type",
),
(
function_fixture(serde_json::json!([return_stmt(int_literal("1.5"))]),
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")))]),
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"))]),
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"))]),
function_fixture(
serde_json::json!([assign("x", int_literal("1"))]),
serde_json::json!([]),
"explicit",
),
"return",
),
(
function_fixture(serde_json::json!([
function_fixture(
serde_json::json!([
return_stmt(int_literal("1")),
assign("x", int_literal("2"))
]),
@@ -772,7 +805,8 @@ mod tests {
"after",
),
(
function_fixture(serde_json::json!([{
function_fixture(
serde_json::json!([{
"kind": "branch",
"arms": [{"condition": int_literal("1"), "condition_span": {"start": 0, "end": 1},
"body": [], "span": {"start": 0, "end": 1}}],
@@ -788,22 +822,21 @@ mod tests {
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:?}"
);
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))]),
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"))]),
let function = function_fixture(
serde_json::json!([return_stmt(int_literal("00042"))]),
serde_json::json!([]),
"explicit",
);
@@ -813,7 +846,8 @@ mod tests {
#[test]
fn index_place_assignment_is_rejected() {
let function = function_fixture(serde_json::json!([{
let function = function_fixture(
serde_json::json!([{
"kind": "assign",
"target": {"kind": "index", "base": variable("x"),
"index": int_literal("0"), "span": {"start": 0, "end": 10}},
+217 -171
View File
@@ -8,7 +8,6 @@
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use num_bigint::BigInt;
use serde::Serialize;
@@ -19,7 +18,7 @@ use crate::certificate::{
ProofPayload, SourceBinding, TargetIdentity, ToolIdentity, ALLOWED_AXIOMS, PAYLOAD_FILE,
};
use crate::document::{self, Extraction, ProofUnit};
use crate::formula::{self, FormulaError, Goal};
use crate::formula::{self, FormulaError, FormulaErrorKind, Goal};
use crate::lean::{Attempt, Evidence, LeanBackend, ModelSource, ProofAttempt};
use crate::linker::{Closure, DependencyTarget, Linker, LoadedUnit};
use crate::model::{self, ModelDef};
@@ -149,17 +148,18 @@ pub struct Report {
impl Report {
pub fn status(&self) -> RunStatus {
if self.status == "failure" {
RunStatus::Failure
} else {
match self.targets.as_slice() {
[] => RunStatus::Success,
targets => {
if targets.iter().all(|target| target.outcome == "verified") {
RunStatus::Success
} else {
RunStatus::Unverified
}
match self.status.as_str() {
"failure" => RunStatus::Failure,
"unverified" => RunStatus::Unverified,
_ => {
if self
.targets
.iter()
.all(|target| target.outcome == "verified")
{
RunStatus::Success
} else {
RunStatus::Unverified
}
}
}
@@ -178,7 +178,7 @@ impl Report {
target.outcome, target.title, target.scope, target.freshness
));
out.push_str(&format!(
" source: {}# {}\n",
" source: {} ({})\n",
target.source.locator, target.source.unit_id
));
out.push_str(&format!(" statement: {}\n", target.statement.normalized));
@@ -207,8 +207,8 @@ impl Report {
let unused: Vec<&str> = target
.declared_dependencies
.iter()
.map(|dependency| dependency.unit_id.as_str())
.filter(|unit_id| !target.used_dependencies.iter().any(|used| used == unit_id))
.map(|dependency| dependency.locator.as_str())
.filter(|locator| !target.used_dependencies.iter().any(|used| used == locator))
.collect();
if !unused.is_empty() {
out.push_str(&format!(" declared but not used: {}\n", unused.join(", ")));
@@ -281,11 +281,13 @@ pub fn run(invocation: Invocation) -> Report {
}
fn marqdo_bin() -> Result<PathBuf> {
let bin = std::env::var_os("MARQDO_BIN").map(PathBuf::from).unwrap_or_else(|| {
// Tool installs always inject an absolute MARQDO_BIN; a developer build
// may rely on PATH, which we resolve explicitly here.
PathBuf::from("marqdo")
});
let bin = std::env::var_os("MARQDO_BIN")
.map(PathBuf::from)
.unwrap_or_else(|| {
// Tool installs always inject an absolute MARQDO_BIN; a developer build
// may rely on PATH, which we resolve explicitly here.
PathBuf::from("marqdo")
});
if bin.is_absolute() {
return Ok(bin);
}
@@ -308,7 +310,6 @@ struct Context {
linker: Linker,
cache: CacheStore,
lean: Option<Arc<LeanBackend>>,
task_started: Instant,
}
impl Context {
@@ -316,15 +317,7 @@ impl Context {
if self.lean.is_none() {
self.lean = Some(Arc::new(LeanBackend::discover()?));
}
Ok(self
.lean
.as_ref()
.expect("just initialized")
.clone())
}
fn work_dir(&self) -> PathBuf {
self.cache.work_dir()
Ok(self.lean.as_ref().expect("just initialized").clone())
}
}
@@ -345,7 +338,6 @@ fn open_context(entry: &Path, explicit_root: Option<&Path>) -> Result<Context> {
linker,
cache,
lean: None,
task_started: Instant::now(),
})
}
@@ -388,12 +380,11 @@ fn check_inner(context: &mut Context, options: &CheckOptions) -> Result<Report>
selected.push((unit.unit_id.clone(), unit.clone()));
found = true;
}
Extraction::Invalid(diagnostic) => {
if diagnostic.code == codes::DOCUMENT_DEPENDENCIES_SHAPE
|| diagnostic.code == codes::DOCUMENT_GOAL_COUNT
{
diagnostics.push(diagnostic.clone());
}
Extraction::Invalid(diagnostic)
if (diagnostic.code == codes::DOCUMENT_DEPENDENCIES_SHAPE
|| diagnostic.code == codes::DOCUMENT_GOAL_COUNT) =>
{
diagnostics.push(diagnostic.clone());
}
_ => {}
}
@@ -432,20 +423,29 @@ fn check_inner(context: &mut Context, options: &CheckOptions) -> Result<Report>
}
}
if selected.is_empty() {
return Ok(empty_report(context, "check", &entry, RunStatus::Success, diagnostics));
return Ok(empty_report(
context,
"check",
&entry,
RunStatus::Success,
diagnostics,
));
}
// Dependency closure.
let selection: Vec<String> = selected.iter().map(|(unit_id, _)| unit_id.clone()).collect();
let selection: Vec<String> = selected
.iter()
.map(|(unit_id, _)| unit_id.clone())
.collect();
let closure = context.linker.resolve_closure(&entry, &selection)?;
diagnostics.extend(closure.diagnostics.iter().cloned());
// Prepare every closure unit (formula + program model validation).
let mut nodes = prepare_closure(&closure, &mut diagnostics);
let nodes = prepare_closure(&closure, &mut diagnostics);
// Process in dependency-first order.
let mut outcomes: HashMap<usize, UnitResult> = HashMap::new();
let indices: Vec<usize> = (0..nodes.len()).collect();
for index in indices {
let result = process_node(context, &mut nodes, &mut outcomes, index);
let result = process_node(context, &nodes, &mut outcomes, index);
outcomes.insert(index, result);
}
// Report selected entry units in document order.
@@ -460,17 +460,21 @@ fn check_inner(context: &mut Context, options: &CheckOptions) -> Result<Report>
let Some(result) = outcomes.get(&index) else {
continue;
};
targets.push(build_target_report(context, &nodes[index], result));
targets.push(build_target_report(context, &nodes, &nodes[index], result));
}
// Export requested bundles.
if let Some(out) = &options.out {
export_bundles(context, &nodes, &outcomes, out, &targets)?;
}
let status = if targets.iter().all(|target| target.outcome == "verified") {
RunStatus::Success
} else {
RunStatus::Unverified
};
let has_error_diagnostic = diagnostics
.iter()
.any(|diagnostic| diagnostic.severity == Severity::Error);
let status =
if !has_error_diagnostic && targets.iter().all(|target| target.outcome == "verified") {
RunStatus::Success
} else {
RunStatus::Unverified
};
let report = Report {
schema: RESULT_SCHEMA.to_string(),
schema_version: RESULT_SCHEMA_VERSION,
@@ -495,6 +499,15 @@ fn empty_report(
status: RunStatus,
diagnostics: Vec<Diagnostic>,
) -> Report {
let status = if status == RunStatus::Success
&& diagnostics
.iter()
.any(|diagnostic| diagnostic.severity == Severity::Error)
{
RunStatus::Unverified
} else {
status
};
Report {
schema: RESULT_SCHEMA.to_string(),
schema_version: RESULT_SCHEMA_VERSION,
@@ -520,12 +533,14 @@ struct PreparedModel {
definition: ModelDef,
link_text: String,
source: ModelSource,
unit_path: Vec<String>,
}
struct PreparedNode {
loaded: LoadedUnit,
goal: Option<Goal>,
formula_error: Option<Diagnostic>,
prepared_outcome: Outcome,
models: Vec<PreparedModel>,
alias_map: BTreeMap<String, String>,
statement_source: String,
@@ -564,6 +579,7 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
loaded: loaded.clone(),
goal: None,
formula_error: None,
prepared_outcome: Outcome::Invalid,
models: Vec::new(),
alias_map: BTreeMap::new(),
statement_source: String::new(),
@@ -604,7 +620,13 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
Err(error) => {
let diagnostic = formula_diagnostic(&loaded, &error);
diagnostics.push(diagnostic.clone());
node.formula_error = Some(diagnostic);
node.formula_error = Some(diagnostic.clone());
node.prepared_error = Some(diagnostic);
node.prepared_outcome = if error.kind == FormulaErrorKind::Unsupported {
Outcome::Unsupported
} else {
Outcome::Invalid
};
continue;
}
}
@@ -612,41 +634,44 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
for dependency in &loaded.dependencies {
match &dependency.target {
DependencyTarget::Theorem {
snapshot,
unit_id,
..
snapshot, unit_id, ..
} => {
let key = (snapshot.canonical_path.clone(), unit_id.clone());
match index_of.get(&key) {
Some(index) => node.theorem_dependencies.push(*index),
None => {
node.prepared_error = Some(Diagnostic::error(
codes::LINK_INVALID,
format!(
"dependency `{}` was not part of the resolved closure",
dependency.link.url
),
)
.at(dependency.link.link_span));
node.prepared_error = Some(
Diagnostic::error(
codes::LINK_INVALID,
format!(
"dependency `{}` was not part of the resolved closure",
dependency.link.url
),
)
.at(dependency.link.link_span),
);
break;
}
}
}
DependencyTarget::Model {
snapshot,
function,
..
snapshot, function, ..
} => {
let module = snapshot
.modules
.values()
.find(|module| module.function(&function.id).is_some());
let Some(module) = module else {
node.prepared_error = Some(Diagnostic::error(
codes::LINK_CONTEXT_CONFLICT,
format!("program model target `{}` is not in its module", dependency.link.url),
)
.at(dependency.link.link_span));
node.prepared_error = Some(
Diagnostic::error(
codes::LINK_CONTEXT_CONFLICT,
format!(
"program model target `{}` is not in its module",
dependency.link.url
),
)
.at(dependency.link.link_span),
);
break;
};
match model::build_model(function, module) {
@@ -667,10 +692,18 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
definition.lean_name.clone(),
);
}
let unit_path = snapshot
.modules
.values()
.find(|module| module.function(&function.id).is_some())
.and_then(|module| module.unit(&function.unit_id))
.map(|unit| unit.path.clone())
.unwrap_or_default();
node.models.push(PreparedModel {
definition,
link_text: dependency.link.text.clone(),
source,
unit_path,
});
}
Err(diagnostic) => {
@@ -718,15 +751,17 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
if node.prepared_error.is_none() {
for model in &node.models {
if !used.contains(&model.link_text) {
node.prepared_error = Some(Diagnostic::error(
codes::MODEL_UNBOUND_ALIAS,
format!(
node.prepared_error = Some(
Diagnostic::error(
codes::MODEL_UNBOUND_ALIAS,
format!(
"program model link `{}` is declared but the formula never calls \
`\\operatorname{{{}}}(...)`",
model.link_text, model.link_text
),
)
.at(node.loaded.proof_unit.goal.block_span));
)
.at(node.loaded.proof_unit.goal.block_span),
);
break;
}
}
@@ -756,12 +791,12 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
fn formula_diagnostic(loaded: &LoadedUnit, error: &FormulaError) -> Diagnostic {
let span = error.offset.and_then(|offset| {
let goal = &loaded.proof_unit.goal;
goal.payload_span.and_then(|payload| {
goal.payload_span.map(|payload| {
let start = payload.start + offset;
if start <= payload.end && start <= loaded.module.source.len() {
Some(Span::new(start, start.min(payload.end)))
Span::new(start, start.min(payload.end))
} else {
Some(goal.block_span)
goal.block_span
}
})
});
@@ -786,7 +821,7 @@ fn formula_diagnostic(loaded: &LoadedUnit, error: &FormulaError) -> Diagnostic {
fn process_node(
context: &mut Context,
nodes: &mut [PreparedNode],
nodes: &[PreparedNode],
outcomes: &mut HashMap<usize, UnitResult>,
index: usize,
) -> UnitResult {
@@ -795,19 +830,14 @@ fn process_node(
(node.theorem_key.clone(), node.scope)
};
if let Some(diagnostic) = nodes[index].prepared_error.clone() {
return simple_result(
Outcome::Invalid,
scope,
vec![diagnostic],
);
let outcome = nodes[index].prepared_outcome;
return simple_result(outcome, scope, vec![diagnostic]);
}
// Blocked dependencies: every declared theorem dependency must be verified.
let mut blocked: Vec<Diagnostic> = Vec::new();
for dependency in &nodes[index].loaded.dependencies {
if let DependencyTarget::Theorem {
snapshot,
unit_id,
..
snapshot, unit_id, ..
} = &dependency.target
{
let found = nodes.iter().position(|node| {
@@ -816,20 +846,27 @@ fn process_node(
});
match found.and_then(|found| outcomes.get(&found)) {
Some(result) if result.outcome == Outcome::Verified => {}
Some(result) => blocked.push(Diagnostic::error(
codes::LINK_MISSING,
format!(
"dependency `{}` has outcome `{}`; it cannot be used as an axiom",
dependency.link.url,
result.outcome.as_str()
),
)
.at(dependency.link.link_span)),
None => blocked.push(Diagnostic::error(
codes::LINK_MISSING,
format!("dependency `{}` was not verified in this run", dependency.link.url),
)
.at(dependency.link.link_span)),
Some(result) => blocked.push(
Diagnostic::error(
codes::LINK_MISSING,
format!(
"dependency `{}` has outcome `{}`; it cannot be used as an axiom",
dependency.link.url,
result.outcome.as_str()
),
)
.at(dependency.link.link_span),
),
None => blocked.push(
Diagnostic::error(
codes::LINK_MISSING,
format!(
"dependency `{}` was not verified in this run",
dependency.link.url
),
)
.at(dependency.link.link_span),
),
}
}
}
@@ -885,12 +922,18 @@ fn process_node(
.theorem_dependencies
.iter()
.map(|dependency| {
format!("MarqdoProof.Generated.Target_{}", nodes[*dependency].theorem_key)
format!(
"MarqdoProof.Generated.Target_{}",
nodes[*dependency].theorem_key
)
})
.collect();
// Ensure every dependency artifact is importable.
for dependency in &nodes[index].theorem_dependencies {
let module = format!("MarqdoProof.Generated.Target_{}", nodes[*dependency].theorem_key);
let module = format!(
"MarqdoProof.Generated.Target_{}",
nodes[*dependency].theorem_key
);
if !lean.build_olean_path(&module).is_file() {
let artifact = context
.cache
@@ -965,10 +1008,7 @@ fn process_node(
key: theorem_key.clone(),
statement_source: nodes[index].statement_source.clone(),
refuted: true,
witnesses: witnesses
.iter()
.map(|value| value.to_string())
.collect(),
witnesses: witnesses.iter().map(|value| value.to_string()).collect(),
model_sources: model_sources.clone(),
imports: Vec::new(),
dependency_names: Vec::new(),
@@ -1023,6 +1063,7 @@ fn process_node(
}
}
#[allow(clippy::too_many_arguments)]
fn replay_cached(
context: &mut Context,
nodes: &[PreparedNode],
@@ -1057,7 +1098,10 @@ fn replay_cached(
Ok(evidence) => {
// Install the artifact so later searches can import this theorem.
let module = format!("MarqdoProof.Generated.Target_{}", nodes[index].theorem_key);
let artifact = context.cache.artifacts_dir().join(format!("{module}.olean"));
let artifact = context
.cache
.artifacts_dir()
.join(format!("{module}.olean"));
if let Ok(bytes) = std::fs::read(&artifact) {
let _ = lean.install_olean(&module, &bytes);
}
@@ -1118,7 +1162,6 @@ fn publish_success(
expected_name: &str,
cache_key: &str,
) -> UnitResult {
let node = &nodes[index];
let manifest = match build_manifest(
context,
nodes,
@@ -1152,7 +1195,11 @@ fn publish_success(
if let Ok(lean) = context.lean() {
let module = format!(
"MarqdoProof.Generated.{}_{}",
if outcome == Outcome::Refuted { "Refute" } else { "Target" },
if outcome == Outcome::Refuted {
"Refute"
} else {
"Target"
},
theorem_key
);
if let Ok(bytes) = lean.read_olean(&module) {
@@ -1170,7 +1217,11 @@ fn publish_success(
axioms: evidence.axioms.clone(),
certificate: Some(CertificateReport {
cache_key: manifest.cache_key.clone(),
directory: context.cache.bundle_dir(&manifest.cache_key).display().to_string(),
directory: context
.cache
.bundle_dir(&manifest.cache_key)
.display()
.to_string(),
payload_sha256: manifest.proof.sha256.clone(),
outcome: manifest.target.outcome.clone(),
}),
@@ -1240,9 +1291,7 @@ fn compute_cache_key_rec(
for dependency in &node.loaded.dependencies {
match &dependency.target {
DependencyTarget::Theorem {
snapshot,
unit_id,
..
snapshot, unit_id, ..
} => {
let dependency_index = nodes.iter().position(|candidate| {
candidate.loaded.snapshot.canonical_path == snapshot.canonical_path
@@ -1254,15 +1303,14 @@ fn compute_cache_key_rec(
format!("dependency `{}` is not in the closure", dependency.link.url),
));
};
let dependency_key = compute_cache_key_rec(
nodes,
dependency_index,
environment_id,
memo,
visiting,
)?;
let dependency_key =
compute_cache_key_rec(nodes, dependency_index, environment_id, memo, visiting)?;
sources.push((
nodes[dependency_index].loaded.snapshot.relative_path.clone(),
nodes[dependency_index]
.loaded
.snapshot
.relative_path
.clone(),
nodes[dependency_index].loaded.module.source_digest.clone(),
nodes[dependency_index]
.loaded
@@ -1272,15 +1320,17 @@ fn compute_cache_key_rec(
));
declared.push((
"theorem".to_string(),
nodes[dependency_index].loaded.snapshot.relative_path.clone(),
nodes[dependency_index]
.loaded
.snapshot
.relative_path
.clone(),
unit_id.clone(),
dependency_key,
));
}
DependencyTarget::Model {
snapshot,
function,
..
snapshot, function, ..
} => {
if let Some(model) = node
.models
@@ -1422,19 +1472,15 @@ fn build_manifest(
let lean = context.lean()?;
let environment = lean.identity().clone();
let mut sources: BTreeMap<String, SourceBinding> = BTreeMap::new();
let mut add_source = |locator: String,
module_id: String,
source_digest: String,
analysis_digest: String| {
sources
.entry(locator.clone())
.or_insert(SourceBinding {
let mut add_source =
|locator: String, module_id: String, source_digest: String, analysis_digest: String| {
sources.entry(locator.clone()).or_insert(SourceBinding {
locator,
module_id,
source_digest,
analysis_digest,
});
};
};
add_source(
node.loaded.snapshot.relative_path.clone(),
node.loaded.module.id.clone(),
@@ -1445,9 +1491,7 @@ fn build_manifest(
for dependency in &node.loaded.dependencies {
match &dependency.target {
DependencyTarget::Theorem {
snapshot,
unit_id,
..
snapshot, unit_id, ..
} => {
let dependency_node = nodes.iter().find(|candidate| {
candidate.loaded.snapshot.canonical_path == snapshot.canonical_path
@@ -1467,11 +1511,7 @@ fn build_manifest(
locator: format!(
"{}#{}",
snapshot.relative_path,
dependency_node
.loaded
.proof_unit
.path
.join("/")
dependency_node.loaded.proof_unit.path.join("/")
),
unit_id: unit_id.clone(),
link_text: dependency.link.text.clone(),
@@ -1479,9 +1519,7 @@ fn build_manifest(
});
}
DependencyTarget::Model {
snapshot,
function,
..
snapshot, function, ..
} => {
add_source(
snapshot.relative_path.clone(),
@@ -1594,15 +1632,13 @@ fn map_project_decls(
}
if let Some(key) = decl.strip_prefix("marqdoModel_") {
for node in nodes {
if let Some(model) = node
.models
.iter()
.find(|model| model.definition.key == key || model.definition.lean_name == *decl)
{
if let Some(model) = node.models.iter().find(|model| {
model.definition.key == key || model.definition.lean_name == *decl
}) {
mapped.insert(format!(
"{}#{}",
model.definition.locator,
model.definition.function_id
model.unit_path.join("/")
));
}
}
@@ -1618,6 +1654,7 @@ fn map_project_decls(
fn build_target_report(
_context: &mut Context,
nodes: &[PreparedNode],
node: &PreparedNode,
result: &UnitResult,
) -> TargetReport {
@@ -1630,21 +1667,15 @@ fn build_target_report(
.map(|dependency| {
let binding = match &dependency.target {
DependencyTarget::Theorem {
snapshot,
unit_id,
..
} => node
.theorem_dependencies
snapshot, unit_id, ..
} => nodes
.iter()
.find(|index| {
let _ = index;
false
.find(|candidate| {
candidate.loaded.snapshot.canonical_path == snapshot.canonical_path
&& candidate.loaded.proof_unit.unit_id == *unit_id
})
.map(|_| String::new())
.unwrap_or_else(|| {
let _ = (snapshot, unit_id);
String::new()
}),
.map(|candidate| format!("marqdoTarget_{}", candidate.theorem_key))
.unwrap_or_default(),
DependencyTarget::Model { function, .. } => node
.models
.iter()
@@ -1689,7 +1720,11 @@ fn build_target_report(
transitive_dependencies: result.transitive.clone(),
axioms: result.axioms.clone(),
certificate,
diagnostics: result.diagnostics.iter().map(DiagnosticReport::from).collect(),
diagnostics: result
.diagnostics
.iter()
.map(DiagnosticReport::from)
.collect(),
}
}
@@ -1715,10 +1750,16 @@ fn export_bundles(
&& node.loaded.proof_unit.unit_id == target.unit_id
})
.ok_or_else(|| {
crate::Failure::new(codes::CERTIFICATE_INVALID, "cannot locate the verified target")
crate::Failure::new(
codes::CERTIFICATE_INVALID,
"cannot locate the verified target",
)
})?;
let result = outcomes.get(&index).ok_or_else(|| {
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no verification result")
crate::Failure::new(
codes::CERTIFICATE_INVALID,
"target has no verification result",
)
})?;
let manifest = result.manifest.as_ref().ok_or_else(|| {
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof manifest")
@@ -1753,10 +1794,16 @@ fn export_bundles(
&& node.loaded.proof_unit.unit_id == target.unit_id
})
.ok_or_else(|| {
crate::Failure::new(codes::CERTIFICATE_INVALID, "cannot locate the verified target")
crate::Failure::new(
codes::CERTIFICATE_INVALID,
"cannot locate the verified target",
)
})?;
let result = outcomes.get(&index).ok_or_else(|| {
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no verification result")
crate::Failure::new(
codes::CERTIFICATE_INVALID,
"target has no verification result",
)
})?;
let manifest = result.manifest.as_ref().ok_or_else(|| {
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof manifest")
@@ -1847,9 +1894,9 @@ fn replay_inner(context: &mut Context, options: &ReplayOptions) -> Result<Report
};
let closure = context
.linker
.resolve_closure(&entry, &[unit.unit_id.clone()])?;
.resolve_closure(&entry, std::slice::from_ref(&unit.unit_id))?;
let mut diagnostics = closure.diagnostics.clone();
let mut nodes = prepare_closure(&closure, &mut diagnostics);
let nodes = prepare_closure(&closure, &mut diagnostics);
let Some(index) = nodes.iter().position(|node| {
node.loaded.snapshot.relative_path == entry.relative_path
&& node.loaded.proof_unit.unit_id == bundle.manifest.target.unit_id
@@ -1956,7 +2003,7 @@ fn replay_inner(context: &mut Context, options: &ReplayOptions) -> Result<Report
simple_result(Outcome::Invalid, nodes[index].scope, Vec::new())
}
};
let target = build_target_report(context, &nodes[index], &result);
let target = build_target_report(context, &nodes, &nodes[index], &result);
Ok(Report {
schema: RESULT_SCHEMA.to_string(),
schema_version: RESULT_SCHEMA_VERSION,
@@ -1989,4 +2036,3 @@ pub fn theorem_key(locator: &str, path: &[String], goal_digest: &str) -> String
pub fn allowed_axioms() -> &'static [&'static str] {
&ALLOWED_AXIOMS
}