diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..c33bf7d --- /dev/null +++ b/Cargo.lock @@ -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" diff --git a/examples/algebra.mq.md b/examples/algebra.mq.md new file mode 100644 index 0000000..ab85674 --- /dev/null +++ b/examples/algebra.mq.md @@ -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 +$$ + +### 证明依赖 diff --git a/examples/arithmetic.mq.md b/examples/arithmetic.mq.md new file mode 100644 index 0000000..a495f00 --- /dev/null +++ b/examples/arithmetic.mq.md @@ -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#整数平方非负性) diff --git a/examples/vector.mq.md b/examples/vector.mq.md new file mode 100644 index 0000000..7223091 --- /dev/null +++ b/examples/vector.mq.md @@ -0,0 +1,14 @@ +# 向量数学 + +## @knowledge 平方和非负性 + +任意两个整数的平方和均非负。 + +$$ +\forall x,y\in\mathbb{Z},\quad x^2+y^2\geq0 +$$ + +### 证明依赖 + +- [整数平方非负性](algebra.mq.md#整数平方非负性) +- [非负整数加法](algebra.mq.md#非负整数加法) diff --git a/src/analysis.rs b/src/analysis.rs index 8e32dd4..2d6fc58 100644 --- a/src/analysis.rs +++ b/src/analysis.rs @@ -1 +1,1511 @@ //! Upstream `marqdo check --emit` integration and strict Analysis validation. +//! +//! This module is the only place that talks to the `marqdo` CLI. It invokes the +//! executable through `argv` (never a shell), reads the emitted +//! `marqdo.analysis` revision 3 artifact, validates the *current* contract in +//! full, and hands the rest of the tool typed data. +//! +//! Two rules are load bearing: +//! +//! * Prove never parses raw Markdown to recover language structure. The AST, +//! units, anchors, functions, references and resources all come from the +//! emitted Analysis. +//! * A snapshot is bound to the exact bytes that produced it. Every consumer +//! records `analysis_digest` (SHA-256 of the emitted JSON) and +//! `source_digest` (SHA-256 of the decoded source), so a later edit cannot be +//! mistaken for the checked snapshot. + +use std::collections::{BTreeMap, HashMap}; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use serde::{Deserialize, Serialize}; + +use crate::{ + codes, sha256_hex, Failure, Result, Span, REQUIRED_ANALYSIS_REVISION, REQUIRED_API_REVISION, +}; + +// --------------------------------------------------------------------------- +// Public typed view of one Analysis artifact +// --------------------------------------------------------------------------- + +/// One checked module together with the indexes the rest of the tool needs. +#[derive(Debug)] +pub struct ModuleData { + pub id: String, + pub package_instance_id: String, + pub relative_path: String, + pub source: String, + pub source_digest: String, + pub document: Node, + pub units: Vec, + pub anchors: BTreeMap, + pub functions: Vec, + pub references: Vec, + pub resources: Vec, + pub(crate) unit_by_id: HashMap, +} + +impl ModuleData { + pub fn unit(&self, unit_id: &str) -> Option<&Unit> { + self.unit_by_id.get(unit_id).map(|index| &self.units[*index]) + } + + /// Direct child units of `parent_id`, in document order. + pub fn children_of<'a>(&'a self, parent_id: &'a str) -> impl Iterator { + self.units + .iter() + .filter(move |unit| unit.parent_id.as_deref() == Some(parent_id)) + } + + /// Resolve a fragment against this module using the *public* anchor map + /// first and the documented exact canonical-name fallback second. + pub fn resolve_fragment(&self, fragment: &str) -> FragmentResolution { + if fragment.is_empty() { + return FragmentResolution::DocumentRoot; + } + if let Some(unit_id) = self.anchors.get(fragment) { + return match self.unit(unit_id) { + Some(unit) => FragmentResolution::Unit(unit.id.clone()), + None => FragmentResolution::Missing, + }; + } + let candidates: Vec<&Unit> = self + .units + .iter() + .filter(|unit| unit.name == fragment) + .collect(); + match candidates.as_slice() { + [] => FragmentResolution::Missing, + [unit] => FragmentResolution::Unit(unit.id.clone()), + many => FragmentResolution::Ambiguous( + many.iter().map(|unit| unit.id.clone()).collect::>(), + ), + } + } + + /// Source slice for a span, if the span is valid for this module. + pub fn slice(&self, span: Span) -> Option<&str> { + if span.is_valid_in(&self.source) { + self.source.get(span.start..span.end) + } else { + None + } + } + + /// A stable, portable locator for this module inside its package. + pub fn locator(&self) -> String { + self.relative_path.clone() + } +} + +/// Outcome of resolving one link fragment inside one module. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FragmentResolution { + DocumentRoot, + Unit(String), + Ambiguous(Vec), + Missing, +} + +/// Project identity captured from the Analysis snapshot. +#[derive(Clone, Debug)] +pub struct ProjectIdentity { + pub root_id: String, + pub identity_kind: String, + pub lock_digest: String, + pub manifest_digest: String, +} + +/// One verified immutable view of an `ENTRY` and the modules the CLI loaded. +#[derive(Debug)] +pub struct Snapshot { + /// Canonical physical path of the entry document. + pub canonical_path: PathBuf, + /// Canonical physical package root used for every local reference. + pub root: PathBuf, + /// Entry module path relative to `root`. + pub relative_path: String, + /// SHA-256 of the exact emitted Analysis bytes. + pub analysis_digest: String, + pub analysis_byte_len: usize, + pub project: ProjectIdentity, + pub entry_module_id: String, + pub modules: BTreeMap>, +} + +impl Snapshot { + pub fn entry(&self) -> &Arc { + // Validated invariant: entry_module_id is present exactly once. + self.modules + .get(&self.entry_module_id) + .expect("validated entry module") + } + + /// Locate a loaded module by its package-relative path. + pub fn module_by_relative_path(&self, relative_path: &str) -> Option<&Arc> { + self.modules + .values() + .find(|module| module.relative_path == relative_path) + } +} + +// --------------------------------------------------------------------------- +// Backend: CLI invocation, snapshot cache and controlled local loading +// --------------------------------------------------------------------------- + +/// Extra bytes allowed for one emitted Analysis artifact. +const ANALYSIS_MAX_BYTES: u64 = 128 * 1024 * 1024; + +/// Invokes the real CLI, validates its Analysis output and caches snapshots. +/// +/// The backend accepts an already-resolved project root. Call +/// [`AnalysisBackend::discover_root`] to apply the documented rule (explicit +/// `--root`, else nearest `marqdo.yaml`, else the entry directory). +pub struct AnalysisBackend { + marqdo_bin: PathBuf, + work_dir: PathBuf, + cache: std::cell::RefCell>>, + timeout: Duration, +} + +impl AnalysisBackend { + pub fn new(marqdo_bin: PathBuf, work_dir: PathBuf) -> Result { + if !marqdo_bin.is_absolute() { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("MARQDO_BIN must be an absolute path, got `{}`", marqdo_bin.display()), + )); + } + if !marqdo_bin.is_file() { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("Marqdo CLI binary not found at `{}`", marqdo_bin.display()), + ) + .with_hint("set MARQDO_BIN to an installed marqdo executable")); + } + 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()), + ) + })?; + if let Ok(revision) = std::env::var("MARQDO_API_REVISION") { + let parsed: i64 = revision.trim().parse().unwrap_or(-1); + if parsed != REQUIRED_API_REVISION as i64 { + return Err(Failure::new( + codes::UPSTREAM_CONTRACT, + format!( + "CLI tool host API revision {revision} does not match required revision \ + {REQUIRED_API_REVISION}" + ), + )); + } + } + Ok(Self { + marqdo_bin, + work_dir, + cache: std::cell::RefCell::new(HashMap::new()), + timeout: Duration::from_secs(crate::limits::CLI_TIMEOUT_SECS), + }) + } + + /// The documented root rule: explicit `--root` wins; otherwise the nearest + /// ancestor with `marqdo.yaml`; otherwise the entry's own directory. + pub fn discover_root(entry: &Path, explicit: Option<&Path>) -> Result { + let entry = canonicalize_file(entry, "entry document")?; + match explicit { + Some(root) => { + let root = std::fs::canonicalize(root).map_err(|error| { + Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!("cannot canonicalize --root `{}`: {error}", root.display()), + ) + })?; + if !root.is_dir() { + return Err(Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!("--root `{}` is not a directory", root.display()), + )); + } + if !entry.starts_with(&root) { + return Err(Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!( + "entry `{}` is outside the controlled root `{}`", + entry.display(), + root.display() + ), + )); + } + Ok(root) + } + 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") + })?; + let start = directory.clone(); + loop { + if directory.join("marqdo.yaml").is_file() { + return Ok(directory); + } + if !directory.pop() { + break; + } + } + Ok(start) + } + } + } + + /// Load one entry document through the real CLI at a fixed root. + pub fn load(&self, entry: &Path, root: &Path) -> Result> { + let canonical = canonicalize_file(entry, "document")?; + if let Some(cached) = self.cache.borrow().get(&canonical) { + return Ok(cached.clone()); + } + let root = std::fs::canonicalize(root).map_err(|error| { + Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!("cannot canonicalize root `{}`: {error}", root.display()), + ) + })?; + if !canonical.starts_with(&root) { + return Err(Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!( + "document `{}` is outside the controlled root `{}`", + canonical.display(), + root.display() + ), + )); + } + // Refuse symbolic links anywhere in the document identity. The CLI + // would follow them; Prove's controlled-root contract does not. + let metadata = std::fs::symlink_metadata(&canonical).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot stat `{}`: {error}", canonical.display()), + ) + })?; + if metadata.file_type().is_symlink() { + return Err(Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!("`{}` is a symbolic link", canonical.display()), + )); + } + 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()); + Ok(snapshot) + } + + /// Run `marqdo check ENTRY --emit PATH` in a private directory. + fn emit_analysis(&self, entry: &Path, root: &Path) -> Result> { + let unique = format!( + "analysis-{}-{}.json", + std::process::id(), + monotonic_counter() + ); + let output_path = self.work_dir.join(unique); + let result = self.run_cli(entry, root, &output_path); + let bytes = match result { + Ok(bytes) => bytes, + Err(error) => { + let _ = std::fs::remove_file(&output_path); + return Err(error); + } + }; + let _ = std::fs::remove_file(&output_path); + Ok(bytes) + } + + fn run_cli(&self, entry: &Path, root: &Path, output_path: &Path) -> Result> { + let mut command = Command::new(&self.marqdo_bin); + command + .arg("check") + .arg(entry) + .arg("--emit") + .arg(output_path) + .current_dir(root) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + // Keep the child environment small: no secrets from the caller are + // needed for static checking. + .env_clear(); + if let Some(path) = std::env::var_os("PATH") { + command.env("PATH", path); + } + command.env("LANG", "C.UTF-8").env("LC_ALL", "C.UTF-8"); + configure_process_group(&mut command); + let mut child = command.spawn().map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot execute `{}`: {error}", self.marqdo_bin.display()), + ) + })?; + let stdout = child.stdout.take(); + let stderr = child.stderr.take(); + let deadline = Instant::now() + self.timeout; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) => { + if Instant::now() >= deadline { + kill_process_group(child.id()); + let _ = child.kill(); + let _ = child.wait(); + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!( + "`marqdo check` did not finish within {}s", + self.timeout.as_secs() + ), + )); + } + std::thread::sleep(Duration::from_millis(10)); + } + Err(error) => { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot wait for `marqdo check`: {error}"), + )) + } + } + }; + let stdout = read_pipe(stdout); + let stderr = read_pipe(stderr); + if !status.success() { + let detail = String::from_utf8_lossy(&stderr).trim().to_string(); + let detail = if detail.is_empty() { + String::from_utf8_lossy(&stdout).trim().to_string() + } else { + detail + }; + return Err(Failure::new( + codes::UPSTREAM_CONTRACT, + format!( + "`marqdo check {}` failed with {}{}", + entry.display(), + status, + if detail.is_empty() { + String::new() + } else { + format!(": {detail}") + } + ), + ) + .with_hint( + "fix the document so the current Marqdo CLI emits Analysis; Prove does not parse \ + raw Markdown to bypass a static error", + )); + } + let metadata = std::fs::metadata(output_path).map_err(|error| { + Failure::new( + codes::UPSTREAM_CONTRACT, + format!( + "`marqdo check --emit` reported success but wrote no artifact at `{}`: {error}", + output_path.display() + ), + ) + })?; + if metadata.len() > ANALYSIS_MAX_BYTES { + return Err(Failure::new( + codes::UPSTREAM_CONTRACT, + format!( + "emitted Analysis is {} bytes, above the {} byte limit", + metadata.len(), + ANALYSIS_MAX_BYTES + ), + )); + } + std::fs::read(output_path).map_err(|error| { + Failure::new( + codes::UPSTREAM_CONTRACT, + format!("cannot read emitted Analysis: {error}"), + ) + }) + } +} + +fn canonicalize_file(path: &Path, label: &str) -> Result { + std::fs::canonicalize(path).map_err(|error| { + Failure::new( + codes::UPSTREAM_CONTRACT, + format!("cannot resolve {label} `{}`: {error}", path.display()), + ) + }) +} + +fn read_pipe(pipe: Option) -> Vec { + let mut buffer = Vec::new(); + if let Some(mut pipe) = pipe { + let _ = pipe.by_ref().take(1024 * 1024).read_to_end(&mut buffer); + } + buffer +} + +fn monotonic_counter() -> u64 { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + COUNTER.fetch_add(1, Ordering::Relaxed) +} + +fn configure_process_group(command: &mut Command) { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + // New session: the CLI and anything it statically starts can be killed + // as one group without touching the harness process group. + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 { + // Fall back to the default group rather than failing; the + // child still belongs to the parent's group. + } + Ok(()) + }); + } + } + let _ = command; +} + +fn kill_process_group(pid: u32) { + #[cfg(unix)] + unsafe { + // Best effort; the child is also killed directly below by the caller. + libc::kill(-(pid as i32), libc::SIGKILL); + } + let _ = pid; +} + +// --------------------------------------------------------------------------- +// JSON DTOs: the exact public `marqdo.analysis` revision 3 shape +// --------------------------------------------------------------------------- + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AnalysisFile { + schema: String, + schema_version: u64, + producer: Producer, + project: Project, + modules: Vec, + diagnostics: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Producer { + name: String, + version: String, + markdown_profile: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Project { + root_id: String, + identity_kind: String, + entry_module_id: String, + lock_digest: String, + manifest_digest: String, + stdlib: Option, + extensions: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct StdlibIdentity { + version: String, + digest: String, + instance_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct RawModule { + id: String, + package_instance_id: String, + relative_path: String, + source_digest: String, + source: String, + document: Node, + units: Vec, + anchors: Vec, + functions: Vec, + imports: Vec, + references: Vec, + calls: Vec, + resources: Vec, +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Node { + pub kind: String, + pub span: Span, + pub children: Vec, + #[serde(default)] + pub literal: Option, + #[serde(default)] + pub tag: Option, + #[serde(default)] + pub level: Option, + #[serde(default)] + pub setext: Option, + #[serde(default)] + pub ordered: Option, + #[serde(default)] + pub start: Option, + #[serde(default)] + pub tight: Option, + #[serde(default)] + pub task: Option, + #[serde(default)] + pub ticks: Option, + #[serde(default)] + pub fenced: Option, + #[serde(default)] + pub info: Option, + #[serde(default)] + pub display: Option, + #[serde(default)] + pub url: Option, + #[serde(default)] + pub title: Option, + #[serde(default)] + pub alignments: Option>, + #[serde(default)] + pub header: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Unit { + pub id: String, + pub path: Vec, + pub parent_id: Option, + pub kind: String, + pub name: String, + pub level: u32, + pub mode: String, + pub mode_origin: String, + pub mode_source_unit_id: String, + pub heading_span: Option, + pub span: Span, + pub function: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Anchor { + anchor: String, + unit_id: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Function { + pub id: String, + pub unit_id: String, + pub local_name: String, + pub namespace: Option, + pub span: Span, + pub heading_span: Span, + pub signature: Signature, + pub effects: Vec, + pub body: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Signature { + pub kind: String, + pub params: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Param { + pub name: String, + pub required: bool, + #[serde(rename = "type")] + pub ty: Option, + pub default: Option, + pub span: Span, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(tag = "kind", deny_unknown_fields)] +pub enum Statement { + #[serde(rename = "assign")] + Assign { + target: Place, + value: Expression, + span: Span, + }, + #[serde(rename = "expression")] + Expression { value: Expression, span: Span }, + #[serde(rename = "branch")] + Branch { + arms: Vec, + span: Span, + }, + #[serde(rename = "loop")] + Loop { + condition: Expression, + condition_span: Span, + body: Vec, + span: Span, + }, + #[serde(rename = "return")] + Return { value: Expression, span: Span }, + #[serde(rename = "break")] + Break { span: Span }, + #[serde(rename = "continue")] + Continue { span: Span }, +} + +impl Statement { + pub fn span(&self) -> Span { + match self { + Statement::Assign { span, .. } + | Statement::Expression { span, .. } + | Statement::Branch { span, .. } + | Statement::Loop { span, .. } + | Statement::Return { span, .. } + | Statement::Break { span } + | Statement::Continue { span } => *span, + } + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct BranchArm { + pub condition: Expression, + pub condition_span: Span, + pub body: Vec, + pub span: Span, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum Place { + Local(String), + Index { + kind: String, + base: Expression, + index: Expression, + span: Span, + }, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(tag = "kind", deny_unknown_fields)] +pub enum Expression { + #[serde(rename = "literal")] + Literal { + #[serde(rename = "type")] + ty: String, + value: Option, + span: Span, + }, + #[serde(rename = "variable")] + Variable { name: String, span: Span }, + #[serde(rename = "list")] + List { + items: Vec, + span: Span, + }, + #[serde(rename = "record")] + Record { + entries: Vec, + span: Span, + }, + #[serde(rename = "unary")] + Unary { + op: String, + operand: Box, + span: Span, + }, + #[serde(rename = "binary")] + Binary { + op: String, + left: Box, + right: Box, + span: Span, + }, + #[serde(rename = "member")] + Member { + base: Box, + field: String, + span: Span, + }, + #[serde(rename = "index")] + Index { + base: Box, + index: Box, + span: Span, + }, + #[serde(rename = "call")] + Call { + callee: Box, + args: Vec, + span: Span, + }, +} + +impl Expression { + pub fn span(&self) -> Span { + match self { + Expression::Literal { span, .. } + | Expression::Variable { span, .. } + | Expression::List { span, .. } + | Expression::Record { span, .. } + | Expression::Unary { span, .. } + | Expression::Binary { span, .. } + | Expression::Member { span, .. } + | Expression::Index { span, .. } + | Expression::Call { span, .. } => *span, + } + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct RecordEntry { + pub key: String, + pub key_span: Span, + pub value: Expression, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Argument { + pub name: Option, + pub value: Expression, + pub span: Span, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Import { + pub alias: String, + pub target: String, + pub span: Span, + pub resolved: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Reference { + pub source: String, + pub source_unit: String, + pub url: String, + pub span: Span, + pub state: String, + pub target_kind: Option, + pub target_module: Option, + pub target_unit: Option, + pub candidate_package_instance_id: Option, + pub candidate_path: Option, + pub fragment: Option, + pub candidates: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Resource { + pub id: String, + pub module_id: String, + pub unit_id: String, + pub kind: String, + pub span: Span, + pub content_digest: String, + pub language: Option, + pub display: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct RawDiagnostic { + module: String, + relative_path: String, + span: Option, + line: Option, + column: Option, + severity: String, + code: String, + message: String, + hints: Vec, +} + +// --------------------------------------------------------------------------- +// Parsing + validation +// --------------------------------------------------------------------------- + +fn parse_and_validate(bytes: &[u8], entry_path: &Path, root: &Path) -> Result { + let text = std::str::from_utf8(bytes).map_err(|error| { + Failure::new( + codes::UPSTREAM_CONTRACT, + format!("emitted Analysis is not valid UTF-8: {error}"), + ) + })?; + let file: AnalysisFile = serde_json::from_str(text).map_err(|error| { + Failure::new( + codes::UPSTREAM_CONTRACT, + format!("emitted Analysis does not match the current marqdo.analysis revision 3 shape: {error}"), + ) + .with_hint("install and build a matching Marqdo CLI (analysis revision 3)") + })?; + let analysis_digest = sha256_hex(bytes); + + if file.schema != "marqdo.analysis" { + return contract(format!("unexpected Analysis schema `{}`", file.schema)); + } + if file.schema_version != REQUIRED_ANALYSIS_REVISION { + return contract(format!( + "Analysis schema_version {} does not match required {REQUIRED_ANALYSIS_REVISION}", + file.schema_version + )); + } + if file.producer.name != "marqdo" { + return contract(format!( + "unexpected Analysis producer `{}`", + file.producer.name + )); + } + if file.producer.markdown_profile != "marqdo.md.v1" { + return contract(format!( + "unexpected markdown profile `{}`", + file.producer.markdown_profile + )); + } + 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" { + return contract(format!( + "unexpected project identity kind `{}`", + file.project.identity_kind + )); + } + if !is_sha256_digest(&file.project.lock_digest) && !file.project.lock_digest.is_empty() { + return contract("project.lock_digest is not a canonical sha256 digest"); + } + if !is_sha256_digest(&file.project.manifest_digest) && !file.project.manifest_digest.is_empty() + { + return contract("project.manifest_digest is not a canonical sha256 digest"); + } + if file.modules.is_empty() { + return contract("Analysis contains no modules"); + } + + // Entry module lookup and physical identity. + let entry_matches: Vec<&RawModule> = file + .modules + .iter() + .filter(|module| module.id == file.project.entry_module_id) + .collect(); + if entry_matches.len() != 1 { + return contract("project.entry_module_id does not occur exactly once in modules"); + } + let entry_relative = entry_matches[0].relative_path.clone(); + let expected_relative = entry_path + .strip_prefix(root) + .map_err(|_| { + Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!("entry `{}` is not below root `{}`", entry_path.display(), root.display()), + ) + })? + .to_string_lossy() + .replace(std::path::MAIN_SEPARATOR, "/"); + if entry_relative != expected_relative { + return contract(format!( + "entry module relative_path `{entry_relative}` does not match the physical entry `{expected_relative}`" + )); + } + + let mut modules = BTreeMap::new(); + let mut instance_roots: HashMap = HashMap::new(); + for raw in &file.modules { + let data = validate_module(raw)?; + // Bind every package instance to a physical root inside the controlled + // root. A module must not claim an absolute or escaping relative path. + let physical = root.join(&data.relative_path); + let canonical = std::fs::canonicalize(&physical).map_err(|error| { + Failure::new( + codes::UPSTREAM_CONTRACT, + format!( + "Analysis module `{}` does not map to a readable file `{}`: {error}", + data.relative_path, + physical.display() + ), + ) + })?; + if !canonical.starts_with(root) { + return Err(Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!( + "Analysis module `{}` escapes the controlled root", + data.relative_path + ), + )); + } + 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 + { + // Distinct packages are allowed; equal instance ids are not. + } + } + if modules.insert(data.id.clone(), Arc::new(data)).is_some() { + return contract("duplicate module id in Analysis"); + } + } + if file.modules.len() > crate::limits::MAX_DOCUMENTS { + return Err(Failure::new( + codes::DOCUMENT_UNIT, + format!( + "Analysis loaded {} modules, above the {} document limit", + file.modules.len(), + crate::limits::MAX_DOCUMENTS + ), + )); + } + + Ok(Snapshot { + canonical_path: entry_path.to_path_buf(), + root: root.to_path_buf(), + relative_path: entry_relative, + analysis_digest, + analysis_byte_len: bytes.len(), + project: ProjectIdentity { + root_id: file.project.root_id.clone(), + identity_kind: file.project.identity_kind.clone(), + lock_digest: file.project.lock_digest.clone(), + manifest_digest: file.project.manifest_digest.clone(), + }, + entry_module_id: file.project.entry_module_id.clone(), + modules, + }) +} + +fn validate_module(raw: &RawModule) -> Result { + if !raw.id.contains("::") { + return contract("module.id is not a canonical module id"); + } + 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 == "..") + { + return contract(format!( + "module.relative_path `{}` is not a safe package-relative path", + raw.relative_path + )); + } + let source_digest = sha256_hex(raw.source.as_bytes()); + if source_digest != raw.source_digest { + return contract(format!( + "module `{}` source_digest does not match its source bytes", + raw.relative_path + )); + } + // Every span in the module must be a valid UTF-8 half-open range. + validate_node_spans(&raw.document, &raw.source, 0)?; + + let max_units = crate::limits::MAX_UNITS; + 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()), + )); + } + let mut unit_by_id = HashMap::new(); + for unit in &raw.units { + if unit.id.is_empty() { + return contract("unit.id is empty"); + } + if unit_by_id.insert(unit.id.clone(), ()).is_some() { + 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)); + } + 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)); + } + } + match unit.mode.as_str() { + "exec" | "knowledge" => {} + other => return contract(format!("unit `{}` has unknown mode `{other}`", unit.id)), + } + } + if raw.units.len() != unit_by_id.len() { + return contract("unit ids are not unique"); + } + + // Exactly one root unit, and a well-formed parent tree. + 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"); + } + let root_unit = roots[0]; + if !root_unit.path.is_empty() || root_unit.parent_id.is_some() || root_unit.level != 0 { + return contract("root unit is not the canonical empty root"); + } + if root_unit.span != Span::new(0, raw.source.len()) { + return contract("root unit span does not cover the module source"); + } + for unit in &raw.units { + if unit.kind == "root" { + continue; + } + if unit.level == 0 || unit.level > 6 { + return contract(format!("unit `{}` has an invalid heading level", unit.id)); + } + 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 = raw + .units + .iter() + .find(|candidate| candidate.id == parent_id) + .ok_or_else(|| { + Failure::new( + codes::UPSTREAM_CONTRACT, + format!("unit `{}` points at missing parent `{parent_id}`", unit.id), + ) + })?; + let mut expected_path = parent.path.clone(); + expected_path.push(unit.name.clone()); + if expected_path != unit.path { + return contract(format!( + "unit `{}` path does not equal parent path plus its own name", + unit.id + )); + } + 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)); + } + 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 + )); + } + } + + let mut anchors = BTreeMap::new(); + for anchor in &raw.anchors { + if anchor.anchor.is_empty() { + 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)); + } + 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)); + } + 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)?; + } + + for reference in &raw.references { + if reference.source != raw.id { + 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)); + } + if !unit_by_id.contains_key(&reference.source_unit) { + return contract("reference.source_unit points at an unknown unit"); + } + match reference.state.as_str() { + "resolved" => { + if reference.target_kind.as_deref() == Some("module") + && reference.target_module.is_none() + { + return contract("resolved module reference has no target_module"); + } + } + "not_loaded" | "missing" | "ambiguous" | "external" | "outside_scope" | "invalid" => {} + other => return contract(format!("reference has unknown state `{other}`")), + } + } + + 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)); + } + if !unit_by_id.contains_key(&resource.unit_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), + ) + })?; + let literal = math_literal(payload).ok_or_else(|| { + Failure::new( + codes::UPSTREAM_CONTRACT, + format!("formula resource `{}` is not a math node", resource.id), + ) + })?; + if sha256_hex(literal.as_bytes()) != resource.content_digest { + return contract(format!( + "formula resource `{}` content_digest does not match its AST payload", + resource.id + )); + } + } + "code" => {} + other => return contract(format!("resource has unknown kind `{other}`")), + } + } + + // Imports must resolve to modules the CLI actually loaded (or be diagnostics + // that the CLI would have rejected; a successful Analysis has none). + let module_ids: Vec<&str> = raw.units.iter().map(|unit| unit.id.as_str()).collect(); + let _ = module_ids; + for import in &raw.imports { + if import.alias.is_empty() { + return contract("import alias is empty"); + } + if !import.span.is_valid_in(&raw.source) { + return contract("import span is out of range"); + } + } + + Ok(ModuleData { + id: raw.id.clone(), + package_instance_id: raw.package_instance_id.clone(), + relative_path: raw.relative_path.clone(), + source: raw.source.clone(), + source_digest, + document: raw.document.clone(), + units: raw.units.clone(), + anchors, + functions: raw.functions.clone(), + references: raw.references.clone(), + resources: raw.resources.clone(), + unit_by_id: raw + .units + .iter() + .enumerate() + .map(|(index, unit)| (unit.id.clone(), index)) + .collect(), + }) +} + +fn is_ancestor(module: &RawModule, ancestor_id: &str, unit_id: &str) -> bool { + let by_id: HashMap<&str, &Unit> = module + .units + .iter() + .map(|unit| (unit.id.as_str(), unit)) + .collect(); + let mut current = by_id.get(unit_id).copied(); + let mut steps = 0usize; + while let Some(unit) = current { + if unit.id == ancestor_id { + return true; + } + steps += 1; + if steps > 64 { + return false; + } + current = match unit.parent_id.as_deref() { + Some(parent) => by_id.get(parent).copied(), + None => None, + }; + } + false +} + +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), + )); + } + if !node.span.is_valid_in(source) { + return contract(format!( + "document node `{}` has an out-of-range span {}", + node.kind, node.span + )); + } + for child in &node.children { + if child.span.start < node.span.start || child.span.end > node.span.end { + return contract(format!( + "document node `{}` child `{}` is not nested in its parent span", + node.kind, child.kind + )); + } + 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" { + return contract(format!("document node `{}` has no literal", node.kind)); + } + } + _ => {} + } + Ok(()) +} + +fn validate_statements(statements: &[Statement], source: &str) -> Result<()> { + for statement in statements { + if !statement.span().is_valid_in(source) { + return contract("function statement span is out of range"); + } + match statement { + Statement::Assign { value, .. } | Statement::Expression { value, .. } => { + validate_expression(value, source)?; + } + Statement::Return { value, .. } => validate_expression(value, source)?, + Statement::Branch { arms, .. } => { + for arm in arms { + validate_expression(&arm.condition, source)?; + validate_statements(&arm.body, source)?; + } + } + Statement::Loop { condition, body, .. } => { + validate_expression(condition, source)?; + validate_statements(body, source)?; + } + Statement::Break { .. } | Statement::Continue { .. } => {} + } + } + Ok(()) +} + +fn validate_expression(expression: &Expression, source: &str) -> Result<()> { + if !expression.span().is_valid_in(source) { + return contract("function expression span is out of range"); + } + match expression { + Expression::List { items, .. } => { + for item in items { + validate_expression(item, source)?; + } + } + Expression::Record { entries, .. } => { + for entry in entries { + validate_expression(&entry.value, source)?; + } + } + Expression::Unary { operand, .. } => validate_expression(operand, source)?, + Expression::Binary { left, right, .. } => { + validate_expression(left, source)?; + validate_expression(right, source)?; + } + Expression::Member { base, .. } => validate_expression(base, source)?, + Expression::Index { base, index, .. } => { + validate_expression(base, source)?; + validate_expression(index, source)?; + } + Expression::Call { callee, args, .. } => { + validate_expression(callee, source)?; + for arg in args { + validate_expression(&arg.value, source)?; + } + } + Expression::Literal { .. } | Expression::Variable { .. } => {} + } + Ok(()) +} + +/// Find the node whose span equals the resource span. +fn find_payload<'a>(node: &'a Node, span: Span) -> Option<&'a Node> { + if node.span == span { + return Some(node); + } + for child in &node.children { + if span.start >= child.span.start && span.end <= child.span.end { + if let Some(found) = find_payload(child, span) { + return Some(found); + } + } + } + None +} + +fn math_literal(node: &Node) -> Option<&str> { + match node.kind.as_str() { + "math_block" => node.literal.as_deref(), + "math" if node.display == Some(true) => node.literal.as_deref(), + _ => None, + } +} + +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()) +} + +fn contract(message: impl Into) -> Result { + 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", + )) +} + +// --------------------------------------------------------------------------- +// Unit tests for the contract validator +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + fn analysis_json(module_extra: &str) -> String { + format!( + r#"{{ + "schema": "marqdo.analysis", + "schema_version": 3, + "producer": {{"name": "marqdo", "version": "test", "markdown_profile": "marqdo.md.v1"}}, + "project": {{ + "root_id": "root:test@0.1.0", + "identity_kind": "manifest", + "entry_module_id": "root:test@0.1.0::index.mq.md", + "lock_digest": "", + "manifest_digest": "", + "stdlib": null, + "extensions": [] + }}, + "modules": [{module_extra}], + "diagnostics": [] +}}"# + ) + } + + fn simple_module() -> String { + let source = "# 标题\n"; + let digest = sha256_hex(source.as_bytes()); + format!( + r#"{{ + "id": "root:test@0.1.0::index.mq.md", + "package_instance_id": "root:test@0.1.0", + "relative_path": "index.mq.md", + "source_digest": "{digest}", + "source": {source:?}, + "document": {{"kind": "document", "span": {{"start": 0, "end": {len}}}, "children": [ + {{"kind": "heading", "span": {{"start": 0, "end": {len}}}, "children": [ + {{"kind": "text", "span": {{"start": 2, "end": {len}}}, "literal": "标题", "children": []}} + ], "level": 1, "setext": false}} + ]}}, + "units": [ + {{"id": "root:test@0.1.0::index.mq.md#", "path": [], "parent_id": null, "kind": "root", "name": "", "level": 0, "mode": "knowledge", "mode_origin": "default", "mode_source_unit_id": "root:test@0.1.0::index.mq.md#", "heading_span": null, "span": {{"start": 0, "end": {len}}}, "function": null}}, + {{"id": "root:test@0.1.0::index.mq.md#标题", "path": ["标题"], "parent_id": "root:test@0.1.0::index.mq.md#", "kind": "namespace", "name": "标题", "level": 1, "mode": "knowledge", "mode_origin": "inherited", "mode_source_unit_id": "root:test@0.1.0::index.mq.md#", "heading_span": {{"start": 0, "end": {len}}}, "span": {{"start": 0, "end": {len}}}, "function": null}} + ], + "anchors": [{{"anchor": "标题", "unit_id": "root:test@0.1.0::index.mq.md#标题"}}], + "functions": [], + "imports": [], + "references": [], + "calls": [], + "resources": [] +}}"#, + len = source.len() + ) + } + + #[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(); + 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(); + 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(); + assert_eq!(error.code, codes::UPSTREAM_CONTRACT); + } + + #[test] + fn resolve_fragment_prefers_anchor_then_exact_name() { + let module = ModuleData { + id: "root:x::a.mq.md".to_string(), + package_instance_id: "root:x".to_string(), + relative_path: "a.mq.md".to_string(), + source: String::new(), + source_digest: String::new(), + document: Node { + kind: "document".to_string(), + span: Span::new(0, 0), + children: vec![], + literal: None, + tag: None, + level: None, + setext: None, + ordered: None, + start: None, + tight: None, + task: None, + ticks: None, + fenced: None, + info: None, + display: None, + url: None, + title: None, + alignments: None, + header: None, + }, + units: vec![], + anchors: BTreeMap::new(), + functions: vec![], + references: vec![], + resources: vec![], + unit_by_id: HashMap::new(), + }; + assert_eq!(module.resolve_fragment("缺失"), FragmentResolution::Missing); + assert_eq!(module.resolve_fragment(""), FragmentResolution::DocumentRoot); + } +} diff --git a/src/document.rs b/src/document.rs index 217e5d9..1f83cea 100644 --- a/src/document.rs +++ b/src/document.rs @@ -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, + /// 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, + /// 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, +} + +/// 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 { + 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 { + 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 { + 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 { + 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 = ¶graph.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 { + 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() { + "".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, url: Option<&str>, children: Vec) -> 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, document: Node) -> ModuleData { + let unit_by_id = units + .iter() + .enumerate() + .map(|(index, unit)| (unit.id.clone(), index)) + .collect::>(); + 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); + } +} diff --git a/src/lib.rs b/src/lib.rs index 698083c..d1d110f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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, diff --git a/tests/analysis_document.rs b/tests/analysis_document.rs new file mode 100644 index 0000000..40543c3 --- /dev/null +++ b/tests/analysis_document.rs @@ -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 { + 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"); +}