1use std::collections::{HashMap, HashSet};
7
8use crate::ir::{ChildNode, VoceIr};
9
10#[derive(Debug, Clone)]
12pub struct NodeEntry {
13 pub path: String,
15 pub type_name: String,
17 pub parent_id: Option<String>,
19}
20
21#[derive(Debug, Default)]
23pub struct NodeIndex {
24 nodes: HashMap<String, NodeEntry>,
26 pub duplicates: Vec<(String, String, String)>, by_type: HashMap<String, Vec<String>>,
30}
31
32impl NodeIndex {
33 pub fn build(ir: &VoceIr) -> Self {
35 let mut index = NodeIndex::default();
36
37 if let Some(ref root) = ir.root {
38 if let Some(ref id) = root.node_id {
39 index.insert(id.clone(), "/root", "ViewRoot", None);
40 }
41
42 if let Some(ref sems) = root.semantic_nodes {
44 for (i, sem) in sems.iter().enumerate() {
45 if let Some(ref id) = sem.node_id {
46 let path = format!("/root/semantic_nodes/{i}");
47 index.insert(id.clone(), &path, "SemanticNode", root.node_id.clone());
48 }
49 }
50 }
51
52 if let Some(ref children) = root.children {
54 index.walk_children(children, "/root/children", root.node_id.clone());
55 }
56 }
57
58 index
59 }
60
61 fn walk_children(
62 &mut self,
63 children: &[ChildNode],
64 parent_path: &str,
65 parent_id: Option<String>,
66 ) {
67 for (i, child) in children.iter().enumerate() {
68 let path = format!("{parent_path}/{i}");
69 let type_name = child.type_name().to_string();
70
71 if let Some(id) = child.node_id() {
72 self.insert(id.clone(), &path, &type_name, parent_id.clone());
73
74 if let Some(grandchildren) = child.children() {
76 let child_path = format!("{path}/children");
77 self.walk_children(&grandchildren, &child_path, Some(id));
78 }
79 }
80 }
81 }
82
83 fn insert(&mut self, id: String, path: &str, type_name: &str, parent_id: Option<String>) {
84 if let Some(existing) = self.nodes.get(&id) {
85 self.duplicates
86 .push((id.clone(), existing.path.clone(), path.to_string()));
87 }
88
89 self.nodes.insert(
90 id.clone(),
91 NodeEntry {
92 path: path.to_string(),
93 type_name: type_name.to_string(),
94 parent_id,
95 },
96 );
97
98 self.by_type
99 .entry(type_name.to_string())
100 .or_default()
101 .push(id);
102 }
103
104 pub fn get(&self, id: &str) -> Option<&NodeEntry> {
106 self.nodes.get(id)
107 }
108
109 pub fn contains(&self, id: &str) -> bool {
111 self.nodes.contains_key(id)
112 }
113
114 pub fn by_type(&self, type_name: &str) -> &[String] {
116 self.by_type.get(type_name).map_or(&[], |v| v.as_slice())
117 }
118
119 pub fn all_ids(&self) -> HashSet<&str> {
121 self.nodes.keys().map(|s| s.as_str()).collect()
122 }
123
124 pub fn path(&self, id: &str) -> &str {
126 self.nodes.get(id).map_or("<unknown>", |e| e.path.as_str())
127 }
128}