diff --git a/Cargo.lock b/Cargo.lock index 15a03da..cd0c6da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -381,7 +381,6 @@ dependencies = [ "serde_yaml", "sha2", "tempfile", - "thiserror", "unicode-normalization", ] @@ -636,26 +635,6 @@ dependencies = [ "windows-sys", ] -[[package]] -name = "thiserror" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "tinyvec" version = "1.13.3" diff --git a/Cargo.toml b/Cargo.toml index 27443c6..b860a8f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,6 @@ serde_json = "=1.0.154" serde_yaml = "=0.9.34" sha2 = "=0.10.9" tempfile = "=3.27.0" -thiserror = "=2.0.21" unicode-normalization = "=0.1.26" [profile.release] diff --git a/scripts/regenerate-analysis-fixture.sh b/scripts/regenerate-analysis-fixture.sh new file mode 100755 index 0000000..6d86c07 --- /dev/null +++ b/scripts/regenerate-analysis-fixture.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# Regenerate the committed Analysis positive fixture with a real core CLI. +# +# Usage: scripts/regenerate-analysis-fixture.sh /path/to/marqdo +# The emitted artefact is recorded together with the producer identity in +# tests/fixtures/analysis/README.md. Never hand-edit the fixture. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +BIN=${1:?usage: $0 /path/to/marqdo} +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +mkdir -p "$WORK/project/physics" +cat > "$WORK/project/marqdo.yaml" <<'YAML' +project: + name: demo + version: 0.1.0 + marqdo: ">=3.0.0-beta.1,<4.0.0" +dependencies: {} +YAML +cat > "$WORK/project/physics/mechanics.mq.md" <<'MD' +--- +type: Theory +title: 经典力学 +tags: [physics, mechanics] +--- + +# 经典力学 + +## @knowledge 牛顿第二定律 + +合外力等于质量与加速度的乘积。 + +$$ +F = ma +$$ + +| 符号 | 含义 | +| --- | --- | +| m | 质量 | +| a | 加速度 | + +计算入口:[计算力](#计算力)。 + +## @exec 计算力 + +`params(m, a)` + +依据[牛顿第二定律](#牛顿第二定律)。 + +`return m * a` +MD +( + cd "$WORK/project" + "$BIN" check physics/mechanics.mq.md --emit "$WORK/analysis.json" +) +cp "$WORK/analysis.json" "$ROOT/tests/fixtures/analysis/mechanics.json" +( + cd "$ROOT/tests/fixtures/analysis" + sha256sum mechanics.json > mechanics.json.sha256 +) +"$BIN" --version +sha256sum "$BIN" diff --git a/src/cli.rs b/src/cli.rs index 923dade..9ca69a2 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -338,15 +338,14 @@ fn validate_embedding( "semantic search requires --embedding-url, --embedding-model and --embedding-revision", )); } - if configured { - if embedding.embedding_url.is_none() + if configured + && (embedding.embedding_url.is_none() || embedding.embedding_model.is_none() - || embedding.embedding_revision.is_none() - { - return Err(KnowledgeError::usage( - "--embedding-url, --embedding-model and --embedding-revision must be given together", - )); - } + || embedding.embedding_revision.is_none()) + { + return Err(KnowledgeError::usage( + "--embedding-url, --embedding-model and --embedding-revision must be given together", + )); } Ok(()) } @@ -421,11 +420,9 @@ fn render_check_human(json_text: &str) -> Result { } /// Exit code helper for commands that produce knowledge diagnostics. -pub fn exit_code_for(errors: usize, warnings: usize) -> i32 { +pub fn exit_code_for(errors: usize, _warnings: usize) -> i32 { if errors > 0 { EXIT_INPUT - } else if warnings > 0 { - EXIT_OK } else { EXIT_OK } diff --git a/src/document/analysis.rs b/src/document/analysis.rs index 805bcac..23d05b8 100644 --- a/src/document/analysis.rs +++ b/src/document/analysis.rs @@ -1,4 +1,2224 @@ -//! Adapter for the core CLI's current public Analysis contract -//! (`marqdo.analysis`, revision 3, produced by `check ENTRY --emit PATH`). +//! Adapter for the core CLI's current public Analysis contract. //! -//! Implemented in the document milestone. +//! `marqdo check ENTRY --emit PATH` emits `marqdo.analysis` revision 3. This +//! module owns the only reader of that artefact. It performs closed-shape and +//! semantic validation (development specification U06) and converts accepted +//! modules into the tool's `DocumentFacts`. Nothing here re-parses Marqdo +//! semantics, re-binds a resolved reference, guesses a dynamic call target or +//! silently accepts an older shape. + +use super::ast::AstNode; +use super::core_cli::{AnalysisBytes, CoreCli, CoreIdentity}; +use super::markdown; +use super::{ + AnalysisFacts, AnalysisReferenceFact, AnchorFact, CallFact, DocumentFacts, FunctionFact, + ImportFact, ReferenceFact, ResourceFact, UnitFact, UnitKind, +}; +use crate::diagnostic::{code, Diagnostic, DiagnosticSet, Severity}; +use crate::model::{edge_state_from_analysis, sha256_hex, sha256_prefixed, EdgeState, Span}; +use serde::Deserialize; +use std::collections::{HashMap, HashSet}; + +pub const ANALYSIS_SCHEMA: &str = "marqdo.analysis"; +pub const ANALYSIS_REVISION: u64 = 3; +pub const MARKDOWN_PROFILE: &str = "marqdo.md.v1"; +const MAX_EXPRESSION_DEPTH: usize = 256; +const MAX_MODULES: usize = 100_000; +const MAX_AST_NODES: usize = 2_000_000; + +// --------------------------------------------------------------------------- +// Contract types (closed; every object rejects unknown fields) +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Artifact { + pub schema: String, + pub schema_version: u64, + pub producer: Producer, + pub project: Project, + pub modules: Vec, + pub diagnostics: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Producer { + pub name: String, + pub version: String, + pub markdown_profile: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Project { + pub root_id: String, + pub identity_kind: IdentityKind, + pub entry_module_id: String, + pub lock_digest: String, + pub manifest_digest: String, + pub stdlib: Option, + pub extensions: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum IdentityKind { + Manifest, + WorkspaceSnapshot, +} + +impl IdentityKind { + pub fn as_str(self) -> &'static str { + match self { + IdentityKind::Manifest => "manifest", + IdentityKind::WorkspaceSnapshot => "workspace_snapshot", + } + } +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StdlibIdentity { + pub version: String, + pub digest: String, + pub instance_id: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExtensionIdentity { + pub kind: ExtensionKind, + pub name: String, + pub version: String, + pub logical_owner: String, + pub source: String, + pub manifest_digest: String, + pub artifact_digest: String, + pub selected_target: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ExtensionKind { + Plugin, + Kernel, + Provider, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Module { + pub id: String, + pub package_instance_id: String, + pub relative_path: String, + pub source_digest: String, + pub source: String, + pub document: AstNode, + pub units: Vec, + pub anchors: Vec, + pub functions: Vec, + pub imports: Vec, + pub references: Vec, + pub calls: Vec, + pub resources: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Unit { + pub id: String, + pub path: Vec, + pub parent_id: Option, + pub kind: UnitKindA, + pub name: String, + pub level: u8, + pub mode: Mode, + pub mode_origin: ModeOrigin, + pub mode_source_unit_id: String, + pub heading_span: Option, + pub span: Span, + pub function: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UnitKindA { + Root, + Namespace, + Function, + Knowledge, + Section, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Mode { + Exec, + Knowledge, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ModeOrigin { + Default, + Explicit, + Inherited, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Anchor { + pub anchor: String, + pub unit_id: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[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, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct Signature { + pub kind: SignatureKind, + pub params: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SignatureKind { + Explicit, + Inferred, +} + +#[derive(Debug, Clone, Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct Param { + pub name: String, + pub required: bool, + #[serde(rename = "type")] + pub type_name: Option, + pub default: Option, + pub span: Span, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Import { + pub alias: String, + pub target: String, + pub span: Span, + pub resolved: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Reference { + pub source: String, + pub source_unit: String, + pub url: String, + pub span: Span, + pub state: RefState, + 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, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RefState { + Resolved, + NotLoaded, + Missing, + Ambiguous, + External, + OutsideScope, + Invalid, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TargetKind { + Module, + File, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Call { + pub function: String, + pub span: Span, + pub callee: serde_json::Value, + pub state: CallState, + pub target: Option, + pub target_kind: Option, + pub target_owner: Option, + pub reason: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CallState { + Function, + Builtin, + Plugin, + Unresolved, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CallTargetKind { + Function, + Builtin, + Plugin, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CallReason { + Dynamic, + Unbound, +} + +#[derive(Debug, Clone, Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct TargetOwner { + pub kind: OwnerKind, + pub package: String, + pub digest: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum OwnerKind { + Plugin, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Resource { + pub id: String, + pub module_id: String, + pub unit_id: String, + pub kind: ResourceKind, + pub span: Span, + pub content_digest: String, + pub language: Option, + pub display: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ResourceKind { + Formula, + Code, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisDiagnostic { + pub module: String, + pub relative_path: String, + pub span: Option, + pub line: Option, + pub column: Option, + pub severity: Severity, + pub code: String, + pub message: String, + pub hints: Vec, +} + +// --------------------------------------------------------------------------- +// Batch and conversion results +// --------------------------------------------------------------------------- + +/// Identity of one Analysis preparation context (one entry). +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct ProjectContext { + pub context_id: String, + pub entry_module_id: String, + pub root_id: String, + pub identity_kind: String, + pub manifest_digest: String, + pub lock_digest: String, + pub stdlib_digest: Option, + pub producer_version: String, + pub analysis_digest: String, + pub extensions: serde_json::Value, +} + +impl ProjectContext { + fn from_artifact(artifact: &Artifact, analysis_digest: &str) -> Self { + let extensions = serde_json::to_value( + artifact + .project + .extensions + .iter() + .map(|extension| { + serde_json::json!({ + "kind": format!("{:?}", extension.kind).to_lowercase(), + "name": extension.name, + "version": extension.version, + "logical_owner": extension.logical_owner, + "source": extension.source, + "manifest_digest": extension.manifest_digest, + "artifact_digest": extension.artifact_digest, + "selected_target": extension.selected_target, + }) + }) + .collect::>(), + ) + .unwrap_or(serde_json::Value::Null); + let stdlib_digest = artifact + .project + .stdlib + .as_ref() + .map(|stdlib| stdlib.digest.clone()); + let identity = serde_json::json!({ + "entry_module_id": artifact.project.entry_module_id, + "root_id": artifact.project.root_id, + "identity_kind": artifact.project.identity_kind.as_str(), + "manifest_digest": artifact.project.manifest_digest, + "lock_digest": artifact.project.lock_digest, + "stdlib_digest": stdlib_digest, + "producer_version": artifact.producer.version, + "extensions": extensions, + }); + let context_id = sha256_prefixed(identity.to_string().as_bytes()); + Self { + context_id, + entry_module_id: artifact.project.entry_module_id.clone(), + root_id: artifact.project.root_id.clone(), + identity_kind: artifact.project.identity_kind.as_str().to_string(), + manifest_digest: artifact.project.manifest_digest.clone(), + lock_digest: artifact.project.lock_digest.clone(), + stdlib_digest, + producer_version: artifact.producer.version.clone(), + analysis_digest: analysis_digest.to_string(), + extensions, + } + } +} + +/// One accepted module plus the contexts that produced it. +#[derive(Debug, Clone)] +pub struct ModuleFacts { + pub module_id: String, + pub package_instance_id: String, + pub source: String, + /// Lowercase hex SHA-256 of the exact module source. + pub source_digest_hex: String, + pub context_ids: Vec, + pub facts: DocumentFacts, +} + +#[derive(Debug)] +pub struct AnalysisBatch { + pub core: CoreIdentity, + pub producer_version: String, + pub contexts: Vec, + pub modules: Vec, + pub diagnostics: DiagnosticSet, + /// Entries whose Analysis invocation or validation failed. + pub failed_entries: Vec, +} + +impl AnalysisBatch { + pub fn module_for_path(&self, rel_path: &str) -> Option<&ModuleFacts> { + self.modules + .iter() + .find(|module| module.facts.rel_path == rel_path) + } +} + +/// Run the core CLI for every entry candidate and build a merged, validated +/// batch. Entries are invoked in sorted order for deterministic diagnostics. +pub fn analyze_core(root: &std::path::Path, entries: &[String], core: &CoreCli) -> AnalysisBatch { + let mut diagnostics = DiagnosticSet::new(); + let mut contexts: Vec = Vec::new(); + let mut modules: Vec = Vec::new(); + let mut failed_entries = Vec::new(); + let mut producer_version = String::new(); + let mut entries: Vec<&String> = entries.iter().collect(); + entries.sort(); + + for entry in entries { + let emitted: AnalysisBytes = match core.emit_analysis(root, entry) { + Ok(bytes) => bytes, + Err(error) => { + failed_entries.push(entry.clone()); + diagnostics.push( + Diagnostic::error(error.code, error.message) + .with_path(entry.as_str()) + .with_hint("fix the document so the core CLI can emit Analysis"), + ); + continue; + } + }; + let analysis_digest = sha256_prefixed(&emitted.bytes); + let artifact = match parse_and_validate(&emitted.bytes) { + Ok(artifact) => artifact, + Err(problems) => { + failed_entries.push(entry.clone()); + diagnostics.merge(problems); + continue; + } + }; + if producer_version.is_empty() { + producer_version = artifact.producer.version.clone(); + } + let context = ProjectContext::from_artifact(&artifact, &analysis_digest); + // Artifact level warnings are preserved for the compile report. + for diagnostic in &artifact.diagnostics { + diagnostics.push(Diagnostic { + code: diagnostic.code.clone(), + severity: diagnostic.severity, + path: Some(diagnostic.relative_path.clone()), + span: diagnostic.span, + message: diagnostic.message.clone(), + hints: diagnostic.hints.clone(), + }); + } + + for module in &artifact.modules { + match module_to_facts(&artifact, module, &context) { + Ok(facts) => merge_module( + &mut modules, + &mut diagnostics, + ModuleFacts { + module_id: module.id.clone(), + package_instance_id: module.package_instance_id.clone(), + source: module.source.clone(), + source_digest_hex: sha256_hex(module.source.as_bytes()), + context_ids: vec![context.context_id.clone()], + facts, + }, + ), + Err(problems) => diagnostics.merge(problems), + } + } + // Store every context (deduplicated by id) even if all its modules were + // already present from another entry. + if !contexts + .iter() + .any(|existing| existing.context_id == context.context_id) + { + contexts.push(context); + } + } + + AnalysisBatch { + core: core.identity.clone(), + producer_version, + contexts, + modules, + diagnostics, + failed_entries, + } +} + +fn merge_module( + modules: &mut Vec, + diagnostics: &mut DiagnosticSet, + candidate: ModuleFacts, +) { + if let Some(existing) = modules + .iter_mut() + .find(|module| module.module_id == candidate.module_id) + { + if existing.source_digest_hex != candidate.source_digest_hex { + diagnostics.push( + Diagnostic::error( + code::ANALYSIS_CONTEXT_CONFLICT, + "the same module identity reports different source bytes in one compilation", + ) + .with_path(&candidate.facts.rel_path), + ); + return; + } + for context_id in &candidate.context_ids { + if !existing.context_ids.contains(context_id) { + existing.context_ids.push(context_id.clone()); + } + } + return; + } + if let Some(existing) = modules + .iter() + .find(|module| module.facts.rel_path == candidate.facts.rel_path) + { + if existing.source_digest_hex != candidate.source_digest_hex + || existing.module_id != candidate.module_id + { + diagnostics.push( + Diagnostic::error( + code::ANALYSIS_CONTEXT_CONFLICT, + format!( + "two Analysis contexts map different modules to `{}`; the contexts are not merged", + candidate.facts.rel_path + ), + ) + .with_path(&candidate.facts.rel_path), + ); + return; + } + } + modules.push(candidate); +} + +// --------------------------------------------------------------------------- +// Parsing and semantic validation +// --------------------------------------------------------------------------- + +/// Parse and fully validate one emitted artifact. Returns all problems found, +/// not just the first, so a bad producer is easy to diagnose. +pub fn parse_and_validate(bytes: &[u8]) -> Result { + let mut problems = DiagnosticSet::new(); + let value: serde_json::Value = match serde_json::from_slice(bytes) { + Ok(value) => value, + Err(error) => { + problems.push(Diagnostic::error( + code::ANALYSIS_INVALID, + format!("Analysis artifact is not valid JSON: {error}"), + )); + return Err(problems); + } + }; + let artifact: Artifact = match serde_json::from_value(value) { + Ok(artifact) => artifact, + Err(error) => { + problems.push(Diagnostic::error( + code::ANALYSIS_INVALID, + format!("Analysis artifact does not match the revision-3 closed shape: {error}"), + )); + return Err(problems); + } + }; + for issue in validate_semantics(&artifact) { + problems.push(issue); + } + if problems.has_errors() { + problems.sorted(); + return Err(problems); + } + Ok(artifact) +} + +fn error(message: impl Into) -> Diagnostic { + Diagnostic::error(code::ANALYSIS_INVALID, message) +} + +fn validate_semantics(artifact: &Artifact) -> Vec { + let mut issues = Vec::new(); + if artifact.schema != ANALYSIS_SCHEMA { + issues.push(error(format!( + "schema must be `{ANALYSIS_SCHEMA}`, found `{}`", + artifact.schema + ))); + } + if artifact.schema_version != ANALYSIS_REVISION { + issues.push(Diagnostic::error( + code::ANALYSIS_UNSUPPORTED, + format!( + "Analysis revision {} is not supported; this build requires revision {ANALYSIS_REVISION}", + artifact.schema_version + ), + )); + } + if artifact.producer.name != "marqdo" { + issues.push(error("producer.name must be `marqdo`")); + } + if artifact.producer.markdown_profile != MARKDOWN_PROFILE { + issues.push(error(format!( + "producer.markdown_profile must be `{MARKDOWN_PROFILE}`" + ))); + } + if artifact.producer.version.trim().is_empty() { + issues.push(error("producer.version must not be empty")); + } + validate_project(artifact, &mut issues); + if artifact.modules.len() > MAX_MODULES { + issues.push(Diagnostic::error( + code::BUDGET_EXCEEDED, + format!( + "Analysis reports {} modules, above the {MAX_MODULES} module budget", + artifact.modules.len() + ), + )); + } + + let mut ids = HashSet::new(); + let mut previous_id: Option<&str> = None; + for module in &artifact.modules { + if !ids.insert(module.id.as_str()) { + issues.push( + error(format!("duplicate module id `{}`", module.id)) + .with_path(&module.relative_path), + ); + } + if let Some(previous) = previous_id { + if previous > module.id.as_str() { + issues.push( + error("modules are not sorted by canonical id") + .with_path(&module.relative_path), + ); + } + } + previous_id = Some(module.id.as_str()); + validate_module(artifact, module, &mut issues); + } + if !artifact + .modules + .iter() + .any(|module| module.id == artifact.project.entry_module_id) + { + issues.push(error(format!( + "project.entry_module_id `{}` does not occur exactly once in modules", + artifact.project.entry_module_id + ))); + } + validate_artifact_diagnostics(artifact, &ids, &mut issues); + issues +} + +fn validate_project(artifact: &Artifact, issues: &mut Vec) { + let project = &artifact.project; + if !valid_root_id(&project.root_id) { + issues.push(error(format!( + "project.root_id `{}` is not a manifest identity or content snapshot", + project.root_id + ))); + } + for (name, digest) in [ + ("lock_digest", &project.lock_digest), + ("manifest_digest", &project.manifest_digest), + ] { + if !digest.is_empty() && !crate::model::is_sha256_prefixed(digest) { + issues.push(error(format!("project.{name} is not a `sha256:` digest"))); + } + } + if let Some(stdlib) = &project.stdlib { + if stdlib.version.trim().is_empty() || stdlib.instance_id.trim().is_empty() { + issues.push(error( + "project.stdlib version/instance_id must not be empty", + )); + } + if !crate::model::is_sha256_prefixed(&stdlib.digest) { + issues.push(error("project.stdlib.digest is not a `sha256:` digest")); + } + } + for extension in &project.extensions { + for (name, digest) in [ + ("manifest_digest", &extension.manifest_digest), + ("artifact_digest", &extension.artifact_digest), + ] { + if !crate::model::is_sha256_prefixed(digest) { + issues.push(error(format!( + "extension `{}` {name} is not a `sha256:` digest", + extension.name + ))); + } + } + if extension.name.trim().is_empty() + || extension.version.trim().is_empty() + || extension.logical_owner.trim().is_empty() + || extension.source.trim().is_empty() + || extension.selected_target.trim().is_empty() + { + issues.push(error("extension identity fields must not be empty")); + } + } +} + +fn valid_root_id(root_id: &str) -> bool { + if root_id.starts_with("sha256:") { + return crate::model::is_sha256_prefixed(root_id); + } + let Some(rest) = root_id.strip_prefix("root:") else { + return false; + }; + !rest.is_empty() + && rest + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '@' | '+' | '/' | '-')) + && rest.contains('@') +} + +fn validate_module(artifact: &Artifact, module: &Module, issues: &mut Vec) { + let path = module.relative_path.clone(); + macro_rules! push { + ($diagnostic:expr) => { + issues.push($diagnostic.with_path(path.clone())) + }; + } + if crate::document::discovery::validate_relative_path(&module.relative_path).is_err() { + push!(error( + "module.relative_path is not a safe root-relative path" + )); + } + if module.package_instance_id.trim().is_empty() { + push!(error("module.package_instance_id must not be empty")); + } + if module.id != format!("{}::{}", module.package_instance_id, module.relative_path) { + push!(error(format!( + "module.id `{}` is not package_instance_id::relative_path", + module.id + ))); + } + if !crate::model::is_sha256_hex(&module.source_digest) { + push!(error( + "module.source_digest must be 64 lowercase hex characters" + )); + } + let computed = sha256_hex(module.source.as_bytes()); + if computed != module.source_digest { + push!(error( + "module.source_digest does not match the module source bytes" + )); + } + let source = module.source.as_bytes(); + if module.document.kind != super::ast::AstKind::Document { + push!(error("module.document must be a document node")); + } + if module.document.span != Span::new(0, source.len() as u64) { + push!(error( + "module.document span must cover the whole module source" + )); + } + if let Err(message) = module.document.validate(source, super::MAX_AST_DEPTH) { + push!(error(format!("module.document is invalid: {message}"))); + } + count_ast_nodes(&module.document, &mut 0u64, issues, &path); + + let mut unit_index: HashMap<&str, usize> = HashMap::new(); + for (index, unit) in module.units.iter().enumerate() { + if unit_index.insert(unit.id.as_str(), index).is_some() { + push!(error(format!("duplicate unit id `{}`", unit.id))); + } + } + if module.units.is_empty() + || module.units[0].kind != UnitKindA::Root + || module.units[0].span != Span::new(0, source.len() as u64) + { + push!(error( + "units must start with one root unit covering the whole source" + )); + } + if module + .units + .iter() + .filter(|unit| unit.kind == UnitKindA::Root) + .count() + != 1 + { + push!(error("there must be exactly one root unit")); + } + let mut anchor_names = HashSet::new(); + for anchor in &module.anchors { + if !anchor_names.insert(anchor.anchor.as_str()) { + push!(error(format!("duplicate anchor `{}`", anchor.anchor))); + } + if !unit_index.contains_key(anchor.unit_id.as_str()) { + push!(error(format!( + "anchor `{}` names an unknown unit", + anchor.anchor + ))); + } + } + for (index, unit) in module.units.iter().enumerate() { + validate_unit(module, index, unit, &unit_index, source, issues, &path); + } + validate_units_are_ordered(module, source, issues, &path); + validate_functions(module, &unit_index, source, issues, &path); + for import in &module.imports { + check_span(import.span, source, &path, "import", issues); + if let Some(resolved) = &import.resolved { + if !resolved.contains("::") { + push!(error("resolved import target is not a canonical module id")); + } + } + } + validate_references(module, &unit_index, source, issues, &path); + validate_calls(module, source, issues, &path); + validate_resources(module, &unit_index, source, issues, &path); + let _ = artifact; +} + +fn count_ast_nodes(node: &AstNode, count: &mut u64, issues: &mut Vec, path: &str) { + *count += 1; + if *count > MAX_AST_NODES as u64 { + issues.push( + error(format!( + "document AST exceeds the {MAX_AST_NODES} node budget" + )) + .with_path(path), + ); + return; + } + for child in &node.children { + count_ast_nodes(child, count, issues, path); + } +} + +fn check_span(span: Span, source: &[u8], path: &str, what: &str, issues: &mut Vec) { + if !span.on_utf8_boundaries(source) { + issues.push( + error(format!( + "{what} span {} is outside the source or splits a UTF-8 character", + span + )) + .with_path(path), + ); + } +} + +fn validate_unit( + module: &Module, + index: usize, + unit: &Unit, + unit_index: &HashMap<&str, usize>, + source: &[u8], + issues: &mut Vec, + path: &str, +) { + check_span(unit.span, source, path, "unit", issues); + if let Some(heading) = unit.heading_span { + check_span(heading, source, path, "unit heading", issues); + if !unit.span.contains(heading) { + issues.push( + error(format!( + "unit `{}` section span does not contain its heading", + unit.name + )) + .with_path(path), + ); + } + } + if index == 0 { + if unit.path != Vec::::new() + || unit.parent_id.is_some() + || unit.kind != UnitKindA::Root + || unit.level != 0 + || !unit.name.is_empty() + || unit.heading_span.is_some() + || unit.function.is_some() + || unit.mode != Mode::Knowledge + || unit.mode_origin != ModeOrigin::Default + || unit.mode_source_unit_id != unit.id + { + issues.push(error("root unit has inconsistent root fields").with_path(path)); + } + return; + } + if unit.path.is_empty() { + issues + .push(error(format!("non-root unit `{}` has an empty path", unit.id)).with_path(path)); + } + if !(1..=6).contains(&unit.level) { + issues.push(error(format!("unit `{}` has an invalid level", unit.id)).with_path(path)); + } + if unit.heading_span.is_none() { + issues.push( + error(format!("non-root unit `{}` has no heading span", unit.id)).with_path(path), + ); + } + let Some(parent_id) = &unit.parent_id else { + issues.push(error(format!("non-root unit `{}` has no parent", unit.id)).with_path(path)); + return; + }; + let Some(parent_index) = unit_index.get(parent_id.as_str()) else { + issues.push(error(format!("unit `{}` names an unknown parent", unit.id)).with_path(path)); + return; + }; + let parent = &module.units[*parent_index]; + if unit.path.len() != parent.path.len() + 1 || unit.path[..parent.path.len()] != parent.path[..] + { + issues.push( + error(format!( + "unit `{}` path is not parent.path + its own name", + unit.id + )) + .with_path(path), + ); + } + match unit.kind { + UnitKindA::Function => { + if unit.function.is_none() { + issues.push( + error(format!("function unit `{}` has no function id", unit.id)) + .with_path(path), + ); + } + if unit.mode != Mode::Exec { + issues.push( + error(format!("function unit `{}` must be in exec mode", unit.id)) + .with_path(path), + ); + } + } + _ => { + if unit.function.is_some() { + issues.push( + error(format!("non-function unit `{}` owns a function", unit.id)) + .with_path(path), + ); + } + } + } + // Mode source must be the unit itself or an ancestor. + let mut cursor = Some(index); + let mut found = false; + let mut guard = 0usize; + while let Some(current) = cursor { + guard += 1; + if guard > module.units.len() + 1 { + issues.push(error("unit parent chain contains a cycle").with_path(path)); + break; + } + if module.units[current].id == unit.mode_source_unit_id { + found = true; + break; + } + cursor = module.units[current] + .parent_id + .as_ref() + .and_then(|parent| unit_index.get(parent.as_str()).copied()); + } + if !found { + issues.push( + error(format!( + "unit `{}` mode source is not itself or an ancestor", + unit.id + )) + .with_path(path), + ); + } +} + +fn validate_units_are_ordered( + module: &Module, + source: &[u8], + issues: &mut Vec, + path: &str, +) { + let mut last_start = 0u64; + for (index, unit) in module.units.iter().enumerate() { + let start = unit + .heading_span + .map(|span| span.start) + .unwrap_or(unit.span.start); + if index > 0 && start < last_start { + issues.push(error("units are not in document order").with_path(path)); + break; + } + last_start = start; + if !unit.span.on_utf8_boundaries(source) { + break; + } + } +} + +fn validate_functions( + module: &Module, + unit_index: &HashMap<&str, usize>, + source: &[u8], + issues: &mut Vec, + path: &str, +) { + let mut function_ids = HashSet::new(); + let mut unit_functions: HashMap<&str, &str> = HashMap::new(); + for function in &module.functions { + if !function_ids.insert(function.id.as_str()) { + issues.push(error(format!("duplicate function id `{}`", function.id)).with_path(path)); + } + let Some(unit_index_value) = unit_index.get(function.unit_id.as_str()) else { + issues.push( + error(format!("function `{}` names an unknown unit", function.id)).with_path(path), + ); + continue; + }; + let unit = &module.units[*unit_index_value]; + if unit.kind != UnitKindA::Function + || unit.function.as_deref() != Some(function.id.as_str()) + { + issues.push( + error(format!( + "function `{}` is not the function of its unit", + function.id + )) + .with_path(path), + ); + } + if unit_functions + .insert(unit.id.as_str(), function.id.as_str()) + .is_some() + { + issues.push(error(format!("unit `{}` has several functions", unit.id)).with_path(path)); + } + if !unit.span.contains(function.span) || !function.span.contains(function.heading_span) { + issues.push( + error(format!( + "function `{}` span is not inside its unit section", + function.id + )) + .with_path(path), + ); + } + if Some(function.heading_span) != unit.heading_span { + issues.push( + error(format!( + "function `{}` heading span differs from its unit heading", + function.id + )) + .with_path(path), + ); + } + check_span(function.span, source, path, "function", issues); + check_span( + function.heading_span, + source, + path, + "function heading", + issues, + ); + if function.effects.len() != 1 || function.effects[0] != "unknown" { + issues.push( + error(format!( + "function `{}` effects must be the conservative [\"unknown\"]", + function.id + )) + .with_path(path), + ); + } + let mut params = HashSet::new(); + for param in &function.signature.params { + check_span(param.span, source, path, "parameter", issues); + if !params.insert(param.name.as_str()) { + issues.push( + error(format!( + "function `{}` has duplicate parameter `{}`", + function.id, param.name + )) + .with_path(path), + ); + } + if let Some(default) = ¶m.default { + if let Err(message) = validate_expression(default, source, 0) { + issues.push( + error(format!( + "function `{}` parameter `{}` default is invalid: {message}", + function.id, param.name + )) + .with_path(path), + ); + } + } + } + for statement in &function.body { + if let Err(message) = validate_statement(statement, source, 0) { + issues.push( + error(format!( + "function `{}` body is invalid: {message}", + function.id + )) + .with_path(path), + ); + break; + } + } + } + for unit in &module.units { + if unit.kind == UnitKindA::Function && !unit_functions.contains_key(unit.id.as_str()) { + issues.push( + error(format!("function unit `{}` has no function", unit.id)).with_path(path), + ); + } + } +} + +fn validate_references( + module: &Module, + unit_index: &HashMap<&str, usize>, + source: &[u8], + issues: &mut Vec, + path: &str, +) { + let module_id = module.id.as_str(); + for reference in &module.references { + if reference.source != module_id { + issues.push(error("reference source is not this module").with_path(path)); + } + if !unit_index.contains_key(reference.source_unit.as_str()) { + issues.push(error("reference source_unit is unknown").with_path(path)); + } + check_span(reference.span, source, path, "reference", issues); + if reference + .fragment + .as_deref() + .is_some_and(|fragment| fragment.contains('\0')) + { + issues.push(error("reference fragment contains a NUL byte").with_path(path)); + } + if let Some(candidate_path) = &reference.candidate_path { + if crate::document::discovery::validate_relative_path(candidate_path).is_err() { + issues.push( + error("reference candidate_path is not a safe relative path").with_path(path), + ); + } + } + match reference.state { + RefState::Resolved => match reference.target_kind { + Some(TargetKind::Module) => { + if reference.target_module.is_none() { + issues.push( + error("resolved module reference has no target_module").with_path(path), + ); + } + if reference.fragment.as_deref().is_some_and(|f| !f.is_empty()) + && reference.target_unit.is_none() + { + issues.push( + error("resolved fragment reference has no target_unit").with_path(path), + ); + } + } + Some(TargetKind::File) => { + if reference.target_module.is_some() { + issues.push( + error("resolved file reference unexpectedly names a module") + .with_path(path), + ); + } + } + None => issues.push(error("resolved reference has no target_kind").with_path(path)), + }, + RefState::NotLoaded => { + if reference.target_module.is_some() + || reference.target_unit.is_some() + || reference.target_kind.is_some() + { + issues.push( + error("not_loaded reference must not claim a resolved target") + .with_path(path), + ); + } + } + RefState::Ambiguous => { + if reference.target_unit.is_some() || reference.candidates.len() < 2 { + issues.push( + error("ambiguous reference must list two or more candidates and no target") + .with_path(path), + ); + } + } + RefState::Missing | RefState::External | RefState::OutsideScope | RefState::Invalid => { + if reference.target_unit.is_some() { + issues.push( + error("unresolved reference must not have a target unit").with_path(path), + ); + } + } + } + if reference.state != RefState::Resolved && reference.candidates.len() > 64 { + issues.push(error("reference candidate list exceeds 64 entries").with_path(path)); + } + } +} + +fn validate_calls(module: &Module, source: &[u8], issues: &mut Vec, path: &str) { + let functions: HashSet<&str> = module.functions.iter().map(|f| f.id.as_str()).collect(); + for call in &module.calls { + if !functions.contains(call.function.as_str()) { + issues.push(error("call owner is not a function of this module").with_path(path)); + } + check_span(call.span, source, path, "call", issues); + if let Err(message) = validate_callee(&call.callee, source, 0) { + issues.push(error(format!("call callee is invalid: {message}")).with_path(path)); + } + match call.state { + CallState::Function => { + if call.target.as_deref().is_none_or(str::is_empty) + || call.target_kind != Some(CallTargetKind::Function) + { + issues.push(error("function call has no function target").with_path(path)); + } + } + CallState::Builtin => { + if call.target.as_deref().is_none_or(str::is_empty) + || call.target_kind != Some(CallTargetKind::Builtin) + { + issues.push(error("builtin call has no builtin target").with_path(path)); + } + } + CallState::Plugin => { + if call.target.as_deref().is_none_or(str::is_empty) + || call.target_kind != Some(CallTargetKind::Plugin) + || call.target_owner.is_none() + { + issues.push(error("plugin call has no plugin target/owner").with_path(path)); + } + if let Some(owner) = &call.target_owner { + if !crate::model::is_sha256_prefixed(&owner.digest) || owner.package.is_empty() + { + issues + .push(error("plugin target_owner identity is invalid").with_path(path)); + } + } + } + CallState::Unresolved => { + if call.target.is_some() + || call.target_kind.is_some() + || call.target_owner.is_some() + { + issues.push(error("unresolved call must not claim a target").with_path(path)); + } + if call.reason.is_none() { + issues.push( + error("unresolved call must state a dynamic/unbound reason") + .with_path(path), + ); + } + } + } + } +} + +fn validate_resources( + module: &Module, + unit_index: &HashMap<&str, usize>, + source: &[u8], + issues: &mut Vec, + path: &str, +) { + let mut ids = HashSet::new(); + for resource in &module.resources { + if !ids.insert(resource.id.as_str()) { + issues.push(error(format!("duplicate resource id `{}`", resource.id)).with_path(path)); + } + if !resource.id.starts_with(&format!("{}#resource:", module.id)) { + issues.push( + error(format!("resource id `{}` is not module-local", resource.id)).with_path(path), + ); + } + if resource.module_id != module.id { + issues.push(error("resource module_id is not this module").with_path(path)); + } + if !unit_index.contains_key(resource.unit_id.as_str()) { + issues.push(error("resource unit_id is unknown").with_path(path)); + } + check_span(resource.span, source, path, "resource", issues); + if !crate::model::is_sha256_hex(&resource.content_digest) { + issues.push(error("resource content_digest must be 64 lowercase hex").with_path(path)); + } + match resource.kind { + ResourceKind::Formula => { + if resource.language.is_some() || resource.display.is_none() { + issues.push( + error("formula resource must have display and no language").with_path(path), + ); + } + } + ResourceKind::Code => { + if resource.display.is_some() { + issues.push(error("code resource must not have display").with_path(path)); + } + } + } + } +} + +fn validate_artifact_diagnostics( + artifact: &Artifact, + module_ids: &HashSet<&str>, + issues: &mut Vec, +) { + for diagnostic in &artifact.diagnostics { + if diagnostic.severity == Severity::Error { + issues.push( + error(format!( + "successful Analysis must not contain error diagnostics (found `{}`)", + diagnostic.code + )) + .with_path(&diagnostic.relative_path), + ); + } + if diagnostic.message.trim().is_empty() { + issues.push( + error("Analysis diagnostic message is empty").with_path(&diagnostic.relative_path), + ); + } + if !module_ids.contains(diagnostic.module.as_str()) { + issues.push( + error("Analysis diagnostic names an unknown module") + .with_path(&diagnostic.relative_path), + ); + } + if let Some(span) = diagnostic.span { + if let Some(module) = artifact + .modules + .iter() + .find(|module| module.id == diagnostic.module) + { + if !span.on_utf8_boundaries(module.source.as_bytes()) { + issues.push( + error("Analysis diagnostic span is invalid") + .with_path(&module.relative_path), + ); + } + } + } + } +} + +// --------------------------------------------------------------------------- +// Expression / statement semantic validation +// --------------------------------------------------------------------------- + +fn span_value(value: &serde_json::Value, source: &[u8], what: &str) -> Result { + let object = value + .as_object() + .ok_or_else(|| format!("{what} span must be an object"))?; + if object.len() != 2 || !object.contains_key("start") || !object.contains_key("end") { + return Err(format!("{what} span must contain exactly start and end")); + } + let start = object["start"] + .as_u64() + .ok_or_else(|| format!("{what} span start must be a non-negative integer"))?; + let end = object["end"] + .as_u64() + .ok_or_else(|| format!("{what} span end must be a non-negative integer"))?; + let span = Span::new(start, end); + if !span.on_utf8_boundaries(source) { + return Err(format!("{what} span {span} is outside the source")); + } + Ok(span) +} + +fn require_keys(value: &serde_json::Value, allowed: &[&str], what: &str) -> Result<(), String> { + let object = value + .as_object() + .ok_or_else(|| format!("{what} must be an object"))?; + for key in object.keys() { + if !allowed.contains(&key.as_str()) { + return Err(format!("{what} has unknown attribute `{key}`")); + } + } + for key in allowed { + if !object.contains_key(*key) { + return Err(format!("{what} is missing required attribute `{key}`")); + } + } + Ok(()) +} + +fn validate_statement( + value: &serde_json::Value, + source: &[u8], + depth: usize, +) -> Result<(), String> { + if depth > MAX_EXPRESSION_DEPTH { + return Err("statement nesting exceeds the depth budget".to_string()); + } + let object = value + .as_object() + .ok_or_else(|| "statement must be an object".to_string())?; + let kind = object + .get("kind") + .and_then(|kind| kind.as_str()) + .ok_or_else(|| "statement kind is missing".to_string())?; + match kind { + "assign" => { + require_keys( + value, + &["kind", "target", "value", "span"], + "assign statement", + )?; + span_value(&object["span"], source, "assign statement")?; + validate_place(&object["target"], source, depth)?; + validate_expression(&object["value"], source, depth)?; + } + "expression" => { + require_keys(value, &["kind", "value", "span"], "expression statement")?; + span_value(&object["span"], source, "expression statement")?; + validate_expression(&object["value"], source, depth)?; + } + "branch" => { + require_keys(value, &["kind", "arms", "span"], "branch statement")?; + span_value(&object["span"], source, "branch statement")?; + let arms = object["arms"] + .as_array() + .ok_or_else(|| "branch arms must be an array".to_string())?; + if arms.is_empty() { + return Err("branch must have at least one arm".to_string()); + } + for arm in arms { + require_keys( + arm, + &["condition", "condition_span", "body", "span"], + "branch arm", + )?; + span_value(&arm["span"], source, "branch arm")?; + validate_expression(&arm["condition"], source, depth + 1)?; + span_value(&arm["condition_span"], source, "branch condition")?; + validate_body(&arm["body"], source, depth + 1)?; + } + } + "loop" => { + require_keys( + value, + &["kind", "condition", "condition_span", "body", "span"], + "loop statement", + )?; + span_value(&object["span"], source, "loop statement")?; + validate_expression(&object["condition"], source, depth)?; + span_value(&object["condition_span"], source, "loop condition")?; + validate_body(&object["body"], source, depth + 1)?; + } + "return" => { + require_keys(value, &["kind", "value", "span"], "return statement")?; + span_value(&object["span"], source, "return statement")?; + validate_expression(&object["value"], source, depth)?; + } + "break" | "continue" => { + require_keys(value, &["kind", "span"], "control statement")?; + span_value(&object["span"], source, "control statement")?; + } + other => return Err(format!("unknown statement kind `{other}`")), + } + Ok(()) +} + +fn validate_body(value: &serde_json::Value, source: &[u8], depth: usize) -> Result<(), String> { + let statements = value + .as_array() + .ok_or_else(|| "statement body must be an array".to_string())?; + for statement in statements { + validate_statement(statement, source, depth + 1)?; + } + Ok(()) +} + +fn validate_place(value: &serde_json::Value, source: &[u8], depth: usize) -> Result<(), String> { + if value.is_string() { + if value.as_str().is_none_or(str::is_empty) { + return Err("assignment target must not be empty".to_string()); + } + return Ok(()); + } + require_keys(value, &["kind", "base", "index", "span"], "index place")?; + let object = value.as_object().expect("checked"); + if object["kind"] != "index" { + return Err("place kind must be `index`".to_string()); + } + span_value(&object["span"], source, "place")?; + validate_expression(&object["base"], source, depth)?; + validate_expression(&object["index"], source, depth) +} + +fn validate_expression( + value: &serde_json::Value, + source: &[u8], + depth: usize, +) -> Result<(), String> { + if depth > MAX_EXPRESSION_DEPTH { + return Err("expression nesting exceeds the depth budget".to_string()); + } + let object = value + .as_object() + .ok_or_else(|| "expression must be an object".to_string())?; + let kind = object + .get("kind") + .and_then(|kind| kind.as_str()) + .ok_or_else(|| "expression kind is missing".to_string())?; + match kind { + "literal" => { + require_keys( + value, + &["kind", "type", "value", "span"], + "literal expression", + )?; + span_value(&object["span"], source, "literal expression")?; + match object["type"].as_str() { + Some("int") => { + let text = object["value"] + .as_str() + .ok_or_else(|| "int literal value must be a decimal string".to_string())?; + if text.is_empty() + || !text + .strip_prefix('-') + .unwrap_or(text) + .bytes() + .all(|byte| byte.is_ascii_digit()) + { + return Err("int literal value must be a decimal string".to_string()); + } + } + Some("float") => { + let number = object["value"] + .as_f64() + .ok_or_else(|| "float literal value must be a finite number".to_string())?; + if !number.is_finite() { + return Err("float literal must be finite".to_string()); + } + } + Some("text") => { + if !object["value"].is_string() { + return Err("text literal value must be a string".to_string()); + } + } + Some("bool") => { + if !object["value"].is_boolean() { + return Err("bool literal value must be a boolean".to_string()); + } + } + Some("none") => { + if !object["value"].is_null() { + return Err("none literal value must be null".to_string()); + } + } + Some(other) => return Err(format!("unknown literal type `{other}`")), + None => return Err("literal type is missing".to_string()), + } + } + "variable" => { + require_keys(value, &["kind", "name", "span"], "variable expression")?; + span_value(&object["span"], source, "variable expression")?; + if object["name"].as_str().is_none_or(str::is_empty) { + return Err("variable name must not be empty".to_string()); + } + } + "list" => { + require_keys(value, &["kind", "items", "span"], "list expression")?; + span_value(&object["span"], source, "list expression")?; + for item in object["items"] + .as_array() + .ok_or_else(|| "list items must be an array".to_string())? + { + validate_expression(item, source, depth + 1)?; + } + } + "record" => { + require_keys(value, &["kind", "entries", "span"], "record expression")?; + span_value(&object["span"], source, "record expression")?; + for entry in object["entries"] + .as_array() + .ok_or_else(|| "record entries must be an array".to_string())? + { + require_keys(entry, &["key", "key_span", "value"], "record entry")?; + if entry["key"].as_str().is_none_or(str::is_empty) { + return Err("record key must not be empty".to_string()); + } + span_value(&entry["key_span"], source, "record key")?; + validate_expression(&entry["value"], source, depth + 1)?; + } + } + "unary" => { + require_keys( + value, + &["kind", "op", "operand", "span"], + "unary expression", + )?; + span_value(&object["span"], source, "unary expression")?; + match object["op"].as_str() { + Some("not" | "neg" | "pos") => {} + _ => return Err("unknown unary operator".to_string()), + } + validate_expression(&object["operand"], source, depth + 1)?; + } + "binary" => { + require_keys( + value, + &["kind", "op", "left", "right", "span"], + "binary expression", + )?; + span_value(&object["span"], source, "binary expression")?; + const OPS: [&str; 15] = [ + "or", + "and", + "eq", + "ne", + "lt", + "le", + "gt", + "ge", + "add", + "sub", + "mul", + "div", + "floor_div", + "mod", + "pow", + ]; + if !object["op"].as_str().is_some_and(|op| OPS.contains(&op)) { + return Err("unknown binary operator".to_string()); + } + validate_expression(&object["left"], source, depth + 1)?; + validate_expression(&object["right"], source, depth + 1)?; + } + "member" => { + require_keys( + value, + &["kind", "base", "field", "span"], + "member expression", + )?; + span_value(&object["span"], source, "member expression")?; + if object["field"].as_str().is_none_or(str::is_empty) { + return Err("member field must not be empty".to_string()); + } + validate_expression(&object["base"], source, depth + 1)?; + } + "index" => { + require_keys( + value, + &["kind", "base", "index", "span"], + "index expression", + )?; + span_value(&object["span"], source, "index expression")?; + validate_expression(&object["base"], source, depth + 1)?; + validate_expression(&object["index"], source, depth + 1)?; + } + "call" => { + require_keys( + value, + &["kind", "callee", "args", "span"], + "call expression", + )?; + span_value(&object["span"], source, "call expression")?; + validate_expression(&object["callee"], source, depth + 1)?; + for argument in object["args"] + .as_array() + .ok_or_else(|| "call args must be an array".to_string())? + { + require_keys(argument, &["name", "value", "span"], "call argument")?; + span_value(&argument["span"], source, "call argument")?; + if let Some(name) = argument["name"].as_str() { + if name.is_empty() { + return Err("argument name must not be empty".to_string()); + } + } else if !argument["name"].is_null() { + return Err("argument name must be a string or null".to_string()); + } + validate_expression(&argument["value"], source, depth + 1)?; + } + } + other => return Err(format!("unknown expression kind `{other}`")), + } + Ok(()) +} + +fn validate_callee(value: &serde_json::Value, source: &[u8], depth: usize) -> Result<(), String> { + if depth > MAX_EXPRESSION_DEPTH { + return Err("callee nesting exceeds the depth budget".to_string()); + } + let object = value + .as_object() + .ok_or_else(|| "callee must be an object".to_string())?; + match object.get("kind").and_then(|kind| kind.as_str()) { + Some("ident") => { + require_keys(value, &["kind", "name"], "identifier callee")?; + if object["name"].as_str().is_none_or(str::is_empty) { + return Err("callee name must not be empty".to_string()); + } + } + Some("member") => { + require_keys(value, &["kind", "base", "field"], "member callee")?; + if object["field"].as_str().is_none_or(str::is_empty) { + return Err("callee field must not be empty".to_string()); + } + validate_callee(&object["base"], source, depth + 1)?; + } + Some("expression") => { + require_keys(value, &["kind", "span"], "expression callee")?; + span_value(&object["span"], source, "expression callee")?; + } + Some(other) => return Err(format!("unknown callee kind `{other}`")), + None => return Err("callee kind is missing".to_string()), + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Conversion into DocumentFacts +// --------------------------------------------------------------------------- + +fn module_to_facts( + artifact: &Artifact, + module: &Module, + context: &ProjectContext, +) -> Result { + let path = module.relative_path.clone(); + let mut problems = DiagnosticSet::new(); + let unit_index: HashMap<&str, usize> = module + .units + .iter() + .enumerate() + .map(|(index, unit)| (unit.id.as_str(), index)) + .collect(); + + // Units and deterministic occurrence indices for duplicate paths. + let mut occurrences: HashMap, u32> = HashMap::new(); + let mut units: Vec = Vec::with_capacity(module.units.len()); + for unit in &module.units { + let occurrence = { + let counter = occurrences.entry(unit.path.clone()).or_insert(0); + let value = *counter; + *counter += 1; + value + }; + units.push(UnitFact { + path: unit.path.clone(), + kind: match unit.kind { + UnitKindA::Root => UnitKind::Root, + UnitKindA::Namespace => UnitKind::Namespace, + UnitKindA::Function => UnitKind::Function, + UnitKindA::Knowledge => UnitKind::Knowledge, + UnitKindA::Section => UnitKind::Section, + }, + name: unit.name.clone(), + level: unit.level, + span: unit.span, + heading_span: unit.heading_span, + parent: unit + .parent_id + .as_ref() + .and_then(|parent| unit_index.get(parent.as_str()).copied()), + function_id: unit.function.clone(), + unit_id: Some(unit.id.clone()), + mode: match unit.mode { + Mode::Exec => "exec".to_string(), + Mode::Knowledge => "knowledge".to_string(), + }, + occurrence, + }); + } + + let anchors: Vec = module + .anchors + .iter() + .filter_map(|anchor| { + unit_index + .get(anchor.unit_id.as_str()) + .map(|unit| AnchorFact { + anchor: anchor.anchor.clone(), + unit: *unit, + }) + }) + .collect(); + + let mut functions = Vec::with_capacity(module.functions.len()); + for function in &module.functions { + let Some(unit) = unit_index.get(function.unit_id.as_str()).copied() else { + problems.push( + Diagnostic::error(code::ANALYSIS_INVALID, "function unit is unknown") + .with_path(&path), + ); + continue; + }; + functions.push(FunctionFact { + function_id: function.id.clone(), + unit, + local_name: function.local_name.clone(), + namespace: function.namespace.clone(), + span: function.span, + heading_span: function.heading_span, + signature: serde_json::to_value(&function.signature).unwrap_or(serde_json::Value::Null), + effects: function.effects.clone(), + body: serde_json::Value::Array(function.body.clone()), + }); + } + + let imports: Vec = module + .imports + .iter() + .map(|import| ImportFact { + alias: import.alias.clone(), + target: import.target.clone(), + span: import.span, + unit: markdown::innermost_unit(&units, import.span), + resolved: import.resolved.clone(), + }) + .collect(); + + let references: Vec = module + .references + .iter() + .map(|reference| ReferenceFact { + url: reference.url.clone(), + span: reference.span, + unit: unit_index + .get(reference.source_unit.as_str()) + .copied() + .unwrap_or_else(|| markdown::innermost_unit(&units, reference.span)), + is_image: false, + title: None, + analysis: Some(AnalysisReferenceFact { + state: edge_state_from_analysis(match reference.state { + RefState::Resolved => "resolved", + RefState::NotLoaded => "not_loaded", + RefState::Missing => "missing", + RefState::Ambiguous => "ambiguous", + RefState::External => "external", + RefState::OutsideScope => "outside_scope", + RefState::Invalid => "invalid", + }) + .unwrap_or(EdgeState::Invalid), + target_kind: reference.target_kind.map(|kind| match kind { + TargetKind::Module => "module".to_string(), + TargetKind::File => "file".to_string(), + }), + target_module: reference.target_module.clone(), + target_unit: reference.target_unit.clone(), + candidate_package_instance_id: reference.candidate_package_instance_id.clone(), + candidate_path: reference.candidate_path.clone(), + fragment: reference.fragment.clone(), + candidates: reference.candidates.clone(), + }), + }) + .collect(); + + let calls: Vec = module + .calls + .iter() + .map(|call| CallFact { + function_id: call.function.clone(), + span: call.span, + callee: call.callee.clone(), + state: match call.state { + CallState::Function => "function", + CallState::Builtin => "builtin", + CallState::Plugin => "plugin", + CallState::Unresolved => "unresolved", + } + .to_string(), + target: call.target.clone(), + target_kind: call.target_kind.map(|kind| { + match kind { + CallTargetKind::Function => "function", + CallTargetKind::Builtin => "builtin", + CallTargetKind::Plugin => "plugin", + } + .to_string() + }), + target_owner: call + .target_owner + .as_ref() + .map(|owner| serde_json::to_value(owner).unwrap_or(serde_json::Value::Null)), + reason: call.reason.map(|reason| { + match reason { + CallReason::Dynamic => "dynamic", + CallReason::Unbound => "unbound", + } + .to_string() + }), + }) + .collect(); + + let resources: Vec = module + .resources + .iter() + .map(|resource| ResourceFact { + id: resource.id.clone(), + kind: match resource.kind { + ResourceKind::Formula => "formula", + ResourceKind::Code => "code", + } + .to_string(), + span: resource.span, + content_digest: resource.content_digest.clone(), + language: resource.language.clone(), + display: resource.display, + unit: unit_index + .get(resource.unit_id.as_str()) + .copied() + .unwrap_or_else(|| markdown::innermost_unit(&units, resource.span)), + }) + .collect(); + + let mut diagnostics = DiagnosticSet::new(); + let blocks = markdown::searchable_blocks(&module.document, &units); + let front_matter = markdown::front_matter_fact(&module.document, &mut diagnostics, &path); + let document_title = document_title(&units, &module.relative_path); + + let stdlib_digest = artifact + .project + .stdlib + .as_ref() + .map(|stdlib| stdlib.digest.clone()); + let analysis = AnalysisFacts { + module_id: module.id.clone(), + package_instance_id: module.package_instance_id.clone(), + context_id: context.context_id.clone(), + entry_module_id: context.entry_module_id.clone(), + root_id: context.root_id.clone(), + identity_kind: context.identity_kind.clone(), + manifest_digest: context.manifest_digest.clone(), + lock_digest: context.lock_digest.clone(), + stdlib_digest, + producer_version: context.producer_version.clone(), + analysis_digest: context.analysis_digest.clone(), + extensions: context.extensions.clone(), + }; + + let mut all = problems; + all.merge(diagnostics); + Ok(DocumentFacts { + rel_path: module.relative_path.clone(), + format: super::DocumentFormat::Marqdo, + source_digest: sha256_prefixed(module.source.as_bytes()), + document_title, + ast: module.document.clone(), + units, + anchors, + functions, + imports, + references, + calls, + resources, + blocks, + front_matter, + analysis: Some(analysis), + diagnostics: all, + }) +} + +fn document_title(units: &[UnitFact], rel_path: &str) -> String { + if let Some(h1) = units + .iter() + .find(|unit| unit.kind == UnitKind::Namespace && !unit.name.is_empty()) + { + return h1.name.clone(); + } + let file = rel_path.rsplit('/').next().unwrap_or(rel_path); + for suffix in [".mq.md", ".md"] { + if let Some(stem) = file.strip_suffix(suffix) { + return stem.to_string(); + } + } + file.to_string() +} + +/// Entry candidates for a snapshot: every discovered `.mq.md`, sorted. +pub fn entry_candidates(files: &[super::SourceFile]) -> Vec { + let mut entries: Vec = files + .iter() + .filter(|file| file.format == super::DocumentFormat::Marqdo) + .map(|file| file.rel_path.clone()) + .collect(); + entries.sort(); + entries +} + +#[cfg(test)] +mod tests { + use super::*; + + const FIXTURE: &str = include_str!("../../tests/fixtures/analysis/mechanics.json"); + + fn valid() -> Artifact { + parse_and_validate(FIXTURE.as_bytes()).expect("committed Analysis fixture must validate") + } + + fn tampered(mut mutate: impl FnMut(&mut serde_json::Value)) -> serde_json::Value { + let mut value: serde_json::Value = serde_json::from_str(FIXTURE).unwrap(); + mutate(&mut value); + value + } + + fn expect_invalid(value: serde_json::Value) -> DiagnosticSet { + let bytes = serde_json::to_vec(&value).unwrap(); + parse_and_validate(&bytes).expect_err("tampered artifact must be rejected") + } + + #[test] + fn committed_fixture_parses_and_validates() { + let artifact = valid(); + assert_eq!(artifact.schema, ANALYSIS_SCHEMA); + assert_eq!(artifact.schema_version, ANALYSIS_REVISION); + assert_eq!(artifact.modules.len(), 1); + assert!(artifact.modules[0] + .functions + .iter() + .any(|function| function.local_name == "计算力")); + assert!(artifact.modules[0] + .references + .iter() + .any(|reference| reference.state == RefState::Resolved)); + } + + #[test] + fn conversion_preserves_upstream_states_and_is_one_node_per_function_unit() { + let artifact = valid(); + let context = ProjectContext::from_artifact(&artifact, "sha256:test"); + let facts = module_to_facts(&artifact, &artifact.modules[0], &context).unwrap(); + assert_eq!(facts.units.len(), 4); + let function_unit = facts + .units + .iter() + .position(|unit| unit.kind == UnitKind::Function) + .unwrap(); + assert_eq!(facts.functions.len(), 1); + assert_eq!(facts.functions[0].unit, function_unit); + assert!(facts.units[function_unit].function_id.is_some()); + assert!(facts + .references + .iter() + .all(|reference| reference.analysis.is_some())); + } + + #[test] + fn wrong_schema_revision_is_rejected() { + let problems = expect_invalid(tampered(|value| { + value["schema_version"] = serde_json::json!(2); + })); + assert!(problems + .iter() + .any(|diagnostic| diagnostic.code == code::ANALYSIS_UNSUPPORTED)); + } + + #[test] + fn source_digest_mismatch_is_rejected() { + let problems = expect_invalid(tampered(|value| { + value["modules"][0]["source_digest"] = serde_json::json!("0".repeat(64)); + })); + assert!(problems + .iter() + .any(|diagnostic| diagnostic.message.contains("source_digest does not match"))); + } + + #[test] + fn span_outside_source_is_rejected() { + let problems = expect_invalid(tampered(|value| { + value["modules"][0]["units"][1]["span"]["end"] = serde_json::json!(999_999); + })); + assert!(problems + .iter() + .any(|diagnostic| diagnostic.message.contains("outside the source"))); + } + + #[test] + fn missing_required_field_is_rejected() { + let problems = expect_invalid(tampered(|value| { + value["modules"][0] + .as_object_mut() + .unwrap() + .remove("anchors"); + })); + assert!(problems + .iter() + .any(|diagnostic| diagnostic.code == code::ANALYSIS_INVALID)); + } + + #[test] + fn unknown_field_is_rejected() { + let problems = expect_invalid(tampered(|value| { + value["modules"][0]["surprise"] = serde_json::json!(true); + })); + assert!(problems + .iter() + .any(|diagnostic| diagnostic.code == code::ANALYSIS_INVALID)); + } + + #[test] + fn error_diagnostics_are_rejected() { + let problems = expect_invalid(tampered(|value| { + value["diagnostics"] = serde_json::json!([{ + "module": "root:demo@0.1.0::physics/mechanics.mq.md", + "relative_path": "physics/mechanics.mq.md", + "span": {"start": 0, "end": 1}, + "line": 1, + "column": 1, + "severity": "error", + "code": "sem.bad", + "message": "bad", + "hints": [] + }]); + })); + assert!(problems.iter().any(|diagnostic| diagnostic + .message + .contains("must not contain error diagnostics"))); + } + + #[test] + fn resolved_reference_without_target_is_rejected() { + let problems = expect_invalid(tampered(|value| { + value["modules"][0]["references"][0]["target_unit"] = serde_json::json!(null); + })); + assert!(problems + .iter() + .any(|diagnostic| diagnostic.message.contains("target_unit"))); + } + + #[test] + fn duplicate_module_identity_is_rejected() { + let problems = expect_invalid(tampered(|value| { + let module = value["modules"][0].clone(); + value["modules"] = serde_json::json!([module.clone(), module]); + })); + assert!(problems + .iter() + .any(|diagnostic| diagnostic.message.contains("duplicate module id"))); + } + + #[test] + fn expression_validation_rejects_unknown_kinds_and_bad_spans() { + let source = b"x"; + let bad_kind = serde_json::json!({ + "kind": "magic", "span": {"start": 0, "end": 1} + }); + assert!(validate_expression(&bad_kind, source, 0).is_err()); + let bad_span = serde_json::json!({ + "kind": "variable", "name": "x", "span": {"start": 1, "end": 9} + }); + assert!(validate_expression(&bad_span, source, 0).is_err()); + let good = serde_json::json!({ + "kind": "binary", "op": "add", + "left": {"kind": "literal", "type": "int", "value": "1", "span": {"start": 0, "end": 1}}, + "right": {"kind": "variable", "name": "x", "span": {"start": 0, "end": 1}}, + "span": {"start": 0, "end": 1} + }); + assert!(validate_expression(&good, source, 0).is_ok()); + } + + #[test] + fn entry_candidates_are_sorted_and_marqdo_only() { + use crate::document::{DocumentFormat, SourceFile}; + let files = vec![ + SourceFile { + rel_path: "b.mq.md".into(), + abs_path: "b".into(), + format: DocumentFormat::Marqdo, + text: String::new(), + digest: "sha256:x".into(), + }, + SourceFile { + rel_path: "a.md".into(), + abs_path: "a".into(), + format: DocumentFormat::PlainMarkdown, + text: String::new(), + digest: "sha256:y".into(), + }, + SourceFile { + rel_path: "a.mq.md".into(), + abs_path: "c".into(), + format: DocumentFormat::Marqdo, + text: String::new(), + digest: "sha256:z".into(), + }, + ]; + assert_eq!(entry_candidates(&files), vec!["a.mq.md", "b.mq.md"]); + } +} diff --git a/src/document/core_cli.rs b/src/document/core_cli.rs new file mode 100644 index 0000000..bd2c86e --- /dev/null +++ b/src/document/core_cli.rs @@ -0,0 +1,392 @@ +//! Process boundary for the core Marqdo CLI. +//! +//! The tool never executes knowledge. It invokes one explicit static command: +//! +//! ```text +//! "$MARQDO_BIN" check ENTRY --emit ARTIFACT +//! ``` +//! +//! Rules: argv only (no shell), explicit binary path (never a `PATH` guess), +//! bounded timeout, private unique output path, exit code and fresh artifact +//! verification, bounded captured output, machine absolute paths sanitised out +//! of diagnostics, and no implicit network/install/lock mutation. + +use crate::diagnostic::code; +use crate::error::KnowledgeError; +use crate::model::{sha256_prefixed, Span}; +use std::fs::File; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +/// Current tool API revision this binary implements. +pub const API_REVISION: &str = "1"; +/// Wall-clock budget for one static Analysis invocation. +pub const ANALYSIS_TIMEOUT: Duration = Duration::from_secs(120); +/// Version probe budget. +const VERSION_TIMEOUT: Duration = Duration::from_secs(10); +/// Maximum capture size for a child's stderr/stdout. +const OUTPUT_CAPTURE_LIMIT: u64 = 64 * 1024; +/// Maximum accepted Analysis artifact size. +pub const ARTIFACT_LIMIT: u64 = 256 * 1024 * 1024; +/// Maximum core binary size accepted for identity hashing. +const BINARY_LIMIT: u64 = 512 * 1024 * 1024; + +/// Verified identity of the core CLI. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CoreIdentity { + pub version: String, + /// `sha256:` + lowercase hex of the exact binary bytes. + pub binary_digest: String, + pub api_revision: Option, +} + +impl CoreIdentity { + /// Deterministic identity string used in build metadata. + pub fn describe(&self) -> String { + format!("marqdo@{}/{}", self.version, self.binary_digest) + } +} + +#[derive(Debug, Clone)] +pub struct CoreCli { + pub path: PathBuf, + pub identity: CoreIdentity, +} + +/// The exact bytes emitted by one `check --emit` invocation. +#[derive(Debug, Clone)] +pub struct AnalysisBytes { + pub bytes: Vec, + /// Diagnostic text from the child, already sanitised and bounded. + pub stderr: String, +} + +impl CoreCli { + /// Locate and verify the core CLI. Never scans `PATH`. + pub fn locate(explicit: Option<&Path>) -> Result { + let api_revision = std::env::var("MARQDO_API_REVISION").ok(); + if let Some(revision) = &api_revision { + if revision != API_REVISION { + return Err(KnowledgeError::environment( + code::ANALYSIS_UNSUPPORTED, + format!( + "tool API revision {revision} is not supported; this build requires revision {API_REVISION}" + ), + ) + .with_hint("launch this tool through `marqdo knowledge` with a matching core CLI")); + } + } + let explicit_path = explicit.map(Path::to_path_buf); + let env_path = std::env::var_os("MARQDO_BIN").map(PathBuf::from); + let candidate = match (explicit_path, env_path) { + (Some(path), _) => Some(path), + (None, Some(path)) => Some(path), + (None, None) => None, + }; + let Some(candidate) = candidate else { + if api_revision.is_some() { + return Err(KnowledgeError::environment( + code::CORE_CLI_MISSING, + "MARQDO_BIN is not set; the core CLI path is unknown", + )); + } + return Err(KnowledgeError::environment( + code::NOT_LAUNCHED_BY_MARQDO, + "core CLI path is unknown", + ) + .with_hint( + "launch through `marqdo knowledge ...` or pass --marqdo-bin PATH for development", + )); + }; + + let metadata = std::fs::symlink_metadata(&candidate).map_err(|error| { + KnowledgeError::environment( + code::CORE_CLI_MISSING, + format!("core CLI cannot be inspected: {error}"), + ) + })?; + if !metadata.is_file() { + return Err(KnowledgeError::environment( + code::CORE_CLI_MISSING, + "core CLI path is not a regular file", + )); + } + let canonical = std::fs::canonicalize(&candidate).map_err(|error| { + KnowledgeError::environment( + code::CORE_CLI_MISSING, + format!("core CLI cannot be resolved: {error}"), + ) + })?; + if metadata.len() > BINARY_LIMIT { + return Err(KnowledgeError::environment( + code::BUDGET_EXCEEDED, + "core CLI binary exceeds the identity hashing budget", + )); + } + let bytes = std::fs::read(&canonical).map_err(|error| { + KnowledgeError::environment( + code::CORE_CLI_MISSING, + format!("core CLI cannot be read: {error}"), + ) + })?; + let binary_digest = sha256_prefixed(&bytes); + let version = probe_version(&canonical)?; + Ok(Self { + path: canonical, + identity: CoreIdentity { + version, + binary_digest, + api_revision, + }, + }) + } + + /// Run one static Analysis invocation for a root-relative entry. + pub fn emit_analysis( + &self, + root: &Path, + entry_rel: &str, + ) -> Result { + crate::document::discovery::validate_relative_path(entry_rel).map_err(|message| { + KnowledgeError::environment( + code::SCOPE_ESCAPE, + format!("entry path is not a safe root-relative path: {message}"), + ) + })?; + if !self.path.is_file() { + return Err(KnowledgeError::environment( + code::CORE_CLI_MISSING, + "core CLI is no longer a regular file", + )); + } + let temp = tempfile::Builder::new() + .prefix("marqdo-knowledge-analysis-") + .tempdir() + .map_err(|error| { + KnowledgeError::environment( + code::IO, + format!("cannot create a private Analysis directory: {error}"), + ) + })?; + let artifact_path = temp.path().join("analysis.json"); + let stdout_path = temp.path().join("stdout.log"); + let stderr_path = temp.path().join("stderr.log"); + let stdout_file = File::create(&stdout_path)?; + let stderr_file = File::create(&stderr_path)?; + + let mut child = Command::new(&self.path) + .arg("check") + .arg(entry_rel) + .arg("--emit") + .arg(&artifact_path) + .current_dir(root) + .stdin(Stdio::null()) + .stdout(Stdio::from(stdout_file)) + .stderr(Stdio::from(stderr_file)) + .spawn() + .map_err(|error| { + KnowledgeError::environment( + code::CORE_CLI_FAILED, + format!("core CLI cannot be started: {error}"), + ) + })?; + + let deadline = Instant::now() + ANALYSIS_TIMEOUT; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) => { + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return Err(KnowledgeError::environment( + code::CORE_CLI_TIMEOUT, + format!( + "core CLI did not finish within {} seconds for `{entry_rel}`", + ANALYSIS_TIMEOUT.as_secs() + ), + )); + } + std::thread::sleep(Duration::from_millis(20)); + } + Err(error) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(KnowledgeError::environment( + code::CORE_CLI_FAILED, + format!("core CLI wait failed: {error}"), + )); + } + } + }; + + let stderr = String::from_utf8_lossy( + &read_bounded(&stderr_path, OUTPUT_CAPTURE_LIMIT).unwrap_or_default(), + ) + .replace(&root.display().to_string(), "."); + let stdout = read_bounded(&stdout_path, OUTPUT_CAPTURE_LIMIT).unwrap_or_default(); + if !status.success() { + let detail = first_lines(&stderr, 8); + let mut message = format!( + "core CLI `check --emit` failed for `{entry_rel}` with exit code {:?}", + status.code() + ); + if !detail.is_empty() { + message.push_str(": "); + message.push_str(&detail); + } + return Err(KnowledgeError::input(code::CORE_CLI_FAILED, message)); + } + let bytes = read_bounded(&artifact_path, ARTIFACT_LIMIT).ok_or_else(|| { + KnowledgeError::input( + code::ANALYSIS_MISSING, + format!("core CLI produced no Analysis artifact for `{entry_rel}`"), + ) + })?; + if bytes.is_empty() { + return Err(KnowledgeError::input( + code::ANALYSIS_MISSING, + format!("core CLI produced an empty Analysis artifact for `{entry_rel}`"), + )); + } + let _ = stdout; + // The temporary directory is removed when `temp` drops (including every + // error path above). + Ok(AnalysisBytes { bytes, stderr }) + } +} + +fn probe_version(binary: &Path) -> Result { + let temp = tempfile::tempdir().map_err(|error| { + KnowledgeError::environment( + code::IO, + format!("cannot create version probe directory: {error}"), + ) + })?; + let stdout_path = temp.path().join("version.log"); + let stderr_path = temp.path().join("version.err"); + let stdout_file = File::create(&stdout_path)?; + let stderr_file = File::create(&stderr_path)?; + let mut child = Command::new(binary) + .arg("--version") + .stdin(Stdio::null()) + .stdout(Stdio::from(stdout_file)) + .stderr(Stdio::from(stderr_file)) + .spawn() + .map_err(|error| { + KnowledgeError::environment( + code::CORE_CLI_FAILED, + format!("core CLI version probe failed to start: {error}"), + ) + })?; + let deadline = Instant::now() + VERSION_TIMEOUT; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) => { + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return Err(KnowledgeError::environment( + code::CORE_CLI_TIMEOUT, + "core CLI version probe timed out", + )); + } + std::thread::sleep(Duration::from_millis(10)); + } + Err(error) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(KnowledgeError::environment( + code::CORE_CLI_FAILED, + format!("core CLI version probe failed: {error}"), + )); + } + } + }; + if !status.success() { + return Err(KnowledgeError::environment( + code::CORE_CLI_FAILED, + "core CLI does not report a version; it is not a compatible marqdo binary", + )); + } + let stdout_bytes = read_bounded(&stdout_path, OUTPUT_CAPTURE_LIMIT).unwrap_or_default(); + let stdout = String::from_utf8_lossy(&stdout_bytes); + let first = stdout.lines().next().unwrap_or("").trim().to_string(); + let mut parts = first.split_whitespace(); + let name = parts.next().unwrap_or(""); + let version = parts.next().unwrap_or(""); + if name != "marqdo" || version.is_empty() { + return Err(KnowledgeError::environment( + code::CORE_CLI_FAILED, + "core CLI version output is not `marqdo `", + )); + } + Ok(version.to_string()) +} + +fn read_bounded(path: &Path, limit: u64) -> Option> { + let metadata = std::fs::metadata(path).ok()?; + if !metadata.is_file() { + return None; + } + let mut file = File::open(path).ok()?; + let mut buffer = Vec::new(); + file.by_ref().take(limit).read_to_end(&mut buffer).ok()?; + Some(buffer) +} + +fn first_lines(text: &str, count: usize) -> String { + let mut out = String::new(); + for line in text.lines().take(count) { + if !out.is_empty() { + out.push_str(" | "); + } + out.push_str(line.trim()); + } + out +} + +/// Helper for validating a span inside a concrete source buffer. +pub fn span_in_source(span: Span, source: &[u8]) -> bool { + span.on_utf8_boundaries(source) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn missing_core_and_missing_env_do_not_scan_path() { + // The test environment may define MARQDO_BIN; only assert the failure + // path when it is absent. + if std::env::var_os("MARQDO_BIN").is_some() { + return; + } + let error = CoreCli::locate(Some(Path::new("/nonexistent/marqdo"))).unwrap_err(); + assert_eq!(error.code, code::CORE_CLI_MISSING); + } + + #[test] + fn entry_paths_are_validated_before_spawning() { + let cli = CoreCli { + path: PathBuf::from("/nonexistent"), + identity: CoreIdentity { + version: "0".into(), + binary_digest: "sha256:0".into(), + api_revision: None, + }, + }; + let error = cli + .emit_analysis(Path::new("/tmp"), "../escape.mq.md") + .unwrap_err(); + assert_eq!(error.code, code::SCOPE_ESCAPE); + } + + #[test] + fn version_output_parsing_requires_marqdo_prefix() { + assert!(first_lines("a\nb\n", 1) == "a"); + } +} diff --git a/src/document/discovery.rs b/src/document/discovery.rs index 5c7770f..959ceb5 100644 --- a/src/document/discovery.rs +++ b/src/document/discovery.rs @@ -120,12 +120,9 @@ pub fn discover(scope: &Scope) -> Result { KnowledgeError::environment(code::SCOPE_ESCAPE, format!("invalid root file: {message}")) })?; let abs = scope.root.join(single); - match read_document(scope, &abs, single, &mut diagnostics)? { - Some(file) => { - total_bytes += file.len(); - files.push(file); - } - None => {} + if let Some(file) = read_document(scope, &abs, single, &mut diagnostics)? { + total_bytes += file.len(); + files.push(file); } } else { walk( diff --git a/src/document/markdown.rs b/src/document/markdown.rs index c2c3256..ad418ba 100644 --- a/src/document/markdown.rs +++ b/src/document/markdown.rs @@ -49,14 +49,14 @@ pub fn parse_plain(file: &SourceFile) -> DocumentFacts { .push(Diagnostic::error(code::MARKDOWN_INVALID, message).with_path(&file.rel_path)); } - let front_matter = extract_front_matter(&ast, &mut diagnostics, &file.rel_path); + let front_matter = front_matter_fact(&ast, &mut diagnostics, &file.rel_path); let mut units = build_units(&ast, file); fix_unit_spans(&mut units, source.len() as u64); let anchors = build_anchors(&units); let title = document_title(&units, &file.rel_path); let references = extract_references(&ast, &units); - let blocks = extract_blocks(&ast, &units); + let blocks = searchable_blocks(&ast, &units); DocumentFacts { rel_path: file.rel_path.clone(), @@ -358,12 +358,12 @@ fn fix_unit_spans(units: &mut [UnitFact], source_len: u64) { .map(|span| span.start) .unwrap_or(units[index].span.start); let mut end = source_len; - for later in index + 1..units.len() { - if units[later].level <= level { - end = units[later] + for later in units.iter().skip(index + 1) { + if later.level <= level { + end = later .heading_span .map(|span| span.start) - .unwrap_or(units[later].span.start); + .unwrap_or(later.span.start); break; } } @@ -446,7 +446,7 @@ fn document_title(units: &[UnitFact], rel_path: &str) -> String { file.to_string() } -fn extract_front_matter( +pub(crate) fn front_matter_fact( ast: &AstNode, diagnostics: &mut DiagnosticSet, rel_path: &str, @@ -631,7 +631,7 @@ fn extract_references(ast: &AstNode, units: &[UnitFact]) -> Vec { references } -fn innermost_unit(units: &[UnitFact], span: Span) -> usize { +pub(crate) fn innermost_unit(units: &[UnitFact], span: Span) -> usize { let mut best = 0usize; let mut best_level = 0u8; for (index, unit) in units.iter().enumerate() { @@ -646,7 +646,7 @@ fn innermost_unit(units: &[UnitFact], span: Span) -> usize { best } -fn extract_blocks(ast: &AstNode, units: &[UnitFact]) -> Vec { +pub(crate) fn searchable_blocks(ast: &AstNode, units: &[UnitFact]) -> Vec { let mut blocks = Vec::new(); for child in &ast.children { if child.kind == AstKind::FrontMatter || child.kind == AstKind::Heading { diff --git a/src/document/mod.rs b/src/document/mod.rs index b06598d..5082fbd 100644 --- a/src/document/mod.rs +++ b/src/document/mod.rs @@ -7,6 +7,7 @@ pub mod analysis; pub mod ast; +pub mod core_cli; pub mod discovery; pub mod markdown; pub mod okf; @@ -530,11 +531,12 @@ impl DocumentFacts { let mut best = 0usize; let mut best_level = 0u8; for (index, unit) in self.units.iter().enumerate() { - if unit.span.contains(span) && (index == 0 || unit.level >= best_level) { - if index == 0 || unit.level >= best_level { - best = index; - best_level = unit.level; - } + if index == 0 { + continue; + } + if unit.span.contains(span) && unit.level >= best_level { + best = index; + best_level = unit.level; } } best diff --git a/src/model.rs b/src/model.rs index 90f364e..f0ffd0d 100644 --- a/src/model.rs +++ b/src/model.rs @@ -41,7 +41,7 @@ impl Span { /// Return the exact source slice when the span is valid and lies on UTF-8 /// boundaries. Never panics on hostile offsets. - pub fn slice<'a>(self, source: &'a [u8]) -> Option<&'a str> { + pub fn slice(self, source: &[u8]) -> Option<&str> { if self.start > self.end || self.end > source.len() as u64 { return None; } diff --git a/tests/core_cli.rs b/tests/core_cli.rs new file mode 100644 index 0000000..e7f2868 --- /dev/null +++ b/tests/core_cli.rs @@ -0,0 +1,98 @@ +//! Integration tests for the core CLI boundary and Analysis adapter. +//! +//! These tests need a real `marqdo` binary. Set `MARQDO_TEST_BIN` to run them; +//! without it they report a skip and do not claim evidence. The repository +//! keeps real captured artefacts under `tests/fixtures/analysis/` for the +//! offline contract tests. + +use marqdo_knowledge::document::analysis; +use marqdo_knowledge::document::core_cli::CoreCli; +use std::path::{Path, PathBuf}; + +fn core_bin() -> Option { + let value = std::env::var_os("MARQDO_TEST_BIN")?; + let path = PathBuf::from(value); + if path.is_file() { + Some(path) + } else { + None + } +} + +fn write_project(root: &Path) { + std::fs::create_dir_all(root.join("physics")).unwrap(); + std::fs::write( + root.join("marqdo.yaml"), + "project:\n name: demo\n version: 0.1.0\n marqdo: \">=3.0.0-beta.1,<4.0.0\"\ndependencies: {}\n", + ) + .unwrap(); + std::fs::write( + root.join("physics/mechanics.mq.md"), + "---\ntype: Theory\ntitle: 经典力学\n---\n\n# 经典力学\n\n## @knowledge 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n\n计算入口:[计算力](#计算力)。\n\n## @exec 计算力\n\n`params(m, a)`\n\n依据[牛顿第二定律](#牛顿第二定律)。\n\n`return m * a`\n", + ) + .unwrap(); + std::fs::write( + root.join("bad.mq.md"), + "# bad\n\n## @exec broken\n\n`return this is not valid ))`\n", + ) + .unwrap(); +} + +#[test] +fn real_core_cli_emits_a_valid_analysis_artifact() { + let Some(bin) = core_bin() else { + eprintln!("skip: MARQDO_TEST_BIN is not set"); + return; + }; + let temp = tempfile::tempdir().unwrap(); + write_project(temp.path()); + let core = CoreCli::locate(Some(&bin)).unwrap(); + assert!(core.identity.version.starts_with('3')); + let emitted = core + .emit_analysis(temp.path(), "physics/mechanics.mq.md") + .unwrap(); + let artifact = analysis::parse_and_validate(&emitted.bytes).unwrap(); + assert_eq!(artifact.schema_version, 3); + assert!(artifact + .modules + .iter() + .any(|module| module.relative_path == "physics/mechanics.mq.md")); + let batch = + analysis::analyze_core(temp.path(), &["physics/mechanics.mq.md".to_string()], &core); + assert!(!batch.diagnostics.has_errors(), "{:?}", batch.diagnostics); + let module = batch + .module_for_path("physics/mechanics.mq.md") + .expect("valid module facts"); + assert!(module + .facts + .functions + .iter() + .any(|function| function.local_name == "计算力")); +} + +#[test] +fn invalid_marqdo_document_fails_analysis_without_an_artifact() { + let Some(bin) = core_bin() else { + eprintln!("skip: MARQDO_TEST_BIN is not set"); + return; + }; + let temp = tempfile::tempdir().unwrap(); + write_project(temp.path()); + let core = CoreCli::locate(Some(&bin)).unwrap(); + let batch = analysis::analyze_core(temp.path(), &["bad.mq.md".to_string()], &core); + assert!(batch.diagnostics.has_errors()); + assert_eq!(batch.modules.len(), 0); + assert_eq!(batch.failed_entries, vec!["bad.mq.md".to_string()]); +} + +#[test] +fn analysis_core_cli_identity_is_recorded() { + let Some(bin) = core_bin() else { + eprintln!("skip: MARQDO_TEST_BIN is not set"); + return; + }; + let core = CoreCli::locate(Some(&bin)).unwrap(); + assert!(core.identity.version.starts_with('3')); + assert!(core.identity.binary_digest.starts_with("sha256:")); + assert_eq!(core.identity.binary_digest.len(), 71); +} diff --git a/tests/fixtures/analysis/README.md b/tests/fixtures/analysis/README.md new file mode 100644 index 0000000..5edc850 --- /dev/null +++ b/tests/fixtures/analysis/README.md @@ -0,0 +1,23 @@ +# Analysis fixture provenance + +`mechanics.json` is a real `marqdo.analysis` revision-3 artefact captured from +the upstream release candidate, not a hand-written example. Tests use it as the +positive fixture for the closed-shape and semantic validator and for the +`DocumentFacts` conversion. + +- Producer: `marqdo 3.0.0-rc.4` (`4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`), + Linux x86_64. +- Command (captured from the project directory): + + ```sh + "$MARQDO_BIN" check physics/mechanics.mq.md --emit analysis.json + ``` + +- Source project: a minimal `marqdo.yaml` plus one document with a namespace, + a Knowledge H2, an Exec H2 with parameters, a Markdown link to an anchor, a + formula, a table and a front matter block. +- Fixture SHA-256: see `mechanics.json.sha256`. +- Regenerate with `scripts/regenerate-analysis-fixture.sh SHA256_OF_CORE_BINARY` + and record the new producer version and binary digest if the contract changes. + A revision that cannot be consumed by the current validator must be treated as + a broken producer/consumer pair, never patched into the tests. diff --git a/tests/fixtures/analysis/mechanics.json b/tests/fixtures/analysis/mechanics.json new file mode 100644 index 0000000..7e9d2b8 --- /dev/null +++ b/tests/fixtures/analysis/mechanics.json @@ -0,0 +1,647 @@ +{ + "schema": "marqdo.analysis", + "schema_version": 3, + "producer": { + "name": "marqdo", + "version": "3.0.0-rc.4", + "markdown_profile": "marqdo.md.v1" + }, + "project": { + "root_id": "root:demo@0.1.0", + "identity_kind": "manifest", + "entry_module_id": "root:demo@0.1.0::physics/mechanics.mq.md", + "lock_digest": "", + "manifest_digest": "sha256:ee4f20fb5156741127f6a4d947b73b9a8f9700a368992974601a958861939a82", + "stdlib": null, + "extensions": [] + }, + "modules": [ + { + "id": "root:demo@0.1.0::physics/mechanics.mq.md", + "package_instance_id": "root:demo@0.1.0", + "relative_path": "physics/mechanics.mq.md", + "source_digest": "27815c2e64ca85343ac4e43213e5c842e458a0dd2ee98e499965fb9da2b37607", + "source": "---\ntype: Theory\ntitle: 经典力学\ntags: [physics, mechanics]\n---\n\n# 经典力学\n\n## @knowledge 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n\n$$\nF = ma\n$$\n\n| 符号 | 含义 |\n| --- | --- |\n| m | 质量 |\n| a | 加速度 |\n\n计算入口:[计算力](#计算力)。\n\n## @exec 计算力\n\n`params(m, a)`\n\n依据[牛顿第二定律](#牛顿第二定律)。\n\n`return m * a`\n", + "document": { + "children": [ + { + "children": [], + "kind": "front_matter", + "literal": "---\ntype: Theory\ntitle: 经典力学\ntags: [physics, mechanics]\n---\n\n", + "span": { + "end": 67, + "start": 0 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "经典力学", + "span": { + "end": 83, + "start": 71 + } + } + ], + "kind": "heading", + "level": 1, + "setext": false, + "span": { + "end": 83, + "start": 69 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@knowledge 牛顿第二定律", + "span": { + "end": 117, + "start": 88 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 117, + "start": 85 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "合外力等于质量与加速度的乘积。", + "span": { + "end": 164, + "start": 119 + } + } + ], + "kind": "paragraph", + "span": { + "end": 164, + "start": 119 + } + }, + { + "children": [], + "kind": "math_block", + "literal": "F = ma\n", + "span": { + "end": 178, + "start": 166 + } + }, + { + "alignments": [ + "none", + "none" + ], + "children": [ + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "符号", + "span": { + "end": 188, + "start": 182 + } + } + ], + "kind": "table_cell", + "span": { + "end": 189, + "start": 181 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "含义", + "span": { + "end": 197, + "start": 191 + } + } + ], + "kind": "table_cell", + "span": { + "end": 198, + "start": 190 + } + } + ], + "header": true, + "kind": "table_row", + "span": { + "end": 199, + "start": 180 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "m", + "span": { + "end": 217, + "start": 216 + } + } + ], + "kind": "table_cell", + "span": { + "end": 218, + "start": 215 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "质量", + "span": { + "end": 226, + "start": 220 + } + } + ], + "kind": "table_cell", + "span": { + "end": 227, + "start": 219 + } + } + ], + "header": false, + "kind": "table_row", + "span": { + "end": 228, + "start": 214 + } + }, + { + "children": [ + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "a", + "span": { + "end": 232, + "start": 231 + } + } + ], + "kind": "table_cell", + "span": { + "end": 233, + "start": 230 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "加速度", + "span": { + "end": 244, + "start": 235 + } + } + ], + "kind": "table_cell", + "span": { + "end": 245, + "start": 234 + } + } + ], + "header": false, + "kind": "table_row", + "span": { + "end": 246, + "start": 229 + } + } + ], + "kind": "table", + "span": { + "end": 246, + "start": 180 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "计算入口:", + "span": { + "end": 263, + "start": 248 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "计算力", + "span": { + "end": 273, + "start": 264 + } + } + ], + "kind": "link", + "span": { + "end": 286, + "start": 263 + }, + "title": "", + "url": "#计算力" + }, + { + "children": [], + "kind": "text", + "literal": "。", + "span": { + "end": 289, + "start": 286 + } + } + ], + "kind": "paragraph", + "span": { + "end": 289, + "start": 248 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "@exec 计算力", + "span": { + "end": 309, + "start": 294 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 309, + "start": 291 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "params(m, a)", + "span": { + "end": 325, + "start": 311 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 325, + "start": 311 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "依据", + "span": { + "end": 333, + "start": 327 + } + }, + { + "children": [ + { + "children": [], + "kind": "text", + "literal": "牛顿第二定律", + "span": { + "end": 352, + "start": 334 + } + } + ], + "kind": "link", + "span": { + "end": 374, + "start": 333 + }, + "title": "", + "url": "#牛顿第二定律" + }, + { + "children": [], + "kind": "text", + "literal": "。", + "span": { + "end": 377, + "start": 374 + } + } + ], + "kind": "paragraph", + "span": { + "end": 377, + "start": 327 + } + }, + { + "children": [ + { + "children": [], + "kind": "code", + "literal": "return m * a", + "span": { + "end": 393, + "start": 379 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 393, + "start": 379 + } + } + ], + "kind": "document", + "span": { + "end": 394, + "start": 0 + } + }, + "units": [ + { + "id": "root:demo@0.1.0::physics/mechanics.mq.md#", + "path": [], + "parent_id": null, + "kind": "root", + "name": "", + "level": 0, + "mode": "knowledge", + "mode_origin": "default", + "mode_source_unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#", + "heading_span": null, + "span": { + "start": 0, + "end": 394 + }, + "function": null + }, + { + "id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学", + "path": [ + "经典力学" + ], + "parent_id": "root:demo@0.1.0::physics/mechanics.mq.md#", + "kind": "namespace", + "name": "经典力学", + "level": 1, + "mode": "knowledge", + "mode_origin": "inherited", + "mode_source_unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#", + "heading_span": { + "start": 69, + "end": 83 + }, + "span": { + "start": 69, + "end": 394 + }, + "function": null + }, + { + "id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律", + "path": [ + "经典力学", + "牛顿第二定律" + ], + "parent_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学", + "kind": "knowledge", + "name": "牛顿第二定律", + "level": 2, + "mode": "knowledge", + "mode_origin": "explicit", + "mode_source_unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律", + "heading_span": { + "start": 85, + "end": 117 + }, + "span": { + "start": 85, + "end": 291 + }, + "function": null + }, + { + "id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力", + "path": [ + "经典力学", + "计算力" + ], + "parent_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学", + "kind": "function", + "name": "计算力", + "level": 2, + "mode": "exec", + "mode_origin": "explicit", + "mode_source_unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力", + "heading_span": { + "start": 291, + "end": 309 + }, + "span": { + "start": 291, + "end": 394 + }, + "function": "root:demo@0.1.0::physics/mechanics.mq.md::经典力学.计算力" + } + ], + "anchors": [ + { + "anchor": "牛顿第二定律", + "unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律" + }, + { + "anchor": "经典力学", + "unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学" + }, + { + "anchor": "计算力", + "unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力" + } + ], + "functions": [ + { + "id": "root:demo@0.1.0::physics/mechanics.mq.md::经典力学.计算力", + "unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力", + "local_name": "计算力", + "namespace": "经典力学", + "span": { + "start": 291, + "end": 393 + }, + "heading_span": { + "start": 291, + "end": 309 + }, + "signature": { + "kind": "explicit", + "params": [ + { + "name": "m", + "required": true, + "type": null, + "default": null, + "span": { + "start": 315, + "end": 316 + } + }, + { + "name": "a", + "required": true, + "type": null, + "default": null, + "span": { + "start": 320, + "end": 322 + } + } + ] + }, + "effects": [ + "unknown" + ], + "body": [ + { + "kind": "return", + "span": { + "end": 393, + "start": 379 + }, + "value": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "m", + "span": { + "end": 388, + "start": 387 + } + }, + "op": "mul", + "right": { + "kind": "variable", + "name": "a", + "span": { + "end": 392, + "start": 391 + } + }, + "span": { + "end": 392, + "start": 387 + } + } + } + ] + } + ], + "imports": [], + "references": [ + { + "source": "root:demo@0.1.0::physics/mechanics.mq.md", + "source_unit": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律", + "url": "#计算力", + "span": { + "start": 263, + "end": 286 + }, + "state": "resolved", + "target_kind": "module", + "target_module": "root:demo@0.1.0::physics/mechanics.mq.md", + "target_unit": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力", + "candidate_package_instance_id": null, + "candidate_path": null, + "fragment": "计算力", + "candidates": [] + }, + { + "source": "root:demo@0.1.0::physics/mechanics.mq.md", + "source_unit": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力", + "url": "#牛顿第二定律", + "span": { + "start": 333, + "end": 374 + }, + "state": "resolved", + "target_kind": "module", + "target_module": "root:demo@0.1.0::physics/mechanics.mq.md", + "target_unit": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律", + "candidate_package_instance_id": null, + "candidate_path": null, + "fragment": "牛顿第二定律", + "candidates": [] + } + ], + "calls": [], + "resources": [ + { + "id": "root:demo@0.1.0::physics/mechanics.mq.md#resource:formula-1", + "module_id": "root:demo@0.1.0::physics/mechanics.mq.md", + "unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律", + "kind": "formula", + "span": { + "start": 166, + "end": 178 + }, + "content_digest": "377d9d34e57777c470a2b3e3ddea6839c9d257cafab6df1640b4d9598d840df6", + "language": null, + "display": true + } + ] + } + ], + "diagnostics": [] +} \ No newline at end of file diff --git a/tests/fixtures/analysis/mechanics.json.sha256 b/tests/fixtures/analysis/mechanics.json.sha256 new file mode 100644 index 0000000..263c2ec --- /dev/null +++ b/tests/fixtures/analysis/mechanics.json.sha256 @@ -0,0 +1 @@ +37e8049262f119388d7934190814b117a33820782547fd9ea70f988818ea9577 tests/fixtures/analysis/mechanics.json