Skip to main content

code_system_graph_core/
source_symbol.rs

1//! Canonical persisted identity for source-level symbols.
2
3use code_system_graph_model::{Node, NodeId, NodeKind, RepoId, stable_id};
4
5/// Typed identity shared by source, data, corroboration, and Explore projections.
6///
7/// `language` is absent only for a data-only symbol whose source parser did not emit a language-
8/// specific symbol. Callers compare [`Self::location_key`] when they need to join those two views.
9#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub struct SourceSymbolIdentity {
11    repository: RepoId,
12    language: Option<String>,
13    source_path: String,
14    symbol: String,
15}
16
17impl SourceSymbolIdentity {
18    /// Creates a language-specific source symbol.
19    #[must_use]
20    pub fn new(
21        repository: RepoId,
22        language: impl Into<String>,
23        source_path: impl Into<String>,
24        symbol: impl Into<String>,
25    ) -> Self {
26        Self {
27            repository,
28            language: Some(language.into().trim().to_ascii_lowercase()),
29            source_path: source_path.into(),
30            symbol: symbol.into(),
31        }
32    }
33
34    /// Creates a data-only source symbol when no language-specific node exists.
35    #[must_use]
36    pub fn data(
37        repository: RepoId,
38        source_path: impl Into<String>,
39        symbol: impl Into<String>,
40    ) -> Self {
41        Self {
42            repository,
43            language: None,
44            source_path: source_path.into(),
45            symbol: symbol.into(),
46        }
47    }
48
49    /// Parses either canonical persisted symbol representation without consulting its display label.
50    #[must_use]
51    pub fn from_node(node: &Node) -> Option<Self> {
52        if node.kind != NodeKind::SymbolRef {
53            return None;
54        }
55        let repository = node.repo_id.clone()?;
56        let source_prefix = format!("symbol:{}:", repository.as_str());
57        if let Some(remainder) = node.stable_key.strip_prefix(&source_prefix) {
58            let (language, source_identity) = remainder.split_once(':')?;
59            let (source_path, symbol) = source_identity.rsplit_once(':')?;
60            if language.is_empty() || source_path.is_empty() || symbol.is_empty() {
61                return None;
62            }
63            return Some(Self::new(
64                repository,
65                decode_component(language)?,
66                decode_component(source_path)?,
67                decode_component(symbol)?,
68            ));
69        }
70        let data_prefix = format!("data-symbol:{}:", repository.as_str());
71        let source_identity = node.stable_key.strip_prefix(&data_prefix)?;
72        let (source_path, symbol) = source_identity.rsplit_once(':')?;
73        if source_path.is_empty() || symbol.is_empty() {
74            return None;
75        }
76        Some(Self::data(
77            repository,
78            decode_component(source_path)?,
79            decode_component(symbol)?,
80        ))
81    }
82
83    /// Repository owning the source artifact.
84    #[must_use]
85    pub const fn repository(&self) -> &RepoId {
86        &self.repository
87    }
88
89    /// Normalized source language, absent for data-only fallback identities.
90    #[must_use]
91    pub fn language(&self) -> Option<&str> {
92        self.language.as_deref()
93    }
94
95    /// Portable repository-relative source path.
96    #[must_use]
97    pub fn source_path(&self) -> &str {
98        &self.source_path
99    }
100
101    /// Unqualified symbol name observed by the extractor.
102    #[must_use]
103    pub fn symbol(&self) -> &str {
104        &self.symbol
105    }
106
107    /// Stable comparison key that deliberately ignores the optional language dimension.
108    #[must_use]
109    pub fn location_key(&self) -> (&RepoId, &str, &str) {
110        (&self.repository, &self.source_path, &self.symbol)
111    }
112
113    /// Canonical persisted key.
114    #[must_use]
115    pub fn stable_key(&self) -> String {
116        self.language.as_ref().map_or_else(
117            || {
118                format!(
119                    "data-symbol:{}:{}:{}",
120                    self.repository.as_str(),
121                    encode_component(&self.source_path),
122                    encode_component(&self.symbol)
123                )
124            },
125            |language| {
126                format!(
127                    "symbol:{}:{}:{}:{}",
128                    self.repository.as_str(),
129                    encode_component(language),
130                    encode_component(&self.source_path),
131                    encode_component(&self.symbol)
132                )
133            },
134        )
135    }
136
137    /// Stable node identifier derived from the canonical key.
138    #[must_use]
139    pub fn node_id(&self) -> NodeId {
140        NodeId::new(stable_id("node", &self.stable_key()))
141    }
142
143    /// Creates the persisted graph node while keeping display text separate from identity.
144    #[must_use]
145    pub fn node(&self, label: impl Into<String>) -> Node {
146        Node {
147            id: self.node_id(),
148            kind: NodeKind::SymbolRef,
149            repo_id: Some(self.repository.clone()),
150            stable_key: self.stable_key(),
151            label: label.into(),
152        }
153    }
154}
155
156fn encode_component(value: &str) -> String {
157    value.replace('%', "%25").replace(':', "%3A")
158}
159
160fn decode_component(value: &str) -> Option<String> {
161    let mut remaining = value;
162    let mut decoded = String::with_capacity(value.len());
163    while let Some(index) = remaining.find('%') {
164        decoded.push_str(&remaining[..index]);
165        remaining = &remaining[index..];
166        if let Some(rest) = remaining.strip_prefix("%25") {
167            decoded.push('%');
168            remaining = rest;
169        } else {
170            let rest = remaining.strip_prefix("%3A")?;
171            decoded.push(':');
172            remaining = rest;
173        }
174    }
175    decoded.push_str(remaining);
176    Some(decoded)
177}
178
179#[cfg(test)]
180mod tests {
181    use code_system_graph_model::{NodeKind, RepoId};
182
183    use super::SourceSymbolIdentity;
184
185    #[test]
186    fn every_supported_language_round_trips_without_using_the_label() {
187        for language in ["javascript", "typescript", "rust", "python", "go", "java"] {
188            let identity = SourceSymbolIdentity::new(
189                RepoId::new("repo:api"),
190                language,
191                "src/nested:module/file.rs",
192                "load_orders",
193            );
194            let mut node = identity.node("an unrelated display label");
195            node.label = "label changes must be harmless".to_owned();
196
197            assert_eq!(SourceSymbolIdentity::from_node(&node), Some(identity));
198        }
199    }
200
201    #[test]
202    fn qualified_symbol_and_delimiter_characters_round_trip_without_ambiguity() {
203        let identity = SourceSymbolIdentity::new(
204            RepoId::new("repo:api"),
205            "rust:async",
206            "src/nested:module/percent%file.rs",
207            "CaféClient::get%checked",
208        );
209
210        assert_eq!(
211            SourceSymbolIdentity::from_node(&identity.node("unrelated")),
212            Some(identity)
213        );
214    }
215
216    #[test]
217    fn data_only_identity_round_trips_and_shares_the_source_location() {
218        let source =
219            SourceSymbolIdentity::new(RepoId::new("repo:api"), "rust", "src/lib.rs", "list_orders");
220        let data = SourceSymbolIdentity::data(RepoId::new("repo:api"), "src/lib.rs", "list_orders");
221
222        assert_eq!(source.location_key(), data.location_key());
223        assert_eq!(
224            SourceSymbolIdentity::from_node(&data.node("anything")),
225            Some(data)
226        );
227    }
228
229    #[test]
230    fn non_symbol_nodes_are_not_parsed_as_source_identities() {
231        let mut node =
232            SourceSymbolIdentity::data(RepoId::new("repo:api"), "src/lib.rs", "list_orders")
233                .node("list_orders");
234        node.kind = NodeKind::Artifact;
235
236        assert!(SourceSymbolIdentity::from_node(&node).is_none());
237    }
238}