diff --git a/src/document/mod.rs b/src/document/mod.rs index 5082fbd..ad23868 100644 --- a/src/document/mod.rs +++ b/src/document/mod.rs @@ -13,7 +13,8 @@ pub mod markdown; pub mod okf; use crate::diagnostic::DiagnosticSet; -use crate::model::{DocumentFormat, Span}; +pub use crate::model::DocumentFormat; +use crate::model::Span; use serde::{Deserialize, Serialize}; use std::path::PathBuf; diff --git a/src/graph/identity.rs b/src/graph/identity.rs new file mode 100644 index 0000000..f89df9d --- /dev/null +++ b/src/graph/identity.rs @@ -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); + } +} diff --git a/src/graph/mod.rs b/src/graph/mod.rs new file mode 100644 index 0000000..b6a449f --- /dev/null +++ b/src/graph/mod.rs @@ -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, + pub title: String, + pub span: Option, + /// `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, + 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, + pub kind: EdgeKind, + pub origin: EdgeOrigin, + pub raw_target: String, + pub span: Option, + pub doc_path: String, + pub state: EdgeState, + pub context: Option, +} + +/// 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, + pub node: NodeKey, +} + +#[derive(Debug, Clone)] +pub struct Graph { + pub facts: Vec, + pub assets: Vec, + pub nodes: Vec, + pub edges: Vec, + pub aliases: Vec, + 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, + sources: &HashMap<&str, &str>, + assets: &[AssetFile], + missing_paths: &std::collections::HashSet, +) -> 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 = BTreeMap::new(); + let mut edges: Vec = Vec::new(); + let mut aliases: Vec = 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 = 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), 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_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 { + 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) { + 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 = 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); + } +} diff --git a/src/graph/resolve.rs b/src/graph/resolve.rs new file mode 100644 index 0000000..8f30ed2 --- /dev/null +++ b/src/graph/resolve.rs @@ -0,0 +1,1084 @@ +//! Reference, import and call resolution. +//! +//! Resolution is exact and deterministic. Ordinary Markdown links are resolved +//! against the documents indexed in the selected root; Marqdo links keep the +//! upstream resolution state and are never silently re-bound. A dynamic or +//! unresolved call stays unresolved. External targets are inert nodes. +//! +//! Local URL rules: split the fragment, percent-decode each part exactly once, +//! reject NUL/control characters, reject absolute/drive/UNC/file targets, +//! resolve the path relative to the referencing document and refuse any escape +//! from the root. External URI schemes never cause network access. + +use super::identity; +use crate::diagnostic::{code, Diagnostic, DiagnosticSet}; +use crate::document::ast::normalize_heading_name; +use crate::document::markdown::slugify; +use crate::document::{AssetFile, DocumentFacts}; +use crate::model::{EdgeKind, EdgeOrigin, EdgeState, NodeKey, NodeKind, Span}; +use std::collections::{BTreeMap, HashMap, HashSet}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LinkError { + OutsideScope, + Invalid(String), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ParsedLink { + External { + scheme: String, + }, + Local { + path: String, + fragment: Option, + }, +} + +impl ParsedLink { + pub fn is_external(&self) -> bool { + matches!(self, ParsedLink::External { .. }) + } +} + +/// Parse one raw Markdown URL without touching the filesystem. +pub fn parse_link(url: &str) -> Result { + if url.chars().any(char::is_control) { + return Err(LinkError::Invalid("URL contains control characters".into())); + } + if url.starts_with("//") { + return Ok(ParsedLink::External { + scheme: "//".into(), + }); + } + // Scheme detection: a colon before any `/`, `?` or `#`. + let mut scheme_end = None; + for (index, ch) in url.char_indices() { + match ch { + ':' => { + scheme_end = Some(index); + break; + } + '/' | '?' | '#' => break, + _ => {} + } + } + if let Some(index) = scheme_end { + let scheme = &url[..index]; + let valid = !scheme.is_empty() + && scheme + .chars() + .next() + .is_some_and(|first| first.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')); + if valid { + if scheme.eq_ignore_ascii_case("file") { + return Err(LinkError::OutsideScope); + } + return Ok(ParsedLink::External { + scheme: scheme.to_ascii_lowercase(), + }); + } + } + let (path_part, fragment_part) = match url.split_once('#') { + Some((path, fragment)) => (path, Some(fragment)), + None => (url, None), + }; + let fragment = match fragment_part { + Some(fragment) => { + let decoded = crate::model::percent_decode(fragment.as_bytes()).ok_or_else(|| { + LinkError::Invalid("fragment is not valid percent encoding".into()) + })?; + let decoded = String::from_utf8(decoded) + .map_err(|_| LinkError::Invalid("fragment is not valid UTF-8".into()))?; + Some(decoded) + } + None => None, + }; + let decoded_path = crate::model::percent_decode(path_part.as_bytes()) + .ok_or_else(|| LinkError::Invalid("path is not valid percent encoding".into()))?; + let path = String::from_utf8(decoded_path) + .map_err(|_| LinkError::Invalid("path is not valid UTF-8".into()))?; + if path.starts_with('/') + || path.starts_with('\\') + || (path.len() >= 2 && path.as_bytes()[1] == b':') + { + return Err(LinkError::OutsideScope); + } + Ok(ParsedLink::Local { path, fragment }) +} + +#[derive(Debug, Clone)] +pub struct ResolvedTarget { + pub node: Option, + pub state: EdgeState, + pub diagnostic: Option, + pub external: Option, + pub external_key: Option, + pub external_title: String, +} + +impl ResolvedTarget { + fn node(node: NodeKey) -> Self { + Self { + node: Some(node), + state: EdgeState::Resolved, + diagnostic: None, + external: None, + external_key: None, + external_title: String::new(), + } + } + + fn external(key: NodeKey, title: &str, metadata: serde_json::Value, state: EdgeState) -> Self { + Self { + node: Some(key.clone()), + state, + diagnostic: None, + external: Some(metadata), + external_key: Some(key), + external_title: title.to_string(), + } + } + + fn unloaded_placeholder(path: &str, span: Span, candidate: &str) -> Self { + Self::unresolved( + EdgeState::NotLoaded, + Some( + Diagnostic::warning( + code::REFERENCE_NOT_LOADED, + format!("document `{candidate}` is not included in the compiled root"), + ) + .with_path(path) + .with_span(span), + ), + ) + } + + fn unresolved(state: EdgeState, diagnostic: Option) -> Self { + Self { + node: None, + state, + diagnostic, + external: None, + external_key: None, + external_title: String::new(), + } + } +} + +enum PathResolution { + SameDocument, + Document(String), + Asset(String), + NotLoaded, + Missing(String), + Outside, + Invalid(String), +} + +enum FragmentLookup { + Unit(usize), + Missing, + Ambiguous, +} + +pub struct Resolver<'a> { + facts: &'a [DocumentFacts], + docs: HashMap<&'a str, &'a DocumentFacts>, + modules: HashMap<&'a str, &'a str>, + unit_ids: HashMap<&'a str, (&'a str, usize)>, + function_ids: HashMap<&'a str, (&'a str, usize)>, + package_of: HashMap<&'a str, &'a str>, + doc_nodes: HashMap<&'a str, NodeKey>, + unit_nodes: HashMap<(&'a str, usize), NodeKey>, + assets: HashMap<&'a str, &'a AssetFile>, + missing_paths: &'a HashSet, + anchors: HashMap<(&'a str, String), usize>, + names: HashMap<(&'a str, String), Vec>, + pub externals: BTreeMap, + pub edges: Vec, + pub diagnostics: DiagnosticSet, +} + +impl<'a> Resolver<'a> { + pub fn new( + facts: &'a [DocumentFacts], + assets: &'a [AssetFile], + missing_paths: &'a HashSet, + ) -> Self { + let mut docs = HashMap::new(); + let mut modules = HashMap::new(); + let mut unit_ids = HashMap::new(); + let mut function_ids = HashMap::new(); + let mut package_of = HashMap::new(); + let mut doc_nodes = HashMap::new(); + let mut unit_nodes = HashMap::new(); + let mut anchors: HashMap<(&str, String), usize> = HashMap::new(); + let mut names: HashMap<(&str, String), Vec> = HashMap::new(); + for fact in facts { + let rel = fact.rel_path.as_str(); + docs.insert(rel, fact); + doc_nodes.insert(rel, identity::document_key(rel)); + unit_nodes.insert((rel, 0), identity::document_key(rel)); + if let Some(analysis) = &fact.analysis { + modules.insert(analysis.module_id.as_str(), rel); + package_of.insert(rel, analysis.package_instance_id.as_str()); + } + for (index, unit) in fact.units.iter().enumerate() { + if index > 0 { + unit_nodes.insert( + (rel, index), + identity::unit_key(rel, unit.occurrence, &unit.path), + ); + } + if let Some(unit_id) = &unit.unit_id { + unit_ids.insert(unit_id.as_str(), (rel, index)); + } + if !unit.name.is_empty() { + names + .entry((rel, normalize_heading_name(&unit.name))) + .or_default() + .push(index); + } + } + for anchor in &fact.anchors { + anchors.insert((rel, anchor.anchor.clone()), anchor.unit); + } + for function in &fact.functions { + function_ids.insert(function.function_id.as_str(), (rel, function.unit)); + } + } + let assets: HashMap<&str, &AssetFile> = assets + .iter() + .map(|asset| (asset.rel_path.as_str(), asset)) + .collect(); + Self { + facts, + docs, + modules, + unit_ids, + function_ids, + package_of, + doc_nodes, + unit_nodes, + assets, + anchors, + names, + missing_paths, + externals: BTreeMap::new(), + edges: Vec::new(), + diagnostics: DiagnosticSet::new(), + } + } + + pub fn resolve_all(mut self) -> (Vec, Vec, DiagnosticSet) { + for fact in self.facts { + let context = fact + .analysis + .as_ref() + .map(|analysis| analysis.context_id.clone()); + let origin = if fact.analysis.is_some() { + EdgeOrigin::Analysis + } else { + EdgeOrigin::Document + }; + for reference in &fact.references { + self.resolve_reference(fact, reference, origin, context.as_deref()); + } + for import in &fact.imports { + self.resolve_import(fact, import, context.as_deref()); + } + for call in &fact.calls { + self.resolve_call(fact, call, context.as_deref()); + } + } + let mut diagnostics = std::mem::take(&mut self.diagnostics); + diagnostics.sorted(); + let externals = self + .externals + .into_iter() + .map(|(key, (title, metadata))| super::Node { + key: key.clone(), + kind: NodeKind::External, + doc_path: String::new(), + parent: None, + title, + span: None, + content_digest: crate::model::sha256_prefixed(key.as_str().as_bytes()), + semantic_digest: None, + metadata, + }) + .collect(); + (externals, self.edges, diagnostics) + } + + fn unit_node(&self, rel: &str, unit: usize) -> NodeKey { + self.unit_nodes + .get(&(rel, unit)) + .cloned() + .unwrap_or_else(|| self.doc_nodes[rel].clone()) + } + + fn register_external( + &mut self, + key: NodeKey, + title: &str, + metadata: serde_json::Value, + ) -> NodeKey { + self.externals + .entry(key.clone()) + .or_insert_with(|| (title.to_string(), metadata)); + key + } + + #[allow(clippy::too_many_arguments)] // one call site type: an edge occurrence + fn push_edge( + &mut self, + source: NodeKey, + target: Option, + kind: EdgeKind, + origin: EdgeOrigin, + raw_target: String, + span: Option, + doc_path: &str, + state: EdgeState, + context: Option<&str>, + ) { + self.edges.push(super::Edge { + source, + target, + kind, + origin, + raw_target, + span, + doc_path: doc_path.to_string(), + state, + context: context.map(str::to_string), + }); + } + + fn resolve_reference( + &mut self, + fact: &DocumentFacts, + reference: &crate::document::ReferenceFact, + origin: EdgeOrigin, + context: Option<&str>, + ) { + let source = self.unit_node(&fact.rel_path, reference.unit); + let resolution = if let Some(analysis) = &reference.analysis { + self.resolve_analysis_reference(fact, reference, analysis) + } else { + self.resolve_native_reference(fact, reference) + }; + if let Some(diagnostic) = &resolution.diagnostic { + self.diagnostics.push(diagnostic.clone()); + } + let target = match (resolution.external_key, resolution.external) { + (Some(key), Some(metadata)) => { + self.register_external(key.clone(), &resolution.external_title, metadata); + Some(key) + } + (Some(key), None) => Some(key), + (None, _) => resolution.node, + }; + self.push_edge( + source, + target, + EdgeKind::References, + origin, + reference.url.clone(), + Some(reference.span), + &fact.rel_path, + resolution.state, + context, + ); + } + + fn resolve_analysis_reference( + &mut self, + fact: &DocumentFacts, + reference: &crate::document::ReferenceFact, + analysis: &crate::document::AnalysisReferenceFact, + ) -> ResolvedTarget { + let span = reference.span; + let path = &fact.rel_path; + match analysis.state { + EdgeState::Resolved => { + if analysis.target_kind.as_deref() == Some("module") { + let Some(module_id) = analysis.target_module.as_deref() else { + return ResolvedTarget::unresolved( + EdgeState::Invalid, + Some(self.reference_diagnostic( + code::ANALYSIS_INVALID, + "resolved module reference has no target module", + path, + span, + )), + ); + }; + if let Some(rel) = self.modules.get(module_id).copied() { + if let Some(unit_id) = analysis.target_unit.as_deref() { + match self.unit_ids.get(unit_id).copied() { + Some((unit_rel, unit)) if unit_rel == rel => { + return ResolvedTarget::node(self.unit_node(rel, unit)); + } + Some(_) => { + return ResolvedTarget::unresolved( + EdgeState::Missing, + Some(self.reference_diagnostic( + code::INTERFACE_CONFLICT, + "upstream resolved unit belongs to a different module than its declared target", + path, + span, + )), + ); + } + None => { + return ResolvedTarget::unresolved( + EdgeState::Missing, + Some(self.reference_diagnostic( + code::INTERFACE_CONFLICT, + "upstream resolved unit id is not present in the compiled module facts", + path, + span, + )), + ); + } + } + } + return ResolvedTarget::node(self.doc_nodes[rel].clone()); + } + // Resolved to a module outside the compiled root: keep an + // explicit external node, never fabricate local source. + let key = match analysis.target_unit.as_deref() { + Some(unit) => identity::external_unit_key(unit), + None => identity::external_module_key(module_id), + }; + return ResolvedTarget::external( + key, + analysis.target_unit.as_deref().unwrap_or(module_id), + serde_json::json!({ + "external_kind": "analysis_target", + "module_id": module_id, + "unit_id": analysis.target_unit, + }), + EdgeState::Resolved, + ); + } + // File target: upstream verified a local file. + if let Some(candidate) = analysis.candidate_path.as_deref() { + if self.docs.contains_key(candidate) { + return ResolvedTarget::node(self.doc_nodes[candidate].clone()); + } + if let Some(asset) = self.assets.get(candidate) { + let key = identity::asset_key(asset.rel_path.as_str()); + return ResolvedTarget::node(key); + } + let key = identity::external_file_key(candidate); + return ResolvedTarget::external( + key, + candidate, + serde_json::json!({"external_kind": "file", "path": candidate}), + EdgeState::Resolved, + ); + } + ResolvedTarget::unresolved( + EdgeState::Invalid, + Some(self.reference_diagnostic( + code::ANALYSIS_INVALID, + "resolved file reference has no candidate path", + path, + span, + )), + ) + } + EdgeState::NotLoaded => self.resolve_not_loaded(fact, reference, analysis), + EdgeState::External => { + let url = reference.url.clone(); + let key = identity::external_url_key(&url); + ResolvedTarget::external( + key, + &url, + serde_json::json!({"external_kind": "url", "url": url}), + EdgeState::External, + ) + } + EdgeState::Missing => ResolvedTarget::unresolved( + EdgeState::Missing, + Some(self.reference_diagnostic( + code::REFERENCE_MISSING, + "Marqdo reference target does not exist", + path, + span, + )), + ), + EdgeState::Ambiguous => ResolvedTarget::unresolved( + EdgeState::Ambiguous, + Some(self.reference_diagnostic( + code::REFERENCE_AMBIGUOUS, + "Marqdo reference is ambiguous; no target was chosen", + path, + span, + )), + ), + EdgeState::OutOfScope => ResolvedTarget::unresolved( + EdgeState::OutOfScope, + Some(self.reference_diagnostic( + code::REFERENCE_OUT_OF_SCOPE, + "reference escapes the allowed knowledge root", + path, + span, + )), + ), + EdgeState::Dynamic | EdgeState::Unresolved => ResolvedTarget::unresolved( + analysis.state, + Some(self.reference_diagnostic( + code::INTERFACE_CONFLICT, + "reference has a state that only calls may carry", + path, + span, + )), + ), + EdgeState::Invalid => ResolvedTarget::unresolved( + EdgeState::Invalid, + Some(self.reference_diagnostic( + code::REFERENCE_INVALID, + "reference address is invalid", + path, + span, + )), + ), + } + } + + fn resolve_not_loaded( + &mut self, + fact: &DocumentFacts, + reference: &crate::document::ReferenceFact, + analysis: &crate::document::AnalysisReferenceFact, + ) -> ResolvedTarget { + let span = reference.span; + let path = &fact.rel_path; + let Some(candidate) = analysis.candidate_path.as_deref() else { + return ResolvedTarget::unresolved( + EdgeState::NotLoaded, + Some(self.reference_diagnostic( + code::REFERENCE_NOT_LOADED, + "local reference is outside the loaded program and had no candidate path", + path, + span, + )), + ); + }; + // A candidate in another package instance is not this root. + let package_matches = analysis + .candidate_package_instance_id + .as_deref() + .is_none_or(|candidate| { + self.package_of + .get(fact.rel_path.as_str()) + .is_some_and(|current| current == &candidate) + }); + if !package_matches { + return ResolvedTarget::unresolved(EdgeState::NotLoaded, None); + } + if crate::document::discovery::validate_relative_path(candidate).is_err() { + return ResolvedTarget::unresolved( + EdgeState::Invalid, + Some(self.reference_diagnostic( + code::REFERENCE_INVALID, + "candidate path is not a safe root-relative path", + path, + span, + )), + ); + } + if let Some(target) = self.docs.get(candidate).copied() { + let fragment = analysis + .fragment + .as_deref() + .filter(|fragment| !fragment.is_empty()); + match fragment { + None => return ResolvedTarget::node(self.doc_nodes[candidate].clone()), + Some(fragment) => { + return match self.lookup_fragment(target.rel_path.as_str(), fragment) { + FragmentLookup::Unit(unit) => { + ResolvedTarget::node(self.unit_node(&target.rel_path, unit)) + } + FragmentLookup::Missing => ResolvedTarget::unresolved( + EdgeState::Missing, + Some(self.reference_diagnostic( + code::REFERENCE_MISSING, + format!( + "document `{candidate}` has no anchor or unique heading `{fragment}`" + ), + path, + span, + )), + ), + FragmentLookup::Ambiguous => ResolvedTarget::unresolved( + EdgeState::Ambiguous, + Some(self.reference_diagnostic( + code::REFERENCE_AMBIGUOUS, + format!( + "heading name `{fragment}` in `{candidate}` is ambiguous" + ), + path, + span, + )), + ), + }; + } + } + } + if let Some(asset) = self.assets.get(candidate) { + return ResolvedTarget::node(identity::asset_key(asset.rel_path.as_str())); + } + if self.missing_paths.contains(candidate) { + return ResolvedTarget::unresolved( + EdgeState::Missing, + Some(self.reference_diagnostic( + code::REFERENCE_MISSING, + format!("referenced path `{candidate}` does not exist in the compiled root"), + path, + span, + )), + ); + } + if crate::document::DocumentFormat::from_path(candidate).is_some() { + // A Markdown target that the selected scope excluded from + // compilation cannot be verified here. + return ResolvedTarget::unloaded_placeholder(path, span, candidate); + } + ResolvedTarget::unresolved( + EdgeState::Missing, + Some(self.reference_diagnostic( + code::REFERENCE_MISSING, + format!("referenced file `{candidate}` does not exist in the compiled root"), + path, + span, + )), + ) + } + + fn resolve_native_reference( + &mut self, + fact: &DocumentFacts, + reference: &crate::document::ReferenceFact, + ) -> ResolvedTarget { + let span = reference.span; + let path = &fact.rel_path; + let link = match parse_link(&reference.url) { + Ok(link) => link, + Err(LinkError::OutsideScope) => { + return ResolvedTarget::unresolved( + EdgeState::OutOfScope, + Some(self.reference_diagnostic( + code::REFERENCE_OUT_OF_SCOPE, + "reference uses an absolute/file target and was not read", + path, + span, + )), + ); + } + Err(LinkError::Invalid(message)) => { + return ResolvedTarget::unresolved( + EdgeState::Invalid, + Some(self.reference_diagnostic( + code::REFERENCE_INVALID, + format!("reference URL is invalid: {message}"), + path, + span, + )), + ); + } + }; + let ParsedLink::Local { + path: link_path, + fragment, + } = link + else { + let url = reference.url.clone(); + let key = identity::external_url_key(&url); + return ResolvedTarget::external( + key, + &url, + serde_json::json!({"external_kind": "url", "url": url}), + EdgeState::External, + ); + }; + let resolution = self.resolve_path(&fact.rel_path, &link_path); + if matches!(resolution, PathResolution::SameDocument) { + let Some(doc) = self.docs.get(fact.rel_path.as_str()).copied() else { + return ResolvedTarget::unresolved(EdgeState::NotLoaded, None); + }; + return self.resolve_document_target(doc, fragment.as_deref(), span, path); + } + match resolution { + PathResolution::SameDocument => unreachable!(), + PathResolution::Document(target) => { + let Some(doc) = self.docs.get(target.as_str()).copied() else { + return ResolvedTarget::unresolved(EdgeState::NotLoaded, None); + }; + self.resolve_document_target(doc, fragment.as_deref(), span, path) + } + PathResolution::Asset(asset) => { + if fragment + .as_deref() + .is_some_and(|fragment| !fragment.is_empty()) + { + return ResolvedTarget::unresolved( + EdgeState::Invalid, + Some(self.reference_diagnostic( + code::REFERENCE_INVALID, + "a file target cannot carry a heading fragment", + path, + span, + )), + ); + } + ResolvedTarget::node(identity::asset_key(&asset)) + } + PathResolution::NotLoaded => ResolvedTarget::unresolved( + EdgeState::NotLoaded, + Some(self.reference_diagnostic( + code::REFERENCE_NOT_LOADED, + "referenced Markdown document is not included in the compiled root", + path, + span, + )), + ), + PathResolution::Missing(target) => ResolvedTarget::unresolved( + EdgeState::Missing, + Some(self.reference_diagnostic( + code::REFERENCE_MISSING, + format!("referenced path `{target}` does not exist in the compiled root"), + path, + span, + )), + ), + PathResolution::Outside => ResolvedTarget::unresolved( + EdgeState::OutOfScope, + Some(self.reference_diagnostic( + code::REFERENCE_OUT_OF_SCOPE, + "reference escapes the allowed knowledge root", + path, + span, + )), + ), + PathResolution::Invalid(message) => ResolvedTarget::unresolved( + EdgeState::Invalid, + Some(self.reference_diagnostic( + code::REFERENCE_INVALID, + format!("reference path is invalid: {message}"), + path, + span, + )), + ), + } + } + + fn resolve_document_target( + &mut self, + doc: &'a DocumentFacts, + fragment: Option<&str>, + span: Span, + source_path: &str, + ) -> ResolvedTarget { + let fragment = fragment.filter(|fragment| !fragment.is_empty()); + let Some(fragment) = fragment else { + return ResolvedTarget::node(self.doc_nodes[doc.rel_path.as_str()].clone()); + }; + match self.lookup_fragment(doc.rel_path.as_str(), fragment) { + FragmentLookup::Unit(unit) => { + ResolvedTarget::node(self.unit_node(doc.rel_path.as_str(), unit)) + } + FragmentLookup::Missing => ResolvedTarget::unresolved( + EdgeState::Missing, + Some(self.reference_diagnostic( + code::REFERENCE_MISSING, + format!( + "document `{}` has no anchor or unique heading `{fragment}`", + doc.rel_path + ), + source_path, + span, + )), + ), + FragmentLookup::Ambiguous => ResolvedTarget::unresolved( + EdgeState::Ambiguous, + Some(self.reference_diagnostic( + code::REFERENCE_AMBIGUOUS, + format!("heading name `{fragment}` is ambiguous; no target was chosen"), + source_path, + span, + )), + ), + } + } + + fn lookup_fragment(&self, rel_path: &str, fragment: &str) -> FragmentLookup { + if let Some(unit) = self.anchors.get(&(rel_path, fragment.to_string())) { + return FragmentLookup::Unit(*unit); + } + let slug = slugify(fragment); + if !slug.is_empty() { + if let Some(unit) = self.anchors.get(&(rel_path, slug)) { + return FragmentLookup::Unit(*unit); + } + } + let normalized = normalize_heading_name(fragment); + match self.names.get(&(rel_path, normalized)) { + None => FragmentLookup::Missing, + Some(units) if units.len() == 1 => FragmentLookup::Unit(units[0]), + Some(_) => FragmentLookup::Ambiguous, + } + } + + fn resolve_path(&self, from_doc: &str, raw_path: &str) -> PathResolution { + if raw_path.is_empty() { + return PathResolution::SameDocument; + } + let rel = match crate::document::discovery::resolve_link_path(from_doc, raw_path) { + Ok(rel) => rel, + Err(message) => { + if message.contains("escapes") || message.contains("absolute") { + return PathResolution::Outside; + } + return PathResolution::Invalid(message); + } + }; + if self.docs.contains_key(rel.as_str()) { + return PathResolution::Document(rel); + } + if crate::document::DocumentFormat::from_path(&rel).is_some() { + // A Markdown target outside the compiled root: even if the file + // exists it was not indexed; a known missing file is definite. + if self.missing_paths.contains(&rel) && !self.assets.contains_key(rel.as_str()) { + return PathResolution::Missing(rel); + } + return PathResolution::NotLoaded; + } + if self.assets.contains_key(rel.as_str()) { + return PathResolution::Asset(rel); + } + PathResolution::Missing(rel) + } + + fn resolve_import( + &mut self, + fact: &DocumentFacts, + import: &crate::document::ImportFact, + context: Option<&str>, + ) { + let source = self.doc_nodes[fact.rel_path.as_str()].clone(); + let (target, state) = match import.resolved.as_deref() { + Some(module_id) => { + if let Some(rel) = self.modules.get(module_id).copied() { + (Some(self.doc_nodes[rel].clone()), EdgeState::Resolved) + } else { + let key = identity::external_module_key(module_id); + self.register_external( + key.clone(), + module_id, + serde_json::json!({"external_kind": "module", "module_id": module_id}), + ); + (Some(key), EdgeState::Resolved) + } + } + None => (None, EdgeState::Unresolved), + }; + self.push_edge( + source, + target, + EdgeKind::Imports, + EdgeOrigin::Analysis, + import.target.clone(), + Some(import.span), + &fact.rel_path, + state, + context, + ); + } + + fn resolve_call( + &mut self, + fact: &DocumentFacts, + call: &crate::document::CallFact, + context: Option<&str>, + ) { + let Some((owner_rel, owner_unit)) = + self.function_ids.get(call.function_id.as_str()).copied() + else { + self.diagnostics.push( + Diagnostic::error( + code::INTERFACE_CONFLICT, + "call owner function is not present in the compiled facts", + ) + .with_path(&fact.rel_path) + .with_span(call.span), + ); + return; + }; + let source = self.unit_node(owner_rel, owner_unit); + let raw_target = call + .target + .clone() + .unwrap_or_else(|| call.callee.to_string()); + let (target, state) = match call.state.as_str() { + "function" => match call.target.as_deref() { + Some(function_id) if !function_id.is_empty() => { + if let Some((rel, unit)) = self.function_ids.get(function_id).copied() { + (Some(self.unit_node(rel, unit)), EdgeState::Resolved) + } else { + let key = identity::external_function_key(function_id); + self.register_external( + key.clone(), + function_id, + serde_json::json!({ + "external_kind": "function", + "function_id": function_id, + }), + ); + (Some(key), EdgeState::Resolved) + } + } + _ => (None, EdgeState::Unresolved), + }, + "builtin" => match call.target.as_deref() { + Some(name) if !name.is_empty() => { + let key = identity::external_symbol_key("builtin", name); + self.register_external( + key.clone(), + name, + serde_json::json!({"external_kind": "builtin", "name": name}), + ); + (Some(key), EdgeState::Resolved) + } + _ => (None, EdgeState::Unresolved), + }, + "plugin" => match call.target.as_deref() { + Some(name) if !name.is_empty() => { + let key = identity::external_symbol_key("plugin", name); + self.register_external( + key.clone(), + name, + serde_json::json!({ + "external_kind": "plugin", + "export": name, + "owner": call.target_owner, + }), + ); + (Some(key), EdgeState::Resolved) + } + _ => (None, EdgeState::Unresolved), + }, + "unresolved" => { + let state = if call.reason.as_deref() == Some("dynamic") { + EdgeState::Dynamic + } else { + EdgeState::Unresolved + }; + (None, state) + } + other => { + self.diagnostics.push( + Diagnostic::error( + code::INTERFACE_CONFLICT, + format!("unknown call state `{other}`"), + ) + .with_path(&fact.rel_path) + .with_span(call.span), + ); + (None, EdgeState::Unresolved) + } + }; + self.push_edge( + source, + target, + EdgeKind::Calls, + EdgeOrigin::Analysis, + raw_target, + Some(call.span), + &fact.rel_path, + state, + context, + ); + } + + fn reference_diagnostic( + &self, + code: &str, + message: impl Into, + path: &str, + span: Span, + ) -> Diagnostic { + Diagnostic::warning(code, message) + .with_path(path) + .with_span(span) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn external_schemes_are_never_local() { + assert!(matches!( + parse_link("https://example.com/a#b"), + Ok(ParsedLink::External { .. }) + )); + assert!(matches!( + parse_link("mailto:user@example.com"), + Ok(ParsedLink::External { .. }) + )); + assert!(matches!( + parse_link("//example.com/x"), + Ok(ParsedLink::External { .. }) + )); + assert!(matches!( + parse_link("file:///etc/passwd"), + Err(LinkError::OutsideScope) + )); + } + + #[test] + fn local_paths_are_percent_decoded_once() { + let link = parse_link("a%20b.md#x%23y").unwrap(); + match link { + ParsedLink::Local { path, fragment } => { + assert_eq!(path, "a b.md"); + assert_eq!(fragment.as_deref(), Some("x#y")); + } + _ => panic!("expected local link"), + } + assert!(matches!( + parse_link("/etc/passwd"), + Err(LinkError::OutsideScope) + )); + assert!(matches!(parse_link("a%00b.md"), Err(LinkError::Invalid(_)))); + assert!(matches!( + parse_link("../escape.md"), + Ok(ParsedLink::Local { .. }) + )); + } + + #[test] + fn fragment_only_and_empty_links_parse() { + match parse_link("#title").unwrap() { + ParsedLink::Local { path, fragment } => { + assert!(path.is_empty()); + assert_eq!(fragment.as_deref(), Some("title")); + } + _ => panic!(), + } + assert!(matches!( + parse_link("doc.md"), + Ok(ParsedLink::Local { fragment: None, .. }) + )); + } +} diff --git a/src/lib.rs b/src/lib.rs index fb56971..b9e8962 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ pub mod compiler; pub mod diagnostic; pub mod document; pub mod error; +pub mod graph; pub mod model; pub mod query;