Files
marqdo-knowledge/src/graph/resolve.rs
T
marqdo-knowledge 1871ded5ed 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
2026-11-26 00:49:53 +08:00

1085 lines
39 KiB
Rust

//! 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<String>,
},
}
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<ParsedLink, LinkError> {
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<NodeKey>,
pub state: EdgeState,
pub diagnostic: Option<Diagnostic>,
pub external: Option<serde_json::Value>,
pub external_key: Option<NodeKey>,
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<Diagnostic>) -> 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<String>,
anchors: HashMap<(&'a str, String), usize>,
names: HashMap<(&'a str, String), Vec<usize>>,
pub externals: BTreeMap<NodeKey, (String, serde_json::Value)>,
pub edges: Vec<super::Edge>,
pub diagnostics: DiagnosticSet,
}
impl<'a> Resolver<'a> {
pub fn new(
facts: &'a [DocumentFacts],
assets: &'a [AssetFile],
missing_paths: &'a HashSet<String>,
) -> 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<usize>> = 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<super::Node>, Vec<super::Edge>, 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<NodeKey>,
kind: EdgeKind,
origin: EdgeOrigin,
raw_target: String,
span: Option<Span>,
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<String>,
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, .. })
));
}
}