sqry-core 6.0.15

Core library for sqry - semantic code search engine
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Node types for the unified code graph
//!
//! This module defines the core node types that represent code entities
//! (functions, classes, modules, etc.) in the unified graph architecture.

use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::Arc;

/// Language identifier
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub enum Language {
    /// C language
    C,
    /// C++ language
    Cpp,
    /// C# language
    CSharp,
    /// CSS language
    Css,
    /// JavaScript language
    JavaScript,
    /// Python language
    Python,
    /// TypeScript language
    TypeScript,
    /// Rust language
    Rust,
    /// Go language
    Go,
    /// Java language
    Java,
    /// Ruby language
    Ruby,
    /// PHP language
    Php,
    /// Swift language
    Swift,
    /// Kotlin language
    Kotlin,
    /// Scala language
    Scala,
    /// SQL language
    Sql,
    /// Dart language
    Dart,
    /// Lua language
    Lua,
    /// Perl language
    Perl,
    /// Shell (Bash) language
    Shell,
    /// Groovy language
    Groovy,
    /// Elixir language
    Elixir,
    /// R language
    R,
    /// Haskell language
    Haskell,
    /// HTML language
    Html,
    /// Svelte language
    Svelte,
    /// Vue language
    Vue,
    /// Zig language
    Zig,
    /// Terraform (HCL) language
    Terraform,
    /// Puppet language
    Puppet,
    /// Pulumi language
    Pulumi,
    /// Virtual language for HTTP endpoints
    Http,
    /// Oracle PL/SQL language
    Plsql,
    /// Salesforce Apex language
    Apex,
    /// SAP ABAP language
    Abap,
    /// `ServiceNow` (Xanadu) language
    ServiceNow,
    /// JSON configuration files
    Json,
}

impl fmt::Display for Language {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Language::C => write!(f, "c"),
            Language::Cpp => write!(f, "cpp"),
            Language::CSharp => write!(f, "csharp"),
            Language::Css => write!(f, "css"),
            Language::JavaScript => write!(f, "js"),
            Language::Python => write!(f, "py"),
            Language::TypeScript => write!(f, "ts"),
            Language::Rust => write!(f, "rust"),
            Language::Go => write!(f, "go"),
            Language::Java => write!(f, "java"),
            Language::Ruby => write!(f, "ruby"),
            Language::Php => write!(f, "php"),
            Language::Swift => write!(f, "swift"),
            Language::Kotlin => write!(f, "kotlin"),
            Language::Scala => write!(f, "scala"),
            Language::Sql => write!(f, "sql"),
            Language::Dart => write!(f, "dart"),
            Language::Lua => write!(f, "lua"),
            Language::Perl => write!(f, "perl"),
            Language::Shell => write!(f, "shell"),
            Language::Groovy => write!(f, "groovy"),
            Language::Elixir => write!(f, "elixir"),
            Language::R => write!(f, "r"),
            Language::Haskell => write!(f, "haskell"),
            Language::Html => write!(f, "html"),
            Language::Svelte => write!(f, "svelte"),
            Language::Vue => write!(f, "vue"),
            Language::Zig => write!(f, "zig"),
            Language::Terraform => write!(f, "terraform"),
            Language::Puppet => write!(f, "puppet"),
            Language::Pulumi => write!(f, "pulumi"),
            Language::Http => write!(f, "http"),
            Language::Plsql => write!(f, "plsql"),
            Language::Apex => write!(f, "apex"),
            Language::Abap => write!(f, "abap"),
            Language::ServiceNow => write!(f, "servicenow"),
            Language::Json => write!(f, "json"),
        }
    }
}

impl Language {
    /// Parse a language identifier or common alias into a `Language`.
    #[must_use]
    pub fn from_id(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "c" => Some(Self::C),
            "cpp" | "c++" => Some(Self::Cpp),
            "csharp" | "c#" | "cs" => Some(Self::CSharp),
            "css" => Some(Self::Css),
            "javascript" | "js" => Some(Self::JavaScript),
            "python" | "py" => Some(Self::Python),
            "typescript" | "ts" => Some(Self::TypeScript),
            "rust" | "rs" => Some(Self::Rust),
            "go" | "golang" => Some(Self::Go),
            "java" => Some(Self::Java),
            "ruby" | "rb" => Some(Self::Ruby),
            "php" => Some(Self::Php),
            "swift" => Some(Self::Swift),
            "kotlin" | "kt" => Some(Self::Kotlin),
            "scala" => Some(Self::Scala),
            "sql" => Some(Self::Sql),
            "dart" => Some(Self::Dart),
            "lua" => Some(Self::Lua),
            "perl" | "pl" => Some(Self::Perl),
            "shell" | "bash" | "sh" => Some(Self::Shell),
            "groovy" => Some(Self::Groovy),
            "elixir" | "ex" | "exs" => Some(Self::Elixir),
            "r" => Some(Self::R),
            "haskell" | "hs" => Some(Self::Haskell),
            "html" => Some(Self::Html),
            "svelte" => Some(Self::Svelte),
            "vue" => Some(Self::Vue),
            "zig" => Some(Self::Zig),
            "terraform" | "hcl" => Some(Self::Terraform),
            "puppet" => Some(Self::Puppet),
            "pulumi" => Some(Self::Pulumi),
            "http" => Some(Self::Http),
            "plsql" => Some(Self::Plsql),
            "apex" | "salesforce" => Some(Self::Apex),
            "abap" => Some(Self::Abap),
            "servicenow" => Some(Self::ServiceNow),
            "json" => Some(Self::Json),
            _ => None,
        }
    }
}

/// Universal node identifier with string interning for memory efficiency
///
/// Per AGENTS.md:149-151, uses `Arc<str>` to reduce memory usage for
/// symbol-heavy data structures (saves 10-50 MB for typical repos).
///
/// # Examples
///
/// ```
/// use sqry_core::graph::node::{NodeId, Language};
/// use std::sync::Arc;
///
/// let node_id = NodeId::new(
///     Language::Cpp,
///     "src/main.cpp",
///     "main"
/// );
///
/// // Arc<str> makes cloning cheap (only refcount increment)
/// let cloned = node_id.clone();
/// assert_eq!(node_id, cloned);
/// ```
#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct NodeId {
    /// Language of origin
    pub language: Language,
    /// File path (interned via `Arc<str>`)
    pub file: Arc<str>,
    /// Qualified name (interned via `Arc<str>`)
    /// Examples: "`std::vector::push_back`", "MyClass.process", "__main__"
    pub qualified_name: Arc<str>,
}

impl NodeId {
    /// Create a new `NodeId` with string interning
    ///
    /// Automatically interns strings via `Arc<str>` for memory efficiency.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqry_core::graph::node::{NodeId, Language};
    ///
    /// let id = NodeId::new(Language::Python, "api.py", "User.authenticate");
    /// println!("{}", id); // "py:api.py:User.authenticate"
    /// ```
    pub fn new(language: Language, file: impl AsRef<str>, qualified_name: impl AsRef<str>) -> Self {
        Self {
            language,
            file: Arc::from(file.as_ref()),
            qualified_name: Arc::from(qualified_name.as_ref()),
        }
    }

    /// Get the symbol name without namespace qualification
    ///
    /// # Examples
    ///
    /// ```
    /// use sqry_core::graph::node::{NodeId, Language};
    ///
    /// let id = NodeId::new(Language::Cpp, "main.cpp", "std::vector::push_back");
    /// assert_eq!(id.symbol_name(), "push_back");
    /// ```
    #[must_use]
    pub fn symbol_name(&self) -> &str {
        // Try C++ style first (::), then Python/Java style (.)
        if let Some(name) = self.qualified_name.rsplit("::").next()
            && name != self.qualified_name.as_ref()
        {
            return name;
        }

        if let Some(name) = self.qualified_name.rsplit('.').next() {
            return name;
        }

        &self.qualified_name
    }
}

impl fmt::Display for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}:{}:{}", self.language, self.file, self.qualified_name)
    }
}

/// Source code span (line and column information)
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Default, Serialize, Deserialize)]
pub struct Span {
    /// Starting position
    pub start: Position,
    /// Ending position
    pub end: Position,
}

impl Span {
    /// Create a new span
    #[must_use]
    pub fn new(start: Position, end: Position) -> Self {
        Self { start, end }
    }

    /// Create a span from byte offsets (legacy compatibility)
    #[must_use]
    pub fn from_bytes(start: usize, end: usize) -> Self {
        Self {
            start: Position {
                line: 0,
                column: start,
            },
            end: Position {
                line: 0,
                column: end,
            },
        }
    }
}

/// Position in source code (line and column)
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Default, Serialize, Deserialize)]
pub struct Position {
    /// Line number (0-indexed)
    pub line: usize,
    /// Column number (0-indexed)
    pub column: usize,
}

impl Position {
    /// Create a new position
    #[must_use]
    pub fn new(line: usize, column: usize) -> Self {
        Self { line, column }
    }
}

/// Type of code entity
#[derive(Debug, Clone, PartialEq)]
pub enum NodeKind {
    /// Function or method
    Function {
        /// Function parameters
        params: Vec<Param>,
        /// Return type (if known)
        return_type: Option<Type>,
        /// Whether the function is async
        is_async: bool,
    },
    /// Class or struct
    Class {
        /// Base classes
        bases: Vec<NodeId>,
        /// Implemented interfaces
        interfaces: Vec<NodeId>,
    },
    /// Module or namespace
    Module {
        /// Exported symbols
        exports: Vec<NodeId>,
    },
    /// Variable, constant, or field
    Variable {
        /// Variable type (if known)
        var_type: Option<Type>,
    },
}

/// Function parameter
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
    /// Parameter name
    pub name: String,
    /// Parameter type (if known)
    pub param_type: Option<Type>,
}

/// Type information (simplified for now)
#[derive(Debug, Clone, PartialEq)]
pub struct Type {
    /// Type name
    pub name: String,
}

/// Additional metadata for a node
#[derive(Debug, Clone, Default)]
pub struct NodeMetadata {
    /// Visibility (public, private, etc.)
    pub visibility: Option<String>,
    /// Documentation string
    pub doc_comment: Option<String>,
    /// Attributes/decorators
    pub attributes: Vec<String>,
}

/// A node in the code graph representing a code entity
#[derive(Debug, Clone)]
pub struct CodeNode {
    /// Unique identifier
    pub id: NodeId,
    /// Node type (function, class, module, etc.)
    pub kind: NodeKind,
    /// Source location
    pub span: Span,
    /// Additional metadata
    pub metadata: NodeMetadata,
}

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

    #[test]
    fn test_node_id_creation() {
        let id = NodeId::new(Language::Cpp, "src/main.cpp", "main");
        assert_eq!(id.language, Language::Cpp);
        assert_eq!(id.file.as_ref(), "src/main.cpp");
        assert_eq!(id.qualified_name.as_ref(), "main");
    }

    #[test]
    fn test_node_id_display() {
        let id = NodeId::new(Language::Python, "api.py", "User.authenticate");
        assert_eq!(id.to_string(), "py:api.py:User.authenticate");
    }

    #[test]
    fn test_node_id_hash() {
        use std::collections::HashSet;

        let id1 = NodeId::new(Language::JavaScript, "api.js", "fetchUsers");
        let id2 = NodeId::new(Language::JavaScript, "api.js", "fetchUsers");
        let id3 = NodeId::new(Language::JavaScript, "api.js", "createUser");

        let mut set = HashSet::new();
        set.insert(id1.clone());
        set.insert(id2.clone());
        set.insert(id3.clone());

        assert_eq!(set.len(), 2); // id1 and id2 are equal
    }

    #[test]
    fn test_node_id_clone_cheap() {
        let id1 = NodeId::new(Language::Cpp, "src/utils.cpp", "std::vector::push_back");
        let id2 = id1.clone();

        // Arc<str> means the underlying string is NOT copied
        assert_eq!(Arc::as_ptr(&id1.file), Arc::as_ptr(&id2.file));
        assert_eq!(
            Arc::as_ptr(&id1.qualified_name),
            Arc::as_ptr(&id2.qualified_name)
        );
    }

    #[test]
    fn test_symbol_name_extraction() {
        let id1 = NodeId::new(Language::Cpp, "main.cpp", "std::vector::push_back");
        assert_eq!(id1.symbol_name(), "push_back");

        let id2 = NodeId::new(Language::Python, "api.py", "User.authenticate");
        assert_eq!(id2.symbol_name(), "authenticate");

        let id3 = NodeId::new(Language::JavaScript, "api.js", "fetchUsers");
        assert_eq!(id3.symbol_name(), "fetchUsers");
    }

    #[test]
    fn test_span_creation() {
        let span = Span::new(Position::new(10, 0), Position::new(20, 1));

        assert_eq!(span.start.line, 10);
        assert_eq!(span.end.line, 20);
    }

    #[test]
    fn test_language_display() {
        assert_eq!(Language::Cpp.to_string(), "cpp");
        assert_eq!(Language::JavaScript.to_string(), "js");
        assert_eq!(Language::Python.to_string(), "py");
        assert_eq!(Language::Ruby.to_string(), "ruby");
        assert_eq!(Language::Php.to_string(), "php");
        assert_eq!(Language::Swift.to_string(), "swift");
        assert_eq!(Language::Kotlin.to_string(), "kotlin");
        assert_eq!(Language::Scala.to_string(), "scala");
        assert_eq!(Language::Http.to_string(), "http");
    }

    #[test]
    fn test_language_from_id() {
        assert_eq!(Language::from_id("javascript"), Some(Language::JavaScript));
        assert_eq!(Language::from_id("js"), Some(Language::JavaScript));
        assert_eq!(Language::from_id("c#"), Some(Language::CSharp));
        assert_eq!(Language::from_id("rb"), Some(Language::Ruby));
        assert_eq!(Language::from_id("json"), Some(Language::Json));
        assert_eq!(Language::from_id("unknown"), None);
    }
}