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    declaration_line: Option<u32>,
16}
17
18impl SourceSymbolIdentity {
19    /// Creates a language-specific source symbol.
20    #[must_use]
21    pub fn new(
22        repository: RepoId,
23        language: impl Into<String>,
24        source_path: impl Into<String>,
25        symbol: impl Into<String>,
26    ) -> Self {
27        Self {
28            repository,
29            language: Some(language.into().trim().to_ascii_lowercase()),
30            source_path: source_path.into(),
31            symbol: symbol.into(),
32            declaration_line: None,
33        }
34    }
35
36    /// Adds a declaration-line discriminator within a repository revision.
37    #[must_use]
38    pub const fn at_declaration(mut self, line: u32) -> Self {
39        self.declaration_line = Some(line);
40        self
41    }
42
43    /// Declaration line for scoped source identities; absent when the identity has no location.
44    #[must_use]
45    pub const fn declaration_line(&self) -> Option<u32> {
46        self.declaration_line
47    }
48
49    /// Creates a data-only source symbol when no language-specific node exists.
50    #[must_use]
51    pub fn data(
52        repository: RepoId,
53        source_path: impl Into<String>,
54        symbol: impl Into<String>,
55    ) -> Self {
56        Self {
57            repository,
58            language: None,
59            source_path: source_path.into(),
60            symbol: symbol.into(),
61            declaration_line: None,
62        }
63    }
64
65    /// Parses either canonical persisted symbol representation without consulting its display label.
66    #[must_use]
67    pub fn from_node(node: &Node) -> Option<Self> {
68        if node.kind != NodeKind::SymbolRef {
69            return None;
70        }
71        let repository = node.repo_id.clone()?;
72        let scoped_prefix = format!("scoped-symbol:{}:", repository.as_str());
73        if let Some(remainder) = node.stable_key.strip_prefix(&scoped_prefix) {
74            let (line, rest) = remainder.split_once(':')?;
75            let mut legacy = node.clone();
76            legacy.stable_key = format!("symbol:{}:{rest}", repository.as_str());
77            return Some(Self::from_node(&legacy)?.at_declaration(line.parse().ok()?));
78        }
79        let source_prefix = format!("symbol:{}:", repository.as_str());
80        if let Some(remainder) = node.stable_key.strip_prefix(&source_prefix) {
81            let (language, source_identity) = remainder.split_once(':')?;
82            let (source_path, symbol) = source_identity.rsplit_once(':')?;
83            if language.is_empty() || source_path.is_empty() || symbol.is_empty() {
84                return None;
85            }
86            return Some(Self::new(
87                repository,
88                decode_component(language)?,
89                decode_component(source_path)?,
90                decode_component(symbol)?,
91            ));
92        }
93        let data_prefix = format!("data-symbol:{}:", repository.as_str());
94        let source_identity = node.stable_key.strip_prefix(&data_prefix)?;
95        let (source_path, symbol) = source_identity.rsplit_once(':')?;
96        if source_path.is_empty() || symbol.is_empty() {
97            return None;
98        }
99        Some(Self::data(
100            repository,
101            decode_component(source_path)?,
102            decode_component(symbol)?,
103        ))
104    }
105
106    /// Repository owning the source artifact.
107    #[must_use]
108    pub const fn repository(&self) -> &RepoId {
109        &self.repository
110    }
111
112    /// Normalized source language, absent for data-only fallback identities.
113    #[must_use]
114    pub fn language(&self) -> Option<&str> {
115        self.language.as_deref()
116    }
117
118    /// Portable repository-relative source path.
119    #[must_use]
120    pub fn source_path(&self) -> &str {
121        &self.source_path
122    }
123
124    /// Unqualified symbol name observed by the extractor.
125    #[must_use]
126    pub fn symbol(&self) -> &str {
127        &self.symbol
128    }
129
130    /// Unqualified comparison key; ignores language and declaration line.
131    /// This is not sufficient to establish identity between scoped symbols.
132    #[must_use]
133    pub fn location_key(&self) -> (&RepoId, &str, &str) {
134        (&self.repository, &self.source_path, &self.symbol)
135    }
136
137    /// Canonical persisted key.
138    #[must_use]
139    pub fn stable_key(&self) -> String {
140        if let (Some(line), Some(language)) = (self.declaration_line, &self.language) {
141            return format!(
142                "scoped-symbol:{}:{line}:{}:{}:{}",
143                self.repository.as_str(),
144                encode_component(language),
145                encode_component(&self.source_path),
146                encode_component(&self.symbol)
147            );
148        }
149        self.language.as_ref().map_or_else(
150            || {
151                format!(
152                    "data-symbol:{}:{}:{}",
153                    self.repository.as_str(),
154                    encode_component(&self.source_path),
155                    encode_component(&self.symbol)
156                )
157            },
158            |language| {
159                format!(
160                    "symbol:{}:{}:{}:{}",
161                    self.repository.as_str(),
162                    encode_component(language),
163                    encode_component(&self.source_path),
164                    encode_component(&self.symbol)
165                )
166            },
167        )
168    }
169
170    /// Stable node identifier derived from the canonical key.
171    #[must_use]
172    pub fn node_id(&self) -> NodeId {
173        NodeId::new(stable_id("node", &self.stable_key()))
174    }
175
176    /// Creates the persisted graph node while keeping display text separate from identity.
177    #[must_use]
178    pub fn node(&self, label: impl Into<String>) -> Node {
179        Node {
180            id: self.node_id(),
181            kind: NodeKind::SymbolRef,
182            repo_id: Some(self.repository.clone()),
183            stable_key: self.stable_key(),
184            label: label.into(),
185        }
186    }
187}
188
189fn encode_component(value: &str) -> String {
190    value.replace('%', "%25").replace(':', "%3A")
191}
192
193fn decode_component(value: &str) -> Option<String> {
194    let mut remaining = value;
195    let mut decoded = String::with_capacity(value.len());
196    while let Some(index) = remaining.find('%') {
197        decoded.push_str(&remaining[..index]);
198        remaining = &remaining[index..];
199        if let Some(rest) = remaining.strip_prefix("%25") {
200            decoded.push('%');
201            remaining = rest;
202        } else {
203            let rest = remaining.strip_prefix("%3A")?;
204            decoded.push(':');
205            remaining = rest;
206        }
207    }
208    decoded.push_str(remaining);
209    Some(decoded)
210}
211
212#[cfg(test)]
213mod tests {
214    use code_system_graph_model::{NodeKind, RepoId};
215
216    use super::SourceSymbolIdentity;
217
218    #[test]
219    fn scoped_identities_round_trip_and_separate_homonyms() {
220        let first = SourceSymbolIdentity::new(RepoId::new("repo"), "rust", "src/lib.rs", "get")
221            .at_declaration(2);
222        let second = SourceSymbolIdentity::new(RepoId::new("repo"), "rust", "src/lib.rs", "get")
223            .at_declaration(8);
224        assert_ne!(first.node_id(), second.node_id());
225        assert_eq!(
226            SourceSymbolIdentity::from_node(&first.node("get")),
227            Some(first)
228        );
229        assert_eq!(
230            SourceSymbolIdentity::from_node(&second.node("get")),
231            Some(second)
232        );
233    }
234
235    #[test]
236    fn every_supported_language_round_trips_without_using_the_label() {
237        for language in ["javascript", "typescript", "rust", "python", "go", "java"] {
238            let identity = SourceSymbolIdentity::new(
239                RepoId::new("repo:api"),
240                language,
241                "src/nested:module/file.rs",
242                "load_orders",
243            );
244            let mut node = identity.node("an unrelated display label");
245            node.label = "label changes must be harmless".to_owned();
246
247            assert_eq!(SourceSymbolIdentity::from_node(&node), Some(identity));
248        }
249    }
250
251    #[test]
252    fn qualified_symbol_and_delimiter_characters_round_trip_without_ambiguity() {
253        let identity = SourceSymbolIdentity::new(
254            RepoId::new("repo:api"),
255            "rust:async",
256            "src/nested:module/percent%file.rs",
257            "CaféClient::get%checked",
258        );
259
260        assert_eq!(
261            SourceSymbolIdentity::from_node(&identity.node("unrelated")),
262            Some(identity)
263        );
264    }
265
266    #[test]
267    fn data_only_identity_round_trips_and_shares_the_source_location() {
268        let source =
269            SourceSymbolIdentity::new(RepoId::new("repo:api"), "rust", "src/lib.rs", "list_orders");
270        let data = SourceSymbolIdentity::data(RepoId::new("repo:api"), "src/lib.rs", "list_orders");
271
272        assert_eq!(source.location_key(), data.location_key());
273        assert_eq!(
274            SourceSymbolIdentity::from_node(&data.node("anything")),
275            Some(data)
276        );
277    }
278
279    #[test]
280    fn non_symbol_nodes_are_not_parsed_as_source_identities() {
281        let mut node =
282            SourceSymbolIdentity::data(RepoId::new("repo:api"), "src/lib.rs", "list_orders")
283                .node("list_orders");
284        node.kind = NodeKind::Artifact;
285
286        assert!(SourceSymbolIdentity::from_node(&node).is_none());
287    }
288}