1use std::{
5 collections::{BTreeMap, HashMap, HashSet},
6 rc::Rc,
7};
8
9use serde_json::{Map, Value};
10
11use crate::RepoPath;
12
13pub type Fields = Map<String, Value>;
15
16pub type Hydrate = dyn Fn(&RepoPath) -> Option<Fields>;
19
20#[derive(Clone)]
24pub struct Hydrator(pub Rc<Hydrate>);
25
26impl std::fmt::Debug for Hydrator {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 f.write_str("Hydrator")
29 }
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub enum NodeKey {
39 Path(RepoPath),
41 Key(String),
43 Missing(String),
46}
47
48impl NodeKey {
49 pub fn as_str(&self) -> &str {
51 match self {
52 NodeKey::Path(p) => p.as_str(),
53 NodeKey::Key(t) | NodeKey::Missing(t) => t,
54 }
55 }
56
57 pub fn path(&self) -> Option<&RepoPath> {
60 match self {
61 NodeKey::Path(p) => Some(p),
62 NodeKey::Key(_) | NodeKey::Missing(_) => None,
63 }
64 }
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69pub enum NodeKind {
70 Root,
72 Directory,
75 Document,
77 Additional,
79 Asset,
81 File,
84 Key,
86 Missing,
88}
89
90impl NodeKind {
91 pub(super) fn shows_via(self) -> bool {
95 matches!(
96 self,
97 NodeKind::File | NodeKind::Additional | NodeKind::Asset | NodeKind::Directory
98 )
99 }
100
101 pub fn name(self) -> &'static str {
103 match self {
104 NodeKind::Root => "root",
105 NodeKind::Directory => "directory",
106 NodeKind::Document => "document",
107 NodeKind::Additional => "additional",
108 NodeKind::Asset => "asset",
109 NodeKind::File => "file",
110 NodeKind::Key => "key",
111 NodeKind::Missing => "missing",
112 }
113 }
114}
115
116#[derive(Debug, Clone, PartialEq)]
119pub struct Node {
120 pub key: NodeKey,
122 pub kind: NodeKind,
124 pub fields: Map<String, Value>,
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
131pub enum EdgeKind {
132 Includes,
134 Keys,
137 Links,
139 Marker,
141 Resource,
143 Sources,
145}
146
147impl EdgeKind {
148 pub fn name(self) -> &'static str {
150 match self {
151 EdgeKind::Includes => "includes",
152 EdgeKind::Keys => "keys",
153 EdgeKind::Links => "links",
154 EdgeKind::Marker => "marker",
155 EdgeKind::Resource => "resource",
156 EdgeKind::Sources => "sources",
157 }
158 }
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
165pub struct Edge {
166 pub from: NodeKey,
168 pub kind: EdgeKind,
170 pub to: NodeKey,
172 pub rel: String,
174 pub region: Option<String>,
177 pub line: Option<usize>,
179 pub synthesised: bool,
181 pub note: Option<String>,
183}
184
185fn inverse(kind: EdgeKind, rel: &str) -> &'static str {
191 match (kind, rel) {
192 (EdgeKind::Keys, "defined-in") => "defines",
193 (EdgeKind::Keys, "defines") => "defined-in",
194 (EdgeKind::Keys, "cites") => "cited-by",
195 (EdgeKind::Keys, _) => "cites",
196 _ => super::inverse_rel(rel),
197 }
198}
199
200#[derive(Debug, Clone, Default)]
203pub struct Graph {
204 pub nodes: BTreeMap<NodeKey, Node>,
206 pub edges: Vec<Edge>,
208 out: HashMap<NodeKey, Vec<usize>>,
209 inbound: HashMap<NodeKey, Vec<usize>>,
210 hydrator: Option<Hydrator>,
213 hydrated: HashSet<NodeKey>,
215 archived: HashSet<NodeKey>,
217}
218
219impl Graph {
220 pub fn new(nodes: BTreeMap<NodeKey, Node>, mut edges: Vec<Edge>) -> Graph {
225 edges.sort();
226 edges.dedup();
227 let mut out: HashMap<NodeKey, Vec<usize>> = HashMap::new();
228 let mut inbound: HashMap<NodeKey, Vec<usize>> = HashMap::new();
229 for (i, e) in edges.iter().enumerate() {
230 out.entry(e.from.clone()).or_default().push(i);
231 inbound.entry(e.to.clone()).or_default().push(i);
232 }
233 Graph {
234 nodes,
235 edges,
236 out,
237 inbound,
238 hydrator: None,
239 hydrated: HashSet::new(),
240 archived: HashSet::new(),
241 }
242 }
243
244 pub fn set_archived(&mut self, paths: impl IntoIterator<Item = RepoPath>) {
248 self.archived = paths.into_iter().map(NodeKey::Path).collect();
249 }
250
251 pub fn is_archived(&self, key: &NodeKey) -> bool {
254 self.archived.contains(key)
255 }
256
257 pub fn add_key(
262 &mut self,
263 path: &RepoPath,
264 slug: &str,
265 key: &str,
266 line: usize,
267 citing: &[RepoPath],
268 ) {
269 let node = NodeKey::Key(format!("{path}#{slug}"));
270 let mut fields = Map::new();
271 fields.insert("key".into(), Value::from(key));
272 fields.insert("line".into(), Value::from(line));
273 self.nodes.insert(
274 node.clone(),
275 Node {
276 key: node.clone(),
277 kind: NodeKind::Key,
278 fields,
279 },
280 );
281 let doc = NodeKey::Path(path.clone());
282 let pair = |from: &NodeKey, to: &NodeKey, rel: &str| {
283 [false, true].map(|synthesised| {
284 let (from, to, rel) = if synthesised {
285 (to, from, inverse(EdgeKind::Keys, rel))
286 } else {
287 (from, to, rel)
288 };
289 Edge {
290 from: from.clone(),
291 kind: EdgeKind::Keys,
292 to: to.clone(),
293 rel: rel.to_string(),
294 region: None,
295 line: None,
296 synthesised,
297 note: None,
298 }
299 })
300 };
301 let mut edges: Vec<Edge> = pair(&node, &doc, "defined-in").into();
302 for source in citing {
303 edges.extend(pair(&NodeKey::Path(source.clone()), &node, "cites"));
304 }
305 self.extend_edges(edges);
306 }
307
308 pub(super) fn extend_edges(&mut self, edges: Vec<Edge>) {
312 let mut all = std::mem::take(&mut self.edges);
313 all.extend(edges);
314 let rebuilt = Graph::new(BTreeMap::new(), all);
315 self.edges = rebuilt.edges;
316 self.out = rebuilt.out;
317 self.inbound = rebuilt.inbound;
318 }
319
320 #[must_use]
325 pub fn with_hydrator(mut self, hydrator: Hydrator, built: HashSet<NodeKey>) -> Graph {
326 self.hydrator = Some(hydrator);
327 self.hydrated = built;
328 self
329 }
330
331 pub fn hydrate(&mut self, key: &NodeKey) {
335 let Some(hydrator) = &self.hydrator else {
336 return;
337 };
338 if self.hydrated.contains(key) {
339 return;
340 }
341 let Some(node) = self.nodes.get_mut(key) else {
342 return;
343 };
344 if node.kind != NodeKind::Document {
345 return;
346 }
347 if let Some(path) = key.path()
348 && let Some(fields) = (hydrator.0)(path)
349 {
350 node.fields = fields;
351 }
352 self.hydrated.insert(key.clone());
353 }
354
355 pub fn node(&self, key: &NodeKey) -> Option<&Node> {
357 self.nodes.get(key)
358 }
359
360 pub fn kind(&self, key: &NodeKey) -> Option<NodeKind> {
362 self.nodes.get(key).map(|n| n.kind)
363 }
364
365 pub fn edges_from(&self, key: &NodeKey) -> impl Iterator<Item = &Edge> {
367 self.edge_indices_from(key).iter().map(|&i| &self.edges[i])
368 }
369
370 pub fn edge_indices_from(&self, key: &NodeKey) -> &[usize] {
373 self.out.get(key).map(Vec::as_slice).unwrap_or_default()
374 }
375
376 pub fn inverse_indices(&self, edge: &Edge) -> impl Iterator<Item = usize> {
388 self.inbound
389 .get(&edge.from)
390 .into_iter()
391 .flatten()
392 .copied()
393 .filter(move |&i| {
394 let other = &self.edges[i];
395 other.from == edge.to
396 && other.kind == edge.kind
397 && other.region == edge.region
398 && other.line == edge.line
399 && (other.rel == inverse(edge.kind, &edge.rel)
400 || inverse(other.kind, &other.rel) == edge.rel)
401 })
402 }
403
404 pub fn parent(key: &NodeKey) -> Option<NodeKey> {
407 key.path()?.parent().map(NodeKey::Path)
408 }
409
410 pub fn ensure(&mut self, path: RepoPath, kind: NodeKind) {
416 let key = NodeKey::Path(path);
417 self.nodes
418 .entry(key.clone())
419 .and_modify(|n| n.kind = kind)
420 .or_insert_with(|| Node {
421 key,
422 kind,
423 fields: Map::new(),
424 });
425 }
426}
427
428pub(super) fn ancestors(path: &RepoPath) -> impl Iterator<Item = RepoPath> {
430 std::iter::successors(path.parent(), RepoPath::parent)
431}
432
433#[cfg(test)]
434mod tests {
435 use super::*;
436
437 fn p(s: &str) -> NodeKey {
438 NodeKey::Path(RepoPath::parse(s).unwrap())
439 }
440
441 fn edge(from: &NodeKey, kind: EdgeKind, to: &NodeKey, rel: &str, synthesised: bool) -> Edge {
442 Edge {
443 from: from.clone(),
444 kind,
445 to: to.clone(),
446 rel: rel.into(),
447 region: None,
448 line: None,
449 synthesised,
450 note: None,
451 }
452 }
453
454 #[test]
456 fn keys_order_paths_before_missing_targets() {
457 let mut keys = vec![
458 NodeKey::Missing("a".into()),
459 p("/z.md"),
460 p("/a.md"),
461 NodeKey::Missing("b".into()),
462 ];
463 keys.sort();
464 assert_eq!(
465 keys,
466 vec![
467 p("/a.md"),
468 p("/z.md"),
469 NodeKey::Missing("a".into()),
470 NodeKey::Missing("b".into())
471 ]
472 );
473 assert_eq!(p("/a.md").as_str(), "/a.md");
474 assert_eq!(NodeKey::Missing("x".into()).as_str(), "x");
475 assert!(NodeKey::Missing("x".into()).path().is_none());
476 assert_eq!(Graph::parent(&p("/k/a.md")), Some(p("/k")));
477 assert_eq!(Graph::parent(&p("/")), None);
478 assert_eq!(Graph::parent(&NodeKey::Missing("x".into())), None);
479 }
480
481 #[test]
484 fn edges_sort_by_from_kind_to_rel_region_note_and_dedup() {
485 let a = p("/a.md");
486 let b = p("/b.md");
487 let m = NodeKey::Missing("m".into());
488 let mut edges = vec![
489 edge(&b, EdgeKind::Links, &a, "depends-on", false),
490 edge(&a, EdgeKind::Resource, &b, "describes", false),
491 edge(&a, EdgeKind::Links, &m, "references", false),
492 edge(&a, EdgeKind::Links, &b, "references", false),
493 edge(&a, EdgeKind::Includes, &b, "includes", false),
494 edge(&a, EdgeKind::Links, &b, "depends-on", false),
495 edge(&a, EdgeKind::Links, &b, "depends-on", false),
496 ];
497 let g = Graph::new(BTreeMap::new(), std::mem::take(&mut edges));
498 let shown: Vec<String> = g
499 .edges
500 .iter()
501 .map(|e| {
502 format!(
503 "{} {} {} {}",
504 e.from.as_str(),
505 e.kind.name(),
506 e.to.as_str(),
507 e.rel
508 )
509 })
510 .collect();
511 assert_eq!(
512 shown,
513 vec![
514 "/a.md includes /b.md includes",
515 "/a.md links /b.md depends-on",
516 "/a.md links /b.md references",
517 "/a.md links m references",
518 "/a.md resource /b.md describes",
519 "/b.md links /a.md depends-on",
520 ]
521 );
522 assert_eq!(g.edges_from(&a).count(), 5);
523 assert_eq!(g.edge_indices_from(&b), &[5]);
524 assert_eq!(g.edge_indices_from(&m), [] as [usize; 0]);
525 assert_eq!(EdgeKind::Sources.name(), "sources");
526 }
527
528 #[test]
529 fn inverses_find_the_declared_or_synthesised_side_and_every_custom_rel() {
530 let a = p("/a.md");
531 let b = p("/b.md");
532 let c = p("/c.md");
533 let g = Graph::new(
534 BTreeMap::new(),
535 vec![
536 edge(&a, EdgeKind::Links, &b, "depends-on", false),
537 edge(&b, EdgeKind::Links, &a, "depended-on-by", true),
538 edge(&a, EdgeKind::Links, &c, "likes", false),
539 edge(&a, EdgeKind::Links, &c, "hates", false),
540 edge(&c, EdgeKind::Links, &a, "relates-to", false),
541 edge(&b, EdgeKind::Resource, &c, "describes", false),
542 ],
543 );
544 let rels = |e: &Edge| {
545 g.inverse_indices(e)
546 .map(|i| g.edges[i].rel.clone())
547 .collect::<Vec<_>>()
548 };
549 let declared = &g.edges[g.edge_indices_from(&a)[0]];
550 assert_eq!(declared.rel, "depends-on");
551 assert_eq!(rels(declared), vec!["depended-on-by"]);
552 let relates = g.edges.iter().find(|e| e.rel == "relates-to").unwrap();
553 assert_eq!(rels(relates), vec!["hates", "likes"]);
554 let custom = g.edges.iter().find(|e| e.rel == "likes").unwrap();
555 assert_eq!(rels(custom), vec!["relates-to"]);
556 let lone = g.edges.iter().find(|e| e.rel == "describes").unwrap();
557 assert_eq!(rels(lone), Vec::<String>::new());
558 }
559
560 #[test]
561 fn ensure_adds_or_rekinds_a_node() {
562 let mut g = Graph::default();
563 let path = RepoPath::parse("/src").unwrap();
564 g.ensure(path.clone(), NodeKind::File);
565 assert_eq!(g.kind(&p("/src")), Some(NodeKind::File));
566 g.ensure(path, NodeKind::Directory);
567 assert_eq!(g.kind(&p("/src")), Some(NodeKind::Directory));
568 assert_eq!(g.nodes.len(), 1);
569 assert!(g.node(&p("/nope")).is_none());
570 assert_eq!(NodeKind::Additional.name(), "additional");
571 }
572}