splice 2.6.2

Span-safe refactoring kernel for 7 languages with Magellan code graph integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! SQLite backend implementation.
//!
//! This module provides the CodeIntelBackend trait implementation
//! for SQLite databases via sqlitegraph.

use super::router::BackendType;
use crate::error::{Result, SpliceError};
use crate::symbol::Language;
use sqlitegraph::{GraphBackend, NodeId, NodeSpec, SnapshotId};
use std::collections::HashMap;
use std::path::Path;

/// SQLite code graph implementation.
///
/// Wraps sqlitegraph's GraphBackend and provides the CodeIntelBackend
/// trait implementation for Splice workflows.
pub struct CodeGraphSqlite {
    /// The underlying sqlitegraph backend
    backend: Box<dyn GraphBackend>,
    /// Cache for symbol name → Vec<NodeId> mapping
    symbol_cache: HashMap<String, Vec<NodeId>>,
    /// Cache for file path → NodeId mapping
    file_cache: HashMap<String, NodeId>,
    /// Database path
    db_path: std::path::PathBuf,
}

impl CodeGraphSqlite {
    /// Open or create a SQLite-backed code graph.
    pub fn open(path: &Path) -> Result<Self> {
        // Handle empty files
        if let Ok(metadata) = std::fs::metadata(path) {
            if metadata.len() == 0 {
                std::fs::remove_file(path).map_err(|e| {
                    SpliceError::Other(format!(
                        "Failed to remove empty graph database {:?}: {}",
                        path, e
                    ))
                })?;
            }
        }

        let config = sqlitegraph::GraphConfig::sqlite();

        let backend = sqlitegraph::open_graph(path, &config).map_err(|e| {
            SpliceError::Other(format!("Failed to open SQLite graph at {:?}: {}", path, e))
        })?;

        Ok(Self {
            backend,
            symbol_cache: HashMap::new(),
            file_cache: HashMap::new(),
            db_path: path.to_path_buf(),
        })
    }

    /// Access the underlying sqlitegraph backend.
    pub fn inner(&self) -> &dyn GraphBackend {
        self.backend.as_ref()
    }

    /// Access the underlying sqlitegraph backend mutably.
    pub fn inner_mut(&mut self) -> &mut dyn GraphBackend {
        self.backend.as_mut()
    }

    /// Get the database path.
    pub fn db_path(&self) -> &Path {
        &self.db_path
    }

    /// Store a file node in the graph.
    fn store_file_node(&mut self, file_path: &Path) -> Result<NodeId> {
        let file_path_str = file_path
            .to_str()
            .ok_or_else(|| SpliceError::Other(format!("Invalid UTF-8 in path: {:?}", file_path)))?;

        // Check cache first
        if let Some(&node_id) = self.file_cache.get(file_path_str) {
            return Ok(node_id);
        }

        use serde_json::json;
        let node = NodeSpec {
            kind: "File".to_string(),
            name: file_path_str.to_string(),
            file_path: Some(file_path_str.to_string()),
            data: json!({
                "file_path": file_path_str,
                "language": "unknown"
            }),
        };

        let node_id_i64 = self
            .backend
            .insert_node(node)
            .map_err(|e| SpliceError::Other(format!("Failed to store file node: {}", e)))?;
        let node_id = NodeId(node_id_i64);

        self.file_cache.insert(file_path_str.to_string(), node_id);
        Ok(node_id)
    }
}

// Inherent methods that match the CodeIntelBackend trait
impl CodeGraphSqlite {
    pub fn find_symbol_in_file(&self, file_path: &str, name: &str) -> Option<NodeId> {
        // Check cache first
        let cache_key = format!("{}::{}", file_path, name);
        if let Some(ids) = self.symbol_cache.get(&cache_key) {
            return ids.first().copied();
        }

        // Query database
        let snapshot = SnapshotId(0);
        let all_ids = match self.backend.entity_ids() {
            Ok(ids) => ids,
            Err(_) => return None,
        };

        for node_id in all_ids {
            if let Ok(node) = self.backend.get_node(snapshot, node_id) {
                if node.name == name {
                    // In Magellan 3.1+, file_path is in node.file_path, not node.data
                    if let Some(node_file) = node.file_path.as_deref() {
                        if node_file == file_path {
                            return Some(NodeId(node_id));
                        }
                    }
                }
            }
        }

        None
    }

    pub fn find_symbols_by_name(&self, name: &str) -> Vec<(NodeId, Option<String>)> {
        let mut results = Vec::new();
        let snapshot = SnapshotId(0);

        let all_ids = match self.backend.entity_ids() {
            Ok(ids) => ids,
            Err(_) => return results,
        };

        for node_id in all_ids {
            if let Ok(node) = self.backend.get_node(snapshot, node_id) {
                if node.name == name {
                    let file_path = node
                        .data
                        .get("file_path")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    results.push((NodeId(node_id), file_path));
                }
            }
        }

        results
    }

    pub fn all_symbol_names(&self) -> Vec<String> {
        use std::collections::HashSet;
        let mut names = HashSet::new();

        // Collect from cache
        for key in self.symbol_cache.keys() {
            if let Some(name) = key.split("::").last() {
                names.insert(name.to_string());
            } else {
                names.insert(key.clone());
            }
        }

        // Collect from database
        if let Ok(all_ids) = self.backend.entity_ids() {
            let snapshot = SnapshotId(0);
            for node_id in all_ids {
                if let Ok(node) = self.backend.get_node(snapshot, node_id) {
                    if node.kind != "File" && node.kind != "file" {
                        names.insert(node.name);
                    }
                }
            }
        }

        names.into_iter().collect()
    }

    pub fn get_span(&self, node_id: NodeId) -> Result<(usize, usize)> {
        let node = self
            .backend
            .get_node(SnapshotId(0), node_id.as_i64())
            .map_err(|e| SpliceError::Other(format!("Failed to get node: {}", e)))?;

        let byte_start = node
            .data
            .get("byte_start")
            .and_then(|v| v.as_u64())
            .ok_or_else(|| SpliceError::Other("Missing byte_start property".to_string()))?
            as usize;

        let byte_end = node
            .data
            .get("byte_end")
            .and_then(|v| v.as_u64())
            .ok_or_else(|| SpliceError::Other("Missing byte_end property".to_string()))?
            as usize;

        Ok((byte_start, byte_end))
    }

    pub fn store_symbol(
        &mut self,
        name: &str,
        kind: &str,
        language: Language,
        byte_start: usize,
        byte_end: usize,
        line_start: usize,
        line_end: usize,
        col_start: usize,
        col_end: usize,
    ) -> Result<NodeId> {
        use serde_json::json;
        let node = NodeSpec {
            kind: kind.to_string(),
            name: name.to_string(),
            file_path: None,
            data: json!({
                "byte_start": byte_start,
                "byte_end": byte_end,
                "line_start": line_start,
                "line_end": line_end,
                "col_start": col_start,
                "col_end": col_end,
                "language": language.as_str(),
                "kind": kind
            }),
        };

        let node_id_i64 = self
            .backend
            .insert_node(node)
            .map_err(|e| SpliceError::Other(format!("Failed to store symbol: {}", e)))?;
        let node_id = NodeId(node_id_i64);

        // Update cache
        self.symbol_cache
            .entry(name.to_string())
            .or_default()
            .push(node_id);

        Ok(node_id)
    }

    pub fn store_symbol_with_file_and_language(
        &mut self,
        file_path: &Path,
        name: &str,
        kind: &str,
        language: Language,
        byte_start: usize,
        byte_end: usize,
        line_start: usize,
        line_end: usize,
        col_start: usize,
        col_end: usize,
    ) -> Result<NodeId> {
        // Ensure file node exists
        let _file_node_id = self.store_file_node(file_path)?;

        let file_path_str = file_path
            .to_str()
            .ok_or_else(|| SpliceError::Other(format!("Invalid UTF-8 in path: {:?}", file_path)))?;

        use serde_json::json;
        let node = NodeSpec {
            kind: kind.to_string(),
            name: name.to_string(),
            file_path: Some(file_path_str.to_string()),
            data: json!({
                "byte_start": byte_start,
                "byte_end": byte_end,
                "line_start": line_start,
                "line_end": line_end,
                "col_start": col_start,
                "col_end": col_end,
                "file_path": file_path_str,
                "language": language.as_str(),
                "kind": kind
            }),
        };

        let node_id_i64 = self
            .backend
            .insert_node(node)
            .map_err(|e| SpliceError::Other(format!("Failed to store symbol: {}", e)))?;
        let node_id = NodeId(node_id_i64);

        // Update caches
        let cache_key = format!("{}::{}", file_path_str, name);
        self.symbol_cache
            .entry(cache_key)
            .or_default()
            .push(node_id);
        self.symbol_cache
            .entry(name.to_string())
            .or_default()
            .push(node_id);

        Ok(node_id)
    }

    pub fn backend_type(&self) -> BackendType {
        BackendType::SQLite
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::NamedTempFile;

    #[test]
    fn test_sqlite_backend_open() {
        let temp_file = NamedTempFile::new().unwrap();
        let path = temp_file.path();

        let graph = CodeGraphSqlite::open(path).unwrap();
        assert!(matches!(graph.backend_type(), BackendType::SQLite));
    }

    #[test]
    fn test_sqlite_store_and_find_symbol() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut graph = CodeGraphSqlite::open(temp_file.path()).unwrap();

        let file_path = Path::new("src/test.rs");
        let node_id = graph
            .store_symbol_with_file_and_language(
                file_path,
                "test_function",
                "function",
                Language::Rust,
                100, // byte_start
                200, // byte_end
                10,  // line_start
                20,  // line_end
                4,   // col_start
                0,   // col_end
            )
            .unwrap();

        // Find by name in file
        let found = graph.find_symbol_in_file("src/test.rs", "test_function");
        assert_eq!(found, Some(node_id));

        // Get span
        let (start, end) = graph.get_span(node_id).unwrap();
        assert_eq!(start, 100);
        assert_eq!(end, 200);
    }

    #[test]
    fn test_sqlite_find_symbols_by_name() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut graph = CodeGraphSqlite::open(temp_file.path()).unwrap();

        // Store same name in different files
        graph
            .store_symbol_with_file_and_language(
                Path::new("src/a.rs"),
                "common",
                "function",
                Language::Rust,
                0,
                10,
                1,
                1,
                0,
                0,
            )
            .unwrap();

        graph
            .store_symbol_with_file_and_language(
                Path::new("src/b.rs"),
                "common",
                "function",
                Language::Rust,
                0,
                10,
                1,
                1,
                0,
                0,
            )
            .unwrap();

        let matches = graph.find_symbols_by_name("common");
        assert_eq!(matches.len(), 2);
    }
}