analysis: bind to marqdo.analysis rev 3 and extract proof units

- strict DTOs for the current public Analysis contract, digest/span validation
- controlled-root CLI invocation with argv-only, timeout and process group kill
- proof-unit selection: one Knowledge H2 + direct 证明依赖 H3 + one display goal
- dependency list shape validation with 证明依赖 links
- real-CLI integration tests for the algebra/vector/arithmetic fixtures
This commit is contained in:
marqdo-prove committed 2026-11-26 09:51:22 +08:00
1 parent ecaf1b756c
commit 3a529b923d
8 files changed
+2672 -1

No files matched your search

Generated
+228
View File
@@ -0,0 +1,228 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "marqdo-prove"
version = "0.1.0"
dependencies = [
"libc",
"num-bigint",
"num-traits",
"serde",
"serde_json",
"sha2",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+21
View File
@@ -0,0 +1,21 @@
# 基础代数
## @knowledge 整数平方非负性
任意整数的平方均非负。
$$
\forall x\in\mathbb{Z},\quad x^2\geq 0
$$
### 证明依赖
## @knowledge 非负整数加法
两个非负整数相加仍然非负。
$$
\forall a,b\in\mathbb{Z},\quad (a\geq0\land b\geq0)\Rightarrow a+b\geq0
$$
### 证明依赖
+22
View File
@@ -0,0 +1,22 @@
# 整数计算
## @exec square
`params(x: Int)`
计算一个整数的平方。
`return x * x`
## @knowledge 平方函数的非负性
平方函数的返回值在精确整数计算模型下非负。
$$
\forall x\in\mathbb{Z},\quad \operatorname{square}(x)\geq0
$$
### 证明依赖
- [square](#square)
- [整数平方非负性](algebra.mq.md#整数平方非负性)
+14
View File
@@ -0,0 +1,14 @@
# 向量数学
## @knowledge 平方和非负性
任意两个整数的平方和均非负。
$$
\forall x,y\in\mathbb{Z},\quad x^2+y^2\geq0
$$
### 证明依赖
- [整数平方非负性](algebra.mq.md#整数平方非负性)
- [非负整数加法](algebra.mq.md#非负整数加法)
+1510
View File
File diff suppressed because it is too large. Load diff
+776
View File
@@ -1 +1,777 @@
//! Proof-unit selection from the public document AST (docs/DEVELOPMENT.md §3).
//!
//! A proof unit is an effective-mode Knowledge H2 whose direct children contain
//! exactly one canonical H3 named `证明依赖`. The unit's goal is the one and
//! only display math block in the H2's *direct* body; the dependency H3 is
//! either empty or exactly one unordered list whose items are exactly one plain
//! Markdown link each.
//!
//! Nothing in this module interprets mathematics: it only selects structure and
//! reports spans. Every decision here is a hard error instead of a guess.
use crate::analysis::{ModuleData, Node, Unit};
use crate::{codes, sha256_hex, Diagnostic, Span};
/// Canonical dependency heading name. Deliberately not configurable and not
/// translated: the first release recognizes one name.
pub const DEPENDENCIES_HEADING: &str = "证明依赖";
/// One extracted target and its declared dependency links.
#[derive(Clone, Debug)]
pub struct ProofUnit {
pub module_id: String,
pub unit_id: String,
pub title: String,
pub path: Vec<String>,
/// Complete H2 section span.
pub section_span: Span,
pub heading_span: Span,
/// The display math payload selected as the goal.
pub goal: GoalMath,
/// Declared dependencies in document order.
pub dependencies: DependencySection,
}
/// The one display math block selected as the target proposition.
#[derive(Clone, Debug)]
pub struct GoalMath {
/// Payload text between the `$$` delimiters, exactly as emitted by the CLI.
pub literal: String,
/// Span of the whole `math_block` node, delimiters included.
pub block_span: Span,
/// Span of `literal` inside the module source when it can be located
/// exactly; `None` means only `block_span` is reliable.
pub payload_span: Option<Span>,
/// Lowercase SHA-256 of `literal` bytes.
pub digest: String,
}
/// The `证明依赖` section of one proof unit.
#[derive(Clone, Debug)]
pub struct DependencySection {
pub unit_id: String,
pub heading_span: Span,
pub section_span: Span,
pub links: Vec<DependencyLink>,
}
/// One dependency link, kept with its display text and span.
#[derive(Clone, Debug)]
pub struct DependencyLink {
pub url: String,
pub text: String,
pub link_span: Span,
pub item_span: Span,
}
/// Extraction result for one candidate H2.
#[derive(Clone, Debug)]
pub enum Extraction {
Unit(ProofUnit),
Invalid(Diagnostic),
}
/// Extract every proof unit from one module, in document order.
///
/// H2 sections without a `证明依赖` direct H3 are simply not proof units; they
/// produce no entry and no diagnostic. A section that *looks* selected (has the
/// heading) but is malformed produces an `Invalid` entry, so the batch is
/// non-zero rather than silently skipping it.
pub fn extract(module: &ModuleData) -> Vec<Extraction> {
let mut extracted = Vec::new();
for unit in module.units.iter() {
if unit.kind != "knowledge" || unit.level != 2 {
continue;
}
let dependency_units = direct_dependency_units(module, unit);
match dependency_units.len() {
0 => continue,
1 => {}
_ => {
extracted.push(Extraction::Invalid(
Diagnostic::error(
codes::DOCUMENT_DEPENDENCIES_SHAPE,
format!(
"知识单元 `{}` 有 {} 个直接 H3 `{DEPENDENCIES_HEADING}`;必须恰好一个",
display_path(unit),
dependency_units.len()
),
)
.at(unit.heading_span.unwrap_or(unit.span))
.with_hint("删除重复的依赖标题,只保留一个 `### 证明依赖`"),
));
continue;
}
}
let dependency_unit = dependency_units[0];
match build_unit(module, unit, dependency_unit) {
Ok(proof_unit) => extracted.push(Extraction::Unit(proof_unit)),
Err(diagnostic) => extracted.push(Extraction::Invalid(diagnostic)),
}
}
extracted
}
/// Resolve `--unit FRAGMENT` against one module using the upstream anchor rules.
///
/// Returns the unit id to select, or a diagnostic when the fragment is missing,
/// ambiguous, or does not select a selected proof unit. An empty fragment is
/// rejected: it would select the document root, which is not a target.
pub fn resolve_selection(module: &ModuleData, fragment: &str) -> Result<String, Diagnostic> {
use crate::analysis::FragmentResolution;
if fragment.is_empty() {
return Err(Diagnostic::error(
codes::DOCUMENT_UNIT,
"`--unit` requires a non-empty exact anchor or heading name",
));
}
match module.resolve_fragment(fragment) {
FragmentResolution::Unit(unit_id) => {
let Some(unit) = module.unit(&unit_id) else {
return Err(Diagnostic::error(
codes::DOCUMENT_UNIT,
format!("anchor `{fragment}` resolved to an unknown unit"),
));
};
if unit.kind != "knowledge" || unit.level != 2 {
return Err(Diagnostic::error(
codes::DOCUMENT_UNIT,
format!(
"`--unit {fragment}` selects `{}` which is not a Knowledge H2 proof unit",
display_path(unit)
),
)
.at(unit.heading_span.unwrap_or(unit.span)));
}
if direct_dependency_units(module, unit).is_empty() {
return Err(Diagnostic::error(
codes::DOCUMENT_UNIT,
format!(
"`--unit {fragment}` selects a Knowledge H2 without a direct `{DEPENDENCIES_HEADING}` heading; it is not a proof target"
),
)
.at(unit.heading_span.unwrap_or(unit.span)));
}
Ok(unit_id)
}
FragmentResolution::Missing => Err(Diagnostic::error(
codes::DOCUMENT_UNIT,
format!("no unit in this document matches `--unit {fragment}`"),
)),
FragmentResolution::Ambiguous(candidates) => Err(Diagnostic::error(
codes::DOCUMENT_UNIT,
format!(
"`--unit {fragment}` is ambiguous; exact candidates: {}",
candidates.join(", ")
),
)
.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",
)),
}
}
fn build_unit(
module: &ModuleData,
unit: &Unit,
dependency_unit: &Unit,
) -> Result<ProofUnit, Diagnostic> {
if unit.mode != "knowledge" {
return Err(Diagnostic::error(
codes::DOCUMENT_UNIT,
format!("proof target `{}` is not in effective Knowledge mode", display_path(unit)),
)
.at(unit.heading_span.unwrap_or(unit.span)));
}
if dependency_unit.mode != "knowledge" {
return Err(Diagnostic::error(
codes::DOCUMENT_DEPENDENCIES_SHAPE,
format!(
"`{DEPENDENCIES_HEADING}` of `{}` is not in effective Knowledge mode",
display_path(unit)
),
)
.at(dependency_unit.heading_span.unwrap_or(dependency_unit.span)));
}
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)),
)
.at(dependency_unit.heading_span.unwrap_or(dependency_unit.span)));
}
let heading_span = unit.heading_span.ok_or_else(|| {
Diagnostic::error(
codes::DOCUMENT_UNIT,
format!("proof target `{}` has no heading span", display_path(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)),
)
})?;
// Direct body: top-level nodes of the H2 section before the first H3.
let body_nodes = direct_body_nodes(module, unit, dependency_unit);
let math_blocks: Vec<&Node> = body_nodes
.iter()
.filter(|node| node.kind == "math_block")
.copied()
.collect();
if math_blocks.len() != 1 {
return Err(Diagnostic::error(
codes::DOCUMENT_GOAL_COUNT,
format!(
"proof target `{}` must have exactly one display math block in its direct body; found {}",
display_path(unit),
math_blocks.len()
),
)
.at(heading_span)
.with_hint(
"put exactly one standalone `$$ ... $$` block directly under the H2 heading; put \
explanations in prose or another H3",
));
}
let math_block = math_blocks[0];
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)),
)
.at(math_block.span)
})?;
if literal.trim().is_empty() {
return Err(Diagnostic::error(
codes::FORMULA_SYNTAX,
format!("selected math block of `{}` is empty", display_path(unit)),
)
.at(math_block.span));
}
if literal.len() > crate::limits::MAX_GOAL_BYTES {
return Err(Diagnostic::error(
codes::DOCUMENT_GOAL_COUNT,
format!(
"goal payload of `{}` is {} bytes, above the {} byte limit",
display_path(unit),
literal.len(),
crate::limits::MAX_GOAL_BYTES
),
)
.at(math_block.span));
}
let payload_span = locate_payload(&module.source, math_block, &literal);
let dependencies = extract_dependencies(module, unit, dependency_unit, dependency_heading_span)?;
Ok(ProofUnit {
module_id: module.id.clone(),
unit_id: unit.id.clone(),
title: unit.name.clone(),
path: unit.path.clone(),
section_span: unit.span,
heading_span,
goal: GoalMath {
digest: sha256_hex(literal.as_bytes()),
literal,
block_span: math_block.span,
payload_span,
},
dependencies,
})
}
/// The direct `证明依赖` H3 children of an H2.
fn direct_dependency_units<'a>(module: &'a ModuleData, unit: &'a Unit) -> Vec<&'a Unit> {
module
.children_of(&unit.id)
.filter(|child| {
child.level == 3
&& child.name == DEPENDENCIES_HEADING
&& child.kind == "section"
})
.collect()
}
/// Top-level AST nodes that belong to the H2's direct body: after the H2
/// heading, before the first H3 heading of its section.
fn direct_body_nodes<'a>(
module: &'a ModuleData,
unit: &'a Unit,
dependency_unit: &Unit,
) -> Vec<&'a Node> {
let Some(heading_span) = unit.heading_span else {
return Vec::new();
};
let section_end = unit.span.end;
let mut boundary = section_end;
for node in &module.document.children {
if node.kind == "heading"
&& node.span.start >= heading_span.end
&& node.span.start < boundary
&& node.span.end <= section_end
{
if let Some(level) = node.level {
if level >= 3 {
boundary = boundary.min(node.span.start);
}
}
}
}
// The dependency heading itself is an H3 and is already the boundary; make
// this explicit so a deleted heading cannot silently widen the body.
boundary = boundary.min(dependency_unit.span.start);
module
.document
.children
.iter()
.filter(|node| {
node.kind != "heading"
&& node.span.start >= heading_span.end
&& node.span.end <= boundary
})
.collect()
}
fn extract_dependencies(
module: &ModuleData,
unit: &Unit,
dependency_unit: &Unit,
dependency_heading_span: Span,
) -> Result<DependencySection, Diagnostic> {
let section_span = dependency_unit.span;
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)),
)
.at(dependency_heading_span));
}
let body_start = dependency_heading_span.end;
let body_end = section_span.end;
// No nested headings are allowed in the dependency section.
for node in &module.document.children {
if node.kind == "heading" && node.span.start >= body_start && node.span.end <= body_end {
return Err(Diagnostic::error(
codes::DOCUMENT_DEPENDENCIES_SHAPE,
format!(
"`{DEPENDENCIES_HEADING}` of `{}` contains a nested heading",
display_path(unit)
),
)
.at(node.span)
.with_hint("the dependency heading must not have child headings"));
}
}
let body: Vec<&Node> = module
.document
.children
.iter()
.filter(|node| node.span.start >= body_start && node.span.end <= body_end)
.collect();
if body.is_empty() {
return Ok(DependencySection {
unit_id: dependency_unit.id.clone(),
heading_span: dependency_heading_span,
section_span,
links: Vec::new(),
});
}
if body.len() != 1 || body[0].kind != "list" {
return Err(shape_error(
unit,
dependency_heading_span,
format!(
"`{DEPENDENCIES_HEADING}` must contain exactly one unordered list, found {} other block(s)",
body.len()
),
"write either nothing or one bullet list where every item is exactly one Markdown link",
));
}
let list = body[0];
if list.ordered != Some(false) {
return Err(shape_error(
unit,
list.span,
format!("`{DEPENDENCIES_HEADING}` list must be unordered"),
"use `- [标题](目标)` bullets; ordered lists are not accepted",
));
}
let mut links = Vec::new();
for item in &list.children {
if item.kind != "item" {
return Err(shape_error(
unit,
item.span,
format!("`{DEPENDENCIES_HEADING}` contains a non-item node `{}`", item.kind),
"the dependency list must contain only bullet items",
));
}
let link = single_link_in_item(item).ok_or_else(|| {
shape_error(
unit,
item.span,
format!(
"every `{DEPENDENCIES_HEADING}` item must be exactly one plain Markdown link"
),
"remove extra text, images, nested lists and multiple links from the item",
)
})?;
let url = link.url.clone().unwrap_or_default();
if url.trim().is_empty() {
return Err(shape_error(
unit,
link.span,
format!("`{DEPENDENCIES_HEADING}` contains a link with an empty destination"),
"every dependency link needs an exact target such as `other.mq.md#标题`",
));
}
let text = link_text(link);
if links
.iter()
.any(|existing: &DependencyLink| existing.url == url)
{
return Err(shape_error(
unit,
link.span,
format!("`{DEPENDENCIES_HEADING}` contains the same link twice: `{url}`"),
"remove the duplicate dependency link",
));
}
links.push(DependencyLink {
url,
text,
link_span: link.span,
item_span: item.span,
});
}
Ok(DependencySection {
unit_id: dependency_unit.id.clone(),
heading_span: dependency_heading_span,
section_span,
links,
})
}
fn single_link_in_item(item: &Node) -> Option<&Node> {
if item.children.len() != 1 {
return None;
}
let paragraph = &item.children[0];
if paragraph.kind != "paragraph" || paragraph.children.len() != 1 {
return None;
}
let link = &paragraph.children[0];
if link.kind != "link" {
return None;
}
Some(link)
}
fn link_text(link: &Node) -> String {
let mut out = String::new();
for child in &link.children {
if let Some(literal) = &child.literal {
out.push_str(literal);
}
}
out
}
fn locate_payload(source: &str, math_block: &Node, literal: &str) -> Option<Span> {
let block = source.get(math_block.span.start..math_block.span.end)?;
let offset = block.find(literal)?;
let start = math_block.span.start + offset;
let end = start + literal.len();
let span = Span::new(start, end);
if span.is_valid_in(source) {
Some(span)
} else {
None
}
}
fn shape_error(
unit: &Unit,
span: Span,
message: String,
hint: &'static str,
) -> Diagnostic {
Diagnostic::error(
codes::DOCUMENT_DEPENDENCIES_SHAPE,
format!("{}: {message}", display_path(unit)),
)
.at(span)
.with_hint(hint)
}
fn display_path(unit: &Unit) -> String {
if unit.path.is_empty() {
"<document>".to_string()
} else {
unit.path.join(" / ")
}
}
#[cfg(test)]
mod tests {
use super::*;
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 {
serde_json::from_value(serde_json::json!({
"id": id,
"path": path,
"parent_id": parent,
"kind": kind,
"name": name,
"level": level,
"mode": if kind == "function" { "exec" } else { "knowledge" },
"mode_origin": "explicit",
"mode_source_unit_id": id,
"heading_span": {"start": heading.start, "end": heading.end},
"span": {"start": span.start, "end": span.end},
"function": null
}))
.expect("unit fixture")
}
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,
children,
literal: literal.map(str::to_string),
level,
url: url.map(str::to_string),
..Node::default()
}
}
/// Build the canonical two-fixture AST for `### 证明依赖` sections.
fn module_with(source: &str, units: Vec<Unit>, document: Node) -> ModuleData {
let unit_by_id = units
.iter()
.enumerate()
.map(|(index, unit)| (unit.id.clone(), index))
.collect::<HashMap<_, _>>();
ModuleData {
id: "root:test::doc.mq.md".to_string(),
package_instance_id: "root:test".to_string(),
relative_path: "doc.mq.md".to_string(),
source: source.to_string(),
source_digest: crate::sha256_hex(source.as_bytes()),
document,
units,
anchors: BTreeMap::new(),
functions: vec![],
references: vec![],
resources: vec![],
unit_by_id,
}
}
fn canonical_modules(source: &str) -> ModuleData {
// Layout of the fixture:
// 0..15 "@knowledge A" H2
// 17..25 "$$x=1$$"
// 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:test::doc.mq.md#A/证明依赖",
&["A", "证明依赖"],
Some("root:test::doc.mq.md#A"),
"section",
"证明依赖",
3,
Span::new(29, 38),
Span::new(29, source.len()),
),
];
let document = node(
"document",
Span::new(0, source.len()),
None,
None,
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("heading", Span::new(29, 38), None, Some(3), None, vec![]),
],
);
module_with(source, units, document)
}
#[test]
fn selects_one_goal_and_empty_dependencies() {
let source = "## @knowledge A\n\n$$x=1$$\n\n### 证明依赖\n";
let module = canonical_modules(source);
let extracted = extract(&module);
assert_eq!(extracted.len(), 1, "{extracted:?}");
let Extraction::Unit(proof_unit) = &extracted[0] else {
panic!("expected a proof unit, got {extracted:?}");
};
assert_eq!(proof_unit.title, "A");
assert_eq!(proof_unit.goal.literal, "x=1");
assert_eq!(proof_unit.goal.digest, crate::sha256_hex(b"x=1"));
assert!(proof_unit.dependencies.links.is_empty());
}
#[test]
fn missing_dependency_heading_is_not_a_target() {
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())),
];
let document = node(
"document",
Span::new(0, source.len()),
None,
None,
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![]),
],
);
assert!(extract(&module_with(source, units, document)).is_empty());
}
#[test]
fn two_goals_are_invalid() {
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:test::doc.mq.md#A/证明依赖",
&["A", "证明依赖"],
Some("root:test::doc.mq.md#A"),
"section",
"证明依赖",
3,
Span::new(33, 44),
Span::new(33, source.len()),
),
];
let document = node(
"document",
Span::new(0, source.len()),
None,
None,
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("heading", Span::new(33, 44), None, Some(3), None, vec![]),
],
);
let extracted = extract(&module_with(source, units, document));
assert_eq!(extracted.len(), 1);
match &extracted[0] {
Extraction::Invalid(diagnostic) => {
assert_eq!(diagnostic.code, codes::DOCUMENT_GOAL_COUNT);
assert!(diagnostic.message.contains("exactly one display math block"));
}
other => panic!("expected invalid, got {other:?}"),
}
}
#[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 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:test::doc.mq.md#A/证明依赖",
&["A", "证明依赖"],
Some("root:test::doc.mq.md#A"),
"section",
"证明依赖",
3,
Span::new(29, 38),
Span::new(29, source.len()),
),
];
let paragraph = node(
"paragraph",
Span::new(40, source.len() - 1),
None,
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 list = Node {
kind: "list".to_string(),
span: Span::new(39, source.len() - 1),
children: vec![item],
ordered: Some(false),
tight: Some(true),
..Node::default()
};
let document = node(
"document",
Span::new(0, source.len()),
None,
None,
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("heading", Span::new(29, 38), None, Some(3), None, vec![]),
list,
],
);
let extracted = extract(&module_with(source, units, document));
assert_eq!(extracted.len(), 1);
match &extracted[0] {
Extraction::Invalid(diagnostic) => {
assert_eq!(diagnostic.code, codes::DOCUMENT_DEPENDENCIES_SHAPE)
}
other => panic!("expected invalid, got {other:?}"),
}
}
#[test]
fn selection_rejects_units_that_are_not_targets() {
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())),
];
let document = node(
"document",
Span::new(0, source.len()),
None,
None,
None,
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();
assert_eq!(error.code, codes::DOCUMENT_UNIT);
assert!(error.message.contains("not a proof target"));
let error = resolve_selection(&module, "").unwrap_err();
assert_eq!(error.code, codes::DOCUMENT_UNIT);
}
}
+1 -1
View File
@@ -65,7 +65,7 @@ pub mod limits {
}
/// A half-open UTF-8 byte range in a single document source.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Span {
pub start: usize,
pub end: usize,
+100
View File
@@ -0,0 +1,100 @@
//! Real-CLI integration: emitted Analysis revision 3 -> proof unit extraction.
//!
//! Requires `MARQDO_BIN` to point at a Marqdo CLI that emits analysis revision 3.
//! The test is skipped (not silently passed) when the variable is unset, so a
//! developer without a built CLI still gets a green unit suite; CI must set it.
use std::path::PathBuf;
use marqdo_prove::analysis::AnalysisBackend;
use marqdo_prove::document::{extract, Extraction};
fn cli() -> Option<PathBuf> {
std::env::var_os("MARQDO_BIN").map(PathBuf::from)
}
fn examples_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples")
}
fn work_dir(tag: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join(".tmp")
.join("tests")
.join(tag);
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("create work dir");
dir
}
#[test]
fn real_cli_extracts_vector_fixture() {
let Some(bin) = cli() else {
eprintln!("skipping: MARQDO_BIN is not set");
return;
};
let root = examples_root();
let backend = AnalysisBackend::new(bin, work_dir("analysis_document")).expect("backend");
let snapshot = backend
.load(&root.join("vector.mq.md"), &root)
.expect("load vector analysis");
assert_eq!(snapshot.relative_path, "vector.mq.md");
assert_eq!(snapshot.project.identity_kind, "workspace_snapshot");
let extracted = extract(snapshot.entry());
assert_eq!(extracted.len(), 1, "{extracted:?}");
let Extraction::Unit(unit) = &extracted[0] else {
panic!("expected proof unit, got {extracted:?}");
};
assert_eq!(unit.title, "平方和非负性");
assert_eq!(
unit.goal.literal,
"\\forall x,y\\in\\mathbb{Z},\\quad x^2+y^2\\geq0\n"
);
assert_eq!(unit.dependencies.links.len(), 2);
assert_eq!(unit.dependencies.links[0].text, "整数平方非负性");
assert_eq!(unit.dependencies.links[0].url, "algebra.mq.md#整数平方非负性");
assert!(unit.goal.payload_span.is_some());
let source = &snapshot.entry().source;
assert_eq!(
&source[unit.goal.payload_span.unwrap().start..unit.goal.payload_span.unwrap().end],
unit.goal.literal
);
}
#[test]
fn real_cli_extracts_algebra_fixture() {
let Some(bin) = cli() else {
eprintln!("skipping: MARQDO_BIN is not set");
return;
};
let root = examples_root();
let backend = AnalysisBackend::new(bin, work_dir("analysis_algebra")).expect("backend");
let snapshot = backend
.load(&root.join("algebra.mq.md"), &root)
.expect("load algebra analysis");
let extracted = extract(snapshot.entry());
assert_eq!(extracted.len(), 2, "{extracted:?}");
for entry in &extracted {
assert!(matches!(entry, Extraction::Unit(_)), "{entry:?}");
}
}
#[test]
fn real_cli_extracts_program_model_fixture() {
let Some(bin) = cli() else {
eprintln!("skipping: MARQDO_BIN is not set");
return;
};
let root = examples_root();
let backend = AnalysisBackend::new(bin, work_dir("analysis_arith")).expect("backend");
let snapshot = backend
.load(&root.join("arithmetic.mq.md"), &root)
.expect("load arithmetic analysis");
let extracted = extract(snapshot.entry());
assert_eq!(extracted.len(), 1, "{extracted:?}");
let Extraction::Unit(unit) = &extracted[0] else {
panic!("expected proof unit, got {extracted:?}");
};
assert_eq!(unit.dependencies.links.len(), 2);
assert_eq!(unit.dependencies.links[0].url, "#square");
}