feat(graph): unified node/edge graph with exact reference resolution
- add one Node/one Edge model over canonical JSON-tuple keys; root units map to their document node and Exec unit/function nodes are the same node - build contains tree, statement and resource nodes, asset nodes and inert external nodes; keep every repeated link occurrence as its own edge - resolve ordinary links relative to the source document with exactly one percent decode, fragment rules, numbered anchors, exact canonical-name fallback and explicit missing/ambiguous/not_loaded/out_of_scope/invalid states - never re-bind a resolved upstream Marqdo target; preserve not_loaded and resolve it in root scope only through exact anchor/name rules; surface interface conflicts when upstream and knowledge mappings disagree - map imports and calls to real nodes or explicit external/unresolved edges; builtin/plugin targets stay external symbols, never fabricated functions - add deterministic logical digest and tests for contains, externals, repeated occurrences, ambiguity, anchors and missing-path distinctions
This commit is contained in:
1 parent
59d5afe10b
commit
1871ded5ed
5 files changed
+1999
-1
No files matched your search
+2
-1
@@ -13,7 +13,8 @@ pub mod markdown;
|
|||||||
pub mod okf;
|
pub mod okf;
|
||||||
|
|
||||||
use crate::diagnostic::DiagnosticSet;
|
use crate::diagnostic::DiagnosticSet;
|
||||||
use crate::model::{DocumentFormat, Span};
|
pub use crate::model::DocumentFormat;
|
||||||
|
use crate::model::Span;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
//! Canonical identity for nodes, aliases and edges.
|
||||||
|
//!
|
||||||
|
//! Every key is a structured tuple encoded by [`NodeKey`]. No key is formed by
|
||||||
|
//! concatenating raw `#`, `::` or `/`. Unit keys carry an explicit occurrence
|
||||||
|
//! index before the path segments, so a path segment that looks like an index
|
||||||
|
//! can never collide with the index itself.
|
||||||
|
|
||||||
|
use crate::model::NodeKey;
|
||||||
|
|
||||||
|
pub fn document_key(rel_path: &str) -> NodeKey {
|
||||||
|
NodeKey::from_parts(&["document", rel_path])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Key for a non-root unit. The root unit is the document node.
|
||||||
|
pub fn unit_key(rel_path: &str, occurrence: u32, path: &[String]) -> NodeKey {
|
||||||
|
let mut parts: Vec<&str> = Vec::with_capacity(path.len() + 3);
|
||||||
|
parts.push("unit");
|
||||||
|
parts.push(rel_path);
|
||||||
|
let occurrence = occurrence.to_string();
|
||||||
|
parts.push(&occurrence);
|
||||||
|
for segment in path {
|
||||||
|
parts.push(segment.as_str());
|
||||||
|
}
|
||||||
|
NodeKey::from_parts(&parts)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn statement_key(
|
||||||
|
rel_path: &str,
|
||||||
|
occurrence: u32,
|
||||||
|
unit_path: &[String],
|
||||||
|
ordinal: usize,
|
||||||
|
span_start: u64,
|
||||||
|
) -> NodeKey {
|
||||||
|
let occurrence = occurrence.to_string();
|
||||||
|
let ordinal = ordinal.to_string();
|
||||||
|
let span_start = span_start.to_string();
|
||||||
|
let mut parts: Vec<&str> = Vec::with_capacity(unit_path.len() + 6);
|
||||||
|
parts.push("statement");
|
||||||
|
parts.push(rel_path);
|
||||||
|
parts.push(&occurrence);
|
||||||
|
for segment in unit_path {
|
||||||
|
parts.push(segment.as_str());
|
||||||
|
}
|
||||||
|
parts.push(&ordinal);
|
||||||
|
parts.push(&span_start);
|
||||||
|
NodeKey::from_parts(&parts)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resource_key(rel_path: &str, resource_id: &str) -> NodeKey {
|
||||||
|
NodeKey::from_parts(&["resource", rel_path, resource_id])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn asset_key(rel_path: &str) -> NodeKey {
|
||||||
|
NodeKey::from_parts(&["asset", rel_path])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn external_url_key(url: &str) -> NodeKey {
|
||||||
|
NodeKey::from_parts(&["external", "url", url])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn external_module_key(module_id: &str) -> NodeKey {
|
||||||
|
NodeKey::from_parts(&["external", "module", module_id])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn external_unit_key(unit_id: &str) -> NodeKey {
|
||||||
|
NodeKey::from_parts(&["external", "unit", unit_id])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn external_function_key(function_id: &str) -> NodeKey {
|
||||||
|
NodeKey::from_parts(&["external", "function", function_id])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn external_symbol_key(kind: &str, name: &str) -> NodeKey {
|
||||||
|
NodeKey::from_parts(&["external", "symbol", kind, name])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn external_file_key(rel_path: &str) -> NodeKey {
|
||||||
|
NodeKey::from_parts(&["external", "file", rel_path])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Edge deduplication key: one row per occurrence, including its source span.
|
||||||
|
pub fn edge_key(
|
||||||
|
source: &str,
|
||||||
|
kind: &str,
|
||||||
|
target: Option<&str>,
|
||||||
|
raw_target: &str,
|
||||||
|
span: Option<(u64, u64)>,
|
||||||
|
) -> String {
|
||||||
|
let (start, end) = span.unwrap_or((0, 0));
|
||||||
|
format!(
|
||||||
|
"{source}\u{1f}{kind}\u{1f}{}\u{1f}{raw_target}\u{1f}{start}\u{1f}{end}",
|
||||||
|
target.unwrap_or("")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unit_keys_with_index_like_segments_do_not_collide() {
|
||||||
|
let a = unit_key("a.md", 0, &["occ:1".to_string()]);
|
||||||
|
let b = unit_key("a.md", 1, &[]);
|
||||||
|
assert_ne!(a, b);
|
||||||
|
let c = unit_key("a.md", 0, &["x".to_string()]);
|
||||||
|
let d = unit_key("a.md", 1, &["x".to_string()]);
|
||||||
|
assert_ne!(c, d);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keys_round_trip_as_opaque_ids() {
|
||||||
|
let key = unit_key("dir/doc.md", 2, &["力学".to_string(), "计算力".to_string()]);
|
||||||
|
assert_eq!(NodeKey::from_encoded(key.as_str()).as_ref(), Some(&key));
|
||||||
|
assert!(!key.as_str().contains('#'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn edge_keys_include_every_occurrence() {
|
||||||
|
let first = edge_key("s", "references", Some("t"), "u", Some((1, 2)));
|
||||||
|
let second = edge_key("s", "references", Some("t"), "u", Some((3, 4)));
|
||||||
|
assert_ne!(first, second);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,789 @@
|
|||||||
|
//! The single knowledge graph: one Node type, one Edge type and the linking
|
||||||
|
//! pipeline from document facts to graph facts.
|
||||||
|
//!
|
||||||
|
//! Invariants:
|
||||||
|
//! * every node has one canonical key and one node kind;
|
||||||
|
//! * `contains` forms a single-parent tree (documents are roots);
|
||||||
|
//! * unresolved edges keep their raw target and an explicit state;
|
||||||
|
//! * repeated link occurrences are separate edges, never merged;
|
||||||
|
//! * external targets are inert nodes and are never fetched;
|
||||||
|
//! * the graph layer performs no I/O and no program parsing.
|
||||||
|
|
||||||
|
pub mod identity;
|
||||||
|
pub mod resolve;
|
||||||
|
|
||||||
|
use crate::diagnostic::{code, Diagnostic, DiagnosticSet};
|
||||||
|
use crate::document::{AssetFile, DocumentFacts};
|
||||||
|
use crate::model::{sha256_prefixed, EdgeKind, EdgeOrigin, EdgeState, NodeKey, NodeKind, Span};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::{BTreeMap, HashMap};
|
||||||
|
|
||||||
|
/// One knowledge node.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Node {
|
||||||
|
pub key: NodeKey,
|
||||||
|
pub kind: NodeKind,
|
||||||
|
/// Root-relative document path; the asset path for asset nodes; empty for
|
||||||
|
/// external nodes.
|
||||||
|
pub doc_path: String,
|
||||||
|
pub parent: Option<NodeKey>,
|
||||||
|
pub title: String,
|
||||||
|
pub span: Option<Span>,
|
||||||
|
/// `sha256:` digest of the original source slice (or the title for nodes
|
||||||
|
/// without a source range).
|
||||||
|
pub content_digest: String,
|
||||||
|
/// Normalised, position-free semantic digest (functions only for now).
|
||||||
|
pub semantic_digest: Option<String>,
|
||||||
|
pub metadata: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Node {
|
||||||
|
pub fn is_searchable(&self) -> bool {
|
||||||
|
!matches!(self.kind, NodeKind::External)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One graph edge occurrence.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Edge {
|
||||||
|
pub source: NodeKey,
|
||||||
|
pub target: Option<NodeKey>,
|
||||||
|
pub kind: EdgeKind,
|
||||||
|
pub origin: EdgeOrigin,
|
||||||
|
pub raw_target: String,
|
||||||
|
pub span: Option<Span>,
|
||||||
|
pub doc_path: String,
|
||||||
|
pub state: EdgeState,
|
||||||
|
pub context: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exact alias binding (canonical upstream ids and OKF concept ids). Only
|
||||||
|
/// unambiguous bindings are stored; search-derived aliases are not aliases.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||||
|
pub struct AliasRecord {
|
||||||
|
pub alias: String,
|
||||||
|
pub context: Option<String>,
|
||||||
|
pub node: NodeKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Graph {
|
||||||
|
pub facts: Vec<DocumentFacts>,
|
||||||
|
pub assets: Vec<AssetFile>,
|
||||||
|
pub nodes: Vec<Node>,
|
||||||
|
pub edges: Vec<Edge>,
|
||||||
|
pub aliases: Vec<AliasRecord>,
|
||||||
|
pub diagnostics: DiagnosticSet,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Graph {
|
||||||
|
pub fn node_count(&self) -> usize {
|
||||||
|
self.nodes.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn edge_count(&self) -> usize {
|
||||||
|
self.edges.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn document_node(&self, rel_path: &str) -> Option<&Node> {
|
||||||
|
let key = identity::document_key(rel_path);
|
||||||
|
self.nodes.iter().find(|node| node.key == key)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deterministic logical digest of the graph content: node keys/kinds/
|
||||||
|
/// titles/digests and edge identities, sorted. Excludes SQLite rowids and
|
||||||
|
/// page order.
|
||||||
|
pub fn logical_digest(&self) -> String {
|
||||||
|
let mut buffer = String::new();
|
||||||
|
for node in &self.nodes {
|
||||||
|
buffer.push_str("n\t");
|
||||||
|
buffer.push_str(node.key.as_str());
|
||||||
|
buffer.push('\t');
|
||||||
|
buffer.push_str(node.kind.as_str());
|
||||||
|
buffer.push('\t');
|
||||||
|
buffer.push_str(&node.title);
|
||||||
|
buffer.push('\t');
|
||||||
|
buffer.push_str(&node.content_digest);
|
||||||
|
buffer.push('\t');
|
||||||
|
buffer.push_str(node.semantic_digest.as_deref().unwrap_or(""));
|
||||||
|
buffer.push('\n');
|
||||||
|
}
|
||||||
|
for edge in &self.edges {
|
||||||
|
buffer.push_str("e\t");
|
||||||
|
buffer.push_str(edge.source.as_str());
|
||||||
|
buffer.push('\t');
|
||||||
|
buffer.push_str(edge.kind.as_str());
|
||||||
|
buffer.push('\t');
|
||||||
|
buffer.push_str(edge.target.as_ref().map(NodeKey::as_str).unwrap_or(""));
|
||||||
|
buffer.push('\t');
|
||||||
|
buffer.push_str(&edge.raw_target);
|
||||||
|
buffer.push('\t');
|
||||||
|
buffer.push_str(edge.state.as_str());
|
||||||
|
buffer.push('\n');
|
||||||
|
}
|
||||||
|
for alias in &self.aliases {
|
||||||
|
buffer.push_str("a\t");
|
||||||
|
buffer.push_str(&alias.alias);
|
||||||
|
buffer.push('\t');
|
||||||
|
buffer.push_str(&alias.node.to_string());
|
||||||
|
buffer.push('\n');
|
||||||
|
}
|
||||||
|
sha256_prefixed(buffer.as_bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the knowledge graph from accepted document facts.
|
||||||
|
pub fn build(
|
||||||
|
facts: Vec<DocumentFacts>,
|
||||||
|
sources: &HashMap<&str, &str>,
|
||||||
|
assets: &[AssetFile],
|
||||||
|
missing_paths: &std::collections::HashSet<String>,
|
||||||
|
) -> Graph {
|
||||||
|
let mut diagnostics = DiagnosticSet::new();
|
||||||
|
for document in &facts {
|
||||||
|
diagnostics.merge(document.diagnostics.clone());
|
||||||
|
if !sources.contains_key(document.rel_path.as_str()) {
|
||||||
|
diagnostics.push(
|
||||||
|
Diagnostic::error(
|
||||||
|
code::INTERNAL,
|
||||||
|
"document facts have no matching source snapshot entry",
|
||||||
|
)
|
||||||
|
.with_path(&document.rel_path),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut node_map: BTreeMap<NodeKey, Node> = BTreeMap::new();
|
||||||
|
let mut edges: Vec<Edge> = Vec::new();
|
||||||
|
let mut aliases: Vec<AliasRecord> = Vec::new();
|
||||||
|
|
||||||
|
// Documents, units, statements and resources.
|
||||||
|
for document in &facts {
|
||||||
|
let source = sources
|
||||||
|
.get(document.rel_path.as_str())
|
||||||
|
.copied()
|
||||||
|
.unwrap_or("");
|
||||||
|
let doc_key = identity::document_key(&document.rel_path);
|
||||||
|
let doc_span = Span::new(0, source.len() as u64);
|
||||||
|
let origin = if document.analysis.is_some() {
|
||||||
|
EdgeOrigin::Analysis
|
||||||
|
} else {
|
||||||
|
EdgeOrigin::Document
|
||||||
|
};
|
||||||
|
let context = document
|
||||||
|
.analysis
|
||||||
|
.as_ref()
|
||||||
|
.map(|analysis| analysis.context_id.clone());
|
||||||
|
node_map.insert(
|
||||||
|
doc_key.clone(),
|
||||||
|
Node {
|
||||||
|
key: doc_key.clone(),
|
||||||
|
kind: NodeKind::Document,
|
||||||
|
doc_path: document.rel_path.clone(),
|
||||||
|
parent: None,
|
||||||
|
title: document.document_title.clone(),
|
||||||
|
span: Some(doc_span),
|
||||||
|
content_digest: content_digest(source, doc_span, &document.document_title),
|
||||||
|
semantic_digest: None,
|
||||||
|
metadata: serde_json::json!({
|
||||||
|
"format": document.format.as_str(),
|
||||||
|
"title": document.document_title,
|
||||||
|
"analysis": document.analysis.as_ref().map(|analysis| serde_json::json!({
|
||||||
|
"module_id": analysis.module_id,
|
||||||
|
"context_id": analysis.context_id,
|
||||||
|
"entry_module_id": analysis.entry_module_id,
|
||||||
|
"root_id": analysis.root_id,
|
||||||
|
})),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut unit_nodes: Vec<NodeKey> = Vec::with_capacity(document.units.len());
|
||||||
|
for (index, unit) in document.units.iter().enumerate() {
|
||||||
|
if index == 0 {
|
||||||
|
unit_nodes.push(doc_key.clone());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let key = identity::unit_key(&document.rel_path, unit.occurrence, &unit.path);
|
||||||
|
let function = document
|
||||||
|
.functions
|
||||||
|
.iter()
|
||||||
|
.find(|function| function.unit == index);
|
||||||
|
let span = Some(unit.span);
|
||||||
|
let metadata = match function {
|
||||||
|
Some(function) => serde_json::json!({
|
||||||
|
"mode": unit.mode,
|
||||||
|
"level": unit.level,
|
||||||
|
"path": unit.path,
|
||||||
|
"unit_id": unit.unit_id,
|
||||||
|
"function_id": function.function_id,
|
||||||
|
"local_name": function.local_name,
|
||||||
|
"namespace": function.namespace,
|
||||||
|
"signature": function.signature,
|
||||||
|
"effects": function.effects,
|
||||||
|
"callable": true,
|
||||||
|
"analysis": document.analysis.as_ref().map(|analysis| serde_json::json!({
|
||||||
|
"module_id": analysis.module_id,
|
||||||
|
"context_id": analysis.context_id,
|
||||||
|
"entry_module_id": analysis.entry_module_id,
|
||||||
|
"root_id": analysis.root_id,
|
||||||
|
})),
|
||||||
|
}),
|
||||||
|
None => serde_json::json!({
|
||||||
|
"mode": unit.mode,
|
||||||
|
"level": unit.level,
|
||||||
|
"path": unit.path,
|
||||||
|
"unit_id": unit.unit_id,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let semantic_digest = function.map(|function| {
|
||||||
|
let normalised = strip_spans(&function.body);
|
||||||
|
let interface = serde_json::json!({
|
||||||
|
"function_id": function.function_id,
|
||||||
|
"signature": function.signature,
|
||||||
|
"body": normalised,
|
||||||
|
});
|
||||||
|
sha256_prefixed(interface.to_string().as_bytes())
|
||||||
|
});
|
||||||
|
node_map.insert(
|
||||||
|
key.clone(),
|
||||||
|
Node {
|
||||||
|
key: key.clone(),
|
||||||
|
kind: match unit.kind {
|
||||||
|
crate::document::UnitKind::Namespace => NodeKind::Namespace,
|
||||||
|
crate::document::UnitKind::Function => NodeKind::Function,
|
||||||
|
_ => NodeKind::Section,
|
||||||
|
},
|
||||||
|
doc_path: document.rel_path.clone(),
|
||||||
|
parent: unit.parent.map(|parent| unit_nodes[parent].clone()),
|
||||||
|
title: unit.name.clone(),
|
||||||
|
span,
|
||||||
|
content_digest: content_digest(source, unit.span, &unit.name),
|
||||||
|
semantic_digest,
|
||||||
|
metadata,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
unit_nodes.push(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Contains edges for units.
|
||||||
|
for (index, unit) in document.units.iter().enumerate() {
|
||||||
|
if index == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(parent) = unit.parent else {
|
||||||
|
diagnostics.push(
|
||||||
|
Diagnostic::error(code::INTERNAL, "non-root unit has no parent")
|
||||||
|
.with_path(&document.rel_path),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
edges.push(Edge {
|
||||||
|
source: unit_nodes[parent].clone(),
|
||||||
|
target: Some(unit_nodes[index].clone()),
|
||||||
|
kind: EdgeKind::Contains,
|
||||||
|
origin,
|
||||||
|
raw_target: String::new(),
|
||||||
|
span: unit.heading_span,
|
||||||
|
doc_path: document.rel_path.clone(),
|
||||||
|
state: EdgeState::Resolved,
|
||||||
|
context: context.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Statements of functions.
|
||||||
|
for function in &document.functions {
|
||||||
|
let function_key = unit_nodes
|
||||||
|
.get(function.unit)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| doc_key.clone());
|
||||||
|
let occurrence = document
|
||||||
|
.units
|
||||||
|
.get(function.unit)
|
||||||
|
.map(|unit| unit.occurrence)
|
||||||
|
.unwrap_or(0);
|
||||||
|
let unit_path = document
|
||||||
|
.units
|
||||||
|
.get(function.unit)
|
||||||
|
.map(|unit| unit.path.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let mut statements = Vec::new();
|
||||||
|
collect_statements(&function.body, &mut statements);
|
||||||
|
let mut seen = std::collections::BTreeSet::new();
|
||||||
|
for (ordinal, (kind, span)) in statements.into_iter().enumerate() {
|
||||||
|
if !seen.insert((span.start, span.end, kind.clone())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let key = identity::statement_key(
|
||||||
|
&document.rel_path,
|
||||||
|
occurrence,
|
||||||
|
&unit_path,
|
||||||
|
ordinal,
|
||||||
|
span.start,
|
||||||
|
);
|
||||||
|
node_map.insert(
|
||||||
|
key.clone(),
|
||||||
|
Node {
|
||||||
|
key: key.clone(),
|
||||||
|
kind: NodeKind::Statement,
|
||||||
|
doc_path: document.rel_path.clone(),
|
||||||
|
parent: Some(function_key.clone()),
|
||||||
|
title: String::new(),
|
||||||
|
span: Some(span),
|
||||||
|
content_digest: content_digest(source, span, ""),
|
||||||
|
semantic_digest: None,
|
||||||
|
metadata: serde_json::json!({"statement_kind": kind}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
edges.push(Edge {
|
||||||
|
source: function_key.clone(),
|
||||||
|
target: Some(key),
|
||||||
|
kind: EdgeKind::Contains,
|
||||||
|
origin: EdgeOrigin::Analysis,
|
||||||
|
raw_target: String::new(),
|
||||||
|
span: Some(span),
|
||||||
|
doc_path: document.rel_path.clone(),
|
||||||
|
state: EdgeState::Resolved,
|
||||||
|
context: context.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resources.
|
||||||
|
for resource in &document.resources {
|
||||||
|
let key = identity::resource_key(&document.rel_path, &resource.id);
|
||||||
|
let parent = unit_nodes
|
||||||
|
.get(resource.unit)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| doc_key.clone());
|
||||||
|
node_map.insert(
|
||||||
|
key.clone(),
|
||||||
|
Node {
|
||||||
|
key: key.clone(),
|
||||||
|
kind: NodeKind::Resource,
|
||||||
|
doc_path: document.rel_path.clone(),
|
||||||
|
parent: Some(parent.clone()),
|
||||||
|
title: resource.kind.clone(),
|
||||||
|
span: Some(resource.span),
|
||||||
|
content_digest: content_digest(source, resource.span, &resource.id),
|
||||||
|
semantic_digest: None,
|
||||||
|
metadata: serde_json::json!({
|
||||||
|
"resource_id": resource.id,
|
||||||
|
"kind": resource.kind,
|
||||||
|
"language": resource.language,
|
||||||
|
"display": resource.display,
|
||||||
|
"content_digest": resource.content_digest,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
edges.push(Edge {
|
||||||
|
source: parent,
|
||||||
|
target: Some(key),
|
||||||
|
kind: EdgeKind::Contains,
|
||||||
|
origin: EdgeOrigin::Analysis,
|
||||||
|
raw_target: String::new(),
|
||||||
|
span: Some(resource.span),
|
||||||
|
doc_path: document.rel_path.clone(),
|
||||||
|
state: EdgeState::Resolved,
|
||||||
|
context: context.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aliases for upstream identities.
|
||||||
|
if let Some(analysis) = &document.analysis {
|
||||||
|
aliases.push(AliasRecord {
|
||||||
|
alias: analysis.module_id.clone(),
|
||||||
|
context: Some(analysis.context_id.clone()),
|
||||||
|
node: doc_key.clone(),
|
||||||
|
});
|
||||||
|
for (index, unit) in document.units.iter().enumerate() {
|
||||||
|
if let Some(unit_id) = &unit.unit_id {
|
||||||
|
aliases.push(AliasRecord {
|
||||||
|
alias: unit_id.clone(),
|
||||||
|
context: Some(analysis.context_id.clone()),
|
||||||
|
node: unit_nodes[index].clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for function in &document.functions {
|
||||||
|
aliases.push(AliasRecord {
|
||||||
|
alias: function.function_id.clone(),
|
||||||
|
context: Some(analysis.context_id.clone()),
|
||||||
|
node: unit_nodes
|
||||||
|
.get(function.unit)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| doc_key.clone()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assets are inert resource nodes; they are never parsed as text.
|
||||||
|
for asset in assets {
|
||||||
|
let key = identity::asset_key(&asset.rel_path);
|
||||||
|
node_map.insert(
|
||||||
|
key.clone(),
|
||||||
|
Node {
|
||||||
|
key,
|
||||||
|
kind: NodeKind::Resource,
|
||||||
|
doc_path: asset.rel_path.clone(),
|
||||||
|
parent: None,
|
||||||
|
title: asset.rel_path.clone(),
|
||||||
|
span: None,
|
||||||
|
content_digest: asset
|
||||||
|
.digest
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| format!("size:{}", asset.size)),
|
||||||
|
semantic_digest: None,
|
||||||
|
metadata: serde_json::json!({
|
||||||
|
"asset": true,
|
||||||
|
"path": asset.rel_path,
|
||||||
|
"size": asset.size,
|
||||||
|
"digest": asset.digest,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reference, import and call edges.
|
||||||
|
let resolver = resolve::Resolver::new(&facts, assets, missing_paths);
|
||||||
|
let (external_nodes, resolved_edges, resolution_diagnostics) = resolver.resolve_all();
|
||||||
|
diagnostics.merge(resolution_diagnostics);
|
||||||
|
for node in external_nodes {
|
||||||
|
node_map.entry(node.key.clone()).or_insert(node);
|
||||||
|
}
|
||||||
|
edges.extend(resolved_edges);
|
||||||
|
|
||||||
|
aliases.sort();
|
||||||
|
aliases.dedup();
|
||||||
|
let mut alias_owners: HashMap<(String, Option<String>), NodeKey> = HashMap::new();
|
||||||
|
for alias in &aliases {
|
||||||
|
let identity = (alias.alias.clone(), alias.context.clone());
|
||||||
|
if let Some(existing) = alias_owners.get(&identity) {
|
||||||
|
if existing != &alias.node {
|
||||||
|
diagnostics.push(Diagnostic::error(
|
||||||
|
code::IDENTITY_AMBIGUOUS,
|
||||||
|
format!(
|
||||||
|
"canonical alias `{}` maps to two different nodes",
|
||||||
|
alias.alias
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
alias_owners.insert(identity, alias.node.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deterministic edge order and duplicate-occurrence de-duplication.
|
||||||
|
edges.sort_by(|a, b| {
|
||||||
|
a.doc_path
|
||||||
|
.cmp(&b.doc_path)
|
||||||
|
.then(a.source.as_str().cmp(b.source.as_str()))
|
||||||
|
.then(a.kind.as_str().cmp(b.kind.as_str()))
|
||||||
|
.then(a.raw_target.cmp(&b.raw_target))
|
||||||
|
.then(
|
||||||
|
a.span
|
||||||
|
.map(|span| span.start)
|
||||||
|
.cmp(&b.span.map(|span| span.start)),
|
||||||
|
)
|
||||||
|
.then(
|
||||||
|
a.span
|
||||||
|
.map(|span| span.end)
|
||||||
|
.cmp(&b.span.map(|span| span.end)),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
edges.dedup_by(|a, b| {
|
||||||
|
a.source == b.source
|
||||||
|
&& a.target == b.target
|
||||||
|
&& a.kind == b.kind
|
||||||
|
&& a.raw_target == b.raw_target
|
||||||
|
&& a.span == b.span
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut nodes: Vec<Node> = node_map.into_values().collect();
|
||||||
|
nodes.sort_by(|a, b| a.key.as_str().cmp(b.key.as_str()));
|
||||||
|
|
||||||
|
// Parent references must exist and the contains tree must be acyclic with
|
||||||
|
// a single parent. Parents were built from unit indexes, but validate the
|
||||||
|
// final graph as a projection invariant.
|
||||||
|
let node_keys: std::collections::HashSet<&str> =
|
||||||
|
nodes.iter().map(|node| node.key.as_str()).collect();
|
||||||
|
for node in &nodes {
|
||||||
|
if let Some(parent) = &node.parent {
|
||||||
|
if !node_keys.contains(parent.as_str()) {
|
||||||
|
diagnostics.push(
|
||||||
|
Diagnostic::error(code::INTERNAL, "node parent does not exist")
|
||||||
|
.with_path(&node.doc_path),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validate_contains_acyclic(&nodes, &edges, &mut diagnostics);
|
||||||
|
|
||||||
|
diagnostics.sorted();
|
||||||
|
Graph {
|
||||||
|
facts,
|
||||||
|
assets: assets.to_vec(),
|
||||||
|
nodes,
|
||||||
|
edges,
|
||||||
|
aliases,
|
||||||
|
diagnostics,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_contains_acyclic(nodes: &[Node], edges: &[Edge], diagnostics: &mut DiagnosticSet) {
|
||||||
|
let parents: HashMap<&str, &str> = nodes
|
||||||
|
.iter()
|
||||||
|
.filter_map(|node| {
|
||||||
|
node.parent
|
||||||
|
.as_ref()
|
||||||
|
.map(|parent| (node.key.as_str(), parent.as_str()))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
for node in nodes {
|
||||||
|
let mut cursor = Some(node.key.as_str());
|
||||||
|
let mut steps = 0usize;
|
||||||
|
while let Some(current) = cursor {
|
||||||
|
steps += 1;
|
||||||
|
if steps > nodes.len() + 1 {
|
||||||
|
diagnostics.push(
|
||||||
|
Diagnostic::error(code::INTERNAL, "contains parent chain contains a cycle")
|
||||||
|
.with_path(&node.doc_path),
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cursor = parents.get(current).copied();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = edges;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn content_digest(source: &str, span: Span, fallback: &str) -> String {
|
||||||
|
match span.slice(source.as_bytes()) {
|
||||||
|
Some(text) => sha256_prefixed(text.as_bytes()),
|
||||||
|
None => sha256_prefixed(fallback.as_bytes()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collect `(statement kind, span)` from a function body, preserving order.
|
||||||
|
fn collect_statements(body: &serde_json::Value, out: &mut Vec<(String, Span)>) {
|
||||||
|
let Some(statements) = body.as_array() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for statement in statements {
|
||||||
|
let Some(object) = statement.as_object() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(kind) = object.get("kind").and_then(|kind| kind.as_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if let Some(span) = statement_span(statement) {
|
||||||
|
out.push((kind.to_string(), span));
|
||||||
|
}
|
||||||
|
match kind {
|
||||||
|
"branch" => {
|
||||||
|
if let Some(arms) = object.get("arms").and_then(|arms| arms.as_array()) {
|
||||||
|
for arm in arms {
|
||||||
|
if let Some(body) = arm.get("body") {
|
||||||
|
collect_statements(body, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"loop" => {
|
||||||
|
if let Some(body) = object.get("body") {
|
||||||
|
collect_statements(body, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn statement_span(statement: &serde_json::Value) -> Option<Span> {
|
||||||
|
let span = statement.get("span")?;
|
||||||
|
let start = span.get("start")?.as_u64()?;
|
||||||
|
let end = span.get("end")?.as_u64()?;
|
||||||
|
Some(Span::new(start, end))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recursively remove source positions for the position-free semantic digest.
|
||||||
|
fn strip_spans(value: &serde_json::Value) -> serde_json::Value {
|
||||||
|
match value {
|
||||||
|
serde_json::Value::Object(object) => {
|
||||||
|
let mut out = serde_json::Map::new();
|
||||||
|
for (key, value) in object {
|
||||||
|
if key == "span" || key.ends_with("_span") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.insert(key.clone(), strip_spans(value));
|
||||||
|
}
|
||||||
|
serde_json::Value::Object(out)
|
||||||
|
}
|
||||||
|
serde_json::Value::Array(items) => {
|
||||||
|
serde_json::Value::Array(items.iter().map(strip_spans).collect())
|
||||||
|
}
|
||||||
|
other => other.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::document::discovery::{discover, resolve_scope};
|
||||||
|
use crate::document::markdown::parse_plain;
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
fn plain_facts(content: &str) -> (String, Vec<DocumentFacts>) {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let path = temp.path().join("doc.md");
|
||||||
|
let mut file = std::fs::File::create(&path).unwrap();
|
||||||
|
file.write_all(content.as_bytes()).unwrap();
|
||||||
|
let scope = resolve_scope(&path, &[]).unwrap();
|
||||||
|
let snapshot = discover(&scope).unwrap();
|
||||||
|
let facts = snapshot.files.iter().map(parse_plain).collect();
|
||||||
|
(content.to_string(), facts)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn contains_tree_and_document_node_are_built() {
|
||||||
|
let (text, facts) = plain_facts("# A\n\n## B\n\ntext\n");
|
||||||
|
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||||
|
sources.insert("doc.md", text.as_str());
|
||||||
|
let graph = build(facts, &sources, &[], &Default::default());
|
||||||
|
assert_eq!(
|
||||||
|
graph
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.filter(|n| n.kind == NodeKind::Document)
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
graph
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.filter(|n| n.kind == NodeKind::Section)
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
graph
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.filter(|n| n.kind == NodeKind::Namespace)
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert!(graph
|
||||||
|
.edges
|
||||||
|
.iter()
|
||||||
|
.any(|edge| edge.kind == EdgeKind::Contains && edge.state == EdgeState::Resolved));
|
||||||
|
assert!(!graph.diagnostics.has_errors(), "{:?}", graph.diagnostics);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn references_externals_and_missing_targets_are_stated() {
|
||||||
|
let (text, facts) = plain_facts(
|
||||||
|
"# t\n\n[ok](#t) [ext](https://example.com) [unindexed](missing.md) [gone](gone.bin) [asset](data.bin)\n",
|
||||||
|
);
|
||||||
|
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||||
|
sources.insert("doc.md", text.as_str());
|
||||||
|
let assets = vec![AssetFile {
|
||||||
|
rel_path: "data.bin".into(),
|
||||||
|
size: 3,
|
||||||
|
digest: Some("sha256:abc".into()),
|
||||||
|
}];
|
||||||
|
let graph = build(facts, &sources, &assets, &Default::default());
|
||||||
|
assert!(!graph.diagnostics.has_errors());
|
||||||
|
let states: Vec<EdgeState> = graph
|
||||||
|
.edges
|
||||||
|
.iter()
|
||||||
|
.filter(|edge| edge.kind == EdgeKind::References)
|
||||||
|
.map(|edge| edge.state)
|
||||||
|
.collect();
|
||||||
|
assert!(states.contains(&EdgeState::Resolved));
|
||||||
|
assert!(states.contains(&EdgeState::External));
|
||||||
|
assert!(states.contains(&EdgeState::NotLoaded));
|
||||||
|
assert!(states.contains(&EdgeState::Missing));
|
||||||
|
assert!(graph
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.any(|node| node.kind == NodeKind::External));
|
||||||
|
assert!(graph
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.any(|diagnostic| diagnostic.code == code::REFERENCE_MISSING));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeated_links_keep_each_occurrence() {
|
||||||
|
let (text, facts) = plain_facts("# t\n\n[a](#t) [a](#t)\n");
|
||||||
|
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||||
|
sources.insert("doc.md", text.as_str());
|
||||||
|
let graph = build(facts, &sources, &[], &Default::default());
|
||||||
|
let references: Vec<_> = graph
|
||||||
|
.edges
|
||||||
|
.iter()
|
||||||
|
.filter(|edge| edge.kind == EdgeKind::References)
|
||||||
|
.collect();
|
||||||
|
assert_eq!(references.len(), 2);
|
||||||
|
assert_ne!(references[0].span, references[1].span);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicate_headings_resolve_through_numbered_anchors() {
|
||||||
|
let (text, facts) = plain_facts("# t\n\n## dup\n\na\n\n## dup\n\nb\n\n[x](#dup-1)\n");
|
||||||
|
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||||
|
sources.insert("doc.md", text.as_str());
|
||||||
|
let graph = build(facts, &sources, &[], &Default::default());
|
||||||
|
let edge = graph
|
||||||
|
.edges
|
||||||
|
.iter()
|
||||||
|
.find(|edge| edge.kind == EdgeKind::References)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(edge.state, EdgeState::Resolved);
|
||||||
|
let target = edge.target.as_ref().unwrap();
|
||||||
|
let node = graph.nodes.iter().find(|node| &node.key == target).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
node.span.unwrap().start,
|
||||||
|
text.find("## dup\n\nb").unwrap() as u64
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ambiguous_canonical_names_are_not_bound() {
|
||||||
|
let (text, mut facts) = plain_facts("# t\n\n## dup\n\na\n\n## dup\n\nb\n\n[x](#dup%20)\n");
|
||||||
|
// Remove numbered anchors to exercise the canonical-name fallback:
|
||||||
|
// two exact name matches must stay ambiguous and unbound.
|
||||||
|
for fact in &mut facts {
|
||||||
|
fact.anchors.clear();
|
||||||
|
}
|
||||||
|
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||||
|
sources.insert("doc.md", text.as_str());
|
||||||
|
let graph = build(facts, &sources, &[], &Default::default());
|
||||||
|
let state = graph
|
||||||
|
.edges
|
||||||
|
.iter()
|
||||||
|
.find(|edge| edge.kind == EdgeKind::References)
|
||||||
|
.map(|edge| edge.state);
|
||||||
|
assert_eq!(state, Some(EdgeState::Ambiguous));
|
||||||
|
assert!(graph
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.any(|diagnostic| diagnostic.code == code::REFERENCE_AMBIGUOUS));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn logical_digest_is_stable_and_path_independent() {
|
||||||
|
let (text, facts) = plain_facts("# A\n\ntext\n");
|
||||||
|
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||||
|
sources.insert("doc.md", text.as_str());
|
||||||
|
let first = build(facts, &sources, &[], &Default::default()).logical_digest();
|
||||||
|
let (text, facts) = plain_facts("# A\n\ntext\n");
|
||||||
|
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||||
|
sources.insert("doc.md", text.as_str());
|
||||||
|
let second = build(facts, &sources, &[], &Default::default()).logical_digest();
|
||||||
|
assert_eq!(first, second);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -10,6 +10,7 @@ pub mod compiler;
|
|||||||
pub mod diagnostic;
|
pub mod diagnostic;
|
||||||
pub mod document;
|
pub mod document;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
pub mod graph;
|
||||||
pub mod model;
|
pub mod model;
|
||||||
pub mod query;
|
pub mod query;
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user