Skip to main content

voce_validator/
index.rs

1//! Node index — fast lookup structure built from the deserialized IR tree.
2//!
3//! Built by a single recursive walk of the IR after deserialization.
4//! Provides O(1) lookup by node ID and node type filtering.
5
6use std::collections::{HashMap, HashSet};
7
8use crate::ir::{ChildNode, VoceIr};
9
10/// Entry for a single node in the index.
11#[derive(Debug, Clone)]
12pub struct NodeEntry {
13    /// JSON-pointer-style path (e.g., "/root/children/0").
14    pub path: String,
15    /// Node type name (e.g., "Container", "TextNode").
16    pub type_name: String,
17    /// Parent node ID (None for ViewRoot).
18    pub parent_id: Option<String>,
19}
20
21/// Fast lookup index over the IR tree.
22#[derive(Debug, Default)]
23pub struct NodeIndex {
24    /// node_id -> NodeEntry
25    nodes: HashMap<String, NodeEntry>,
26    /// Duplicate node_ids found during indexing.
27    pub duplicates: Vec<(String, String, String)>, // (id, path1, path2)
28    /// All node IDs of a given type.
29    by_type: HashMap<String, Vec<String>>,
30}
31
32impl NodeIndex {
33    /// Build the index from a deserialized IR document.
34    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            // Index semantic nodes
43            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            // Index children recursively
53            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                // Recurse into children if present
75                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    /// Look up a node by ID.
105    pub fn get(&self, id: &str) -> Option<&NodeEntry> {
106        self.nodes.get(id)
107    }
108
109    /// Check if a node ID exists.
110    pub fn contains(&self, id: &str) -> bool {
111        self.nodes.contains_key(id)
112    }
113
114    /// Get all node IDs of a given type.
115    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    /// Get all node IDs.
120    pub fn all_ids(&self) -> HashSet<&str> {
121        self.nodes.keys().map(|s| s.as_str()).collect()
122    }
123
124    /// Get the path for a node ID (for diagnostic messages).
125    pub fn path(&self, id: &str) -> &str {
126        self.nodes.get(id).map_or("<unknown>", |e| e.path.as_str())
127    }
128}