codesearch 0.1.12

A fast, intelligent CLI tool with multiple search modes (regex, fuzzy, semantic), code analysis, and dead code detection for popular programming languages
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
//! Advanced Symbol Extraction and Indexing
//!
//! This module provides comprehensive symbol extraction for AI agent consumption.
//! It captures rich structural information including signatures, relationships,
//! hierarchies, and context without using LLM.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

#[cfg(feature = "mcp")]
use schemars::JsonSchema;

pub mod extractor;
pub mod indexer;
pub mod relationships;
pub mod context;

pub use extractor::{SymbolExtractor, extract_symbols_from_file};
pub use indexer::{SymbolIndex, SymbolIndexStore};
pub use relationships::RelationshipGraph;
pub use context::SymbolContext;

/// Comprehensive symbol information with rich metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub struct Symbol {
    /// Unique identifier for the symbol
    pub id: String,

    /// Symbol name
    pub name: String,

    /// Symbol kind (function, class, method, variable, etc.)
    pub kind: SymbolKind,

    /// File path where symbol is defined
    pub file_path: String,

    /// Line number where symbol is defined
    pub line: usize,

    /// Column number where symbol is defined
    pub column: usize,

    /// End line number
    pub end_line: usize,

    /// Full signature with parameters and return types
    pub signature: String,

    /// Documentation comment (if any)
    pub documentation: Option<String>,

    /// Visibility (public, private, protected, etc.)
    pub visibility: SymbolVisibility,

    /// Parent symbol (for methods, nested classes, etc.)
    pub parent: Option<String>,

    /// Type information (if applicable)
    pub type_info: Option<TypeInfo>,

    /// Generic parameters (if applicable)
    pub generics: Vec<String>,

    /// Annotations/decorators
    pub annotations: Vec<String>,

    /// Attributes/modifiers
    pub attributes: Vec<String>,

    /// Language-specific metadata
    pub metadata: HashMap<String, String>,
}

/// Symbol kind classification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub enum SymbolKind {
    // Top-level declarations
    Module,
    Package,
    Namespace,

    // Types
    Class,
    Interface,
    Trait,
    Struct,
    Enum,
    Union,
    TypeAlias,

    // Functions
    Function,
    Method,
    Constructor,
    Destructor,

    // Variables
    Variable,
    Field,
    Property,
    Parameter,
    Constant,

    // Other
    Macro,
    Import,
    Export,
    Unknown,
}

/// Visibility modifiers
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub enum SymbolVisibility {
    Public,
    Private,
    Protected,
    Internal,
    PackagePrivate,
    FilePrivate,
    None,
}

/// Type information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub struct TypeInfo {
    /// Type name
    pub name: String,

    /// Type parameters
    pub parameters: Vec<String>,

    /// Return type (for functions)
    pub return_type: Option<Box<TypeInfo>>,

    /// Is nullable/optional
    pub nullable: bool,

    /// Type kind (primitive, object, array, etc.)
    pub kind: TypeKind,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub enum TypeKind {
    Primitive,
    Object,
    Array,
    Map,
    Tuple,
    Function,
    Union,
    Intersection,
    Unknown,
}

/// File-level symbol information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileSymbols {
    /// File path
    pub path: String,

    /// Language
    pub language: String,

    /// All symbols in this file
    pub symbols: Vec<Symbol>,

    /// Import statements
    pub imports: Vec<ImportInfo>,

    /// Export statements
    pub exports: Vec<ExportInfo>,

    /// File-level documentation
    pub file_doc: Option<String>,
}

/// Import information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportInfo {
    /// Import path/module
    pub path: String,

    /// Imported symbols (if specific)
    pub symbols: Vec<String>,

    /// Alias (if renamed)
    pub alias: Option<String>,

    /// Is wildcard import
    pub is_wildcard: bool,

    /// Line number
    pub line: usize,
}

/// Export information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportInfo {
    /// Exported symbol name
    pub name: String,

    /// Alias (if renamed)
    pub alias: Option<String>,

    /// Line number
    pub line: usize,
}

/// Symbol search result with context
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub struct SymbolSearchResult {
    /// The matching symbol
    pub symbol: Symbol,

    /// Relevance score (0-100)
    pub score: f64,

    /// Context lines before the symbol
    pub context_before: Vec<String>,

    /// Context lines after the symbol
    pub context_after: Vec<String>,

    /// Related symbols
    pub related_symbols: Vec<SymbolRelation>,
}

/// Relationship between symbols
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub struct SymbolRelation {
    /// Related symbol ID
    pub symbol_id: String,

    /// Relationship type
    pub relation_type: SymbolRelationType,

    /// Confidence score (0-1)
    pub confidence: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub enum SymbolRelationType {
    Inherits,
    Implements,
    Calls,
    CalledBy,
    Contains,
    ContainedIn,
    References,
    ReferencedBy,
    Overrides,
    OverriddenBy,
    Instantiates,
    InstantiatedBy,
    ParameterOf,
    ReturnTypeOf,
    FieldOf,
    MethodOf,
    Imports,
    ImportedBy,
    Exports,
    ExportedBy,
}

/// Index statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexStats {
    /// Total number of symbols indexed
    pub total_symbols: usize,

    /// Number of files indexed
    pub total_files: usize,

    /// Symbols by kind
    pub symbols_by_kind: HashMap<String, usize>,

    /// Symbols by language
    pub symbols_by_language: HashMap<String, usize>,

    /// Index size in bytes
    pub index_size_bytes: u64,

    /// Last update time
    pub last_updated: chrono::DateTime<chrono::Utc>,
}

impl Symbol {
    /// Create a unique symbol ID
    pub fn create_id(file_path: &str, name: &str, kind: &SymbolKind, line: usize) -> String {
        format!("{}:{}:{}:{}",
            file_path.replace("/", "_").replace(".", "_"),
            name,
            format!("{:?}", kind),
            line
        )
    }

    /// Get the qualified name (including parent if any)
    pub fn qualified_name(&self) -> String {
        if let Some(ref parent) = self.parent {
            format!("{}.{}", parent, self.name)
        } else {
            self.name.clone()
        }
    }

    /// Check if this is a public symbol
    pub fn is_public(&self) -> bool {
        matches!(self.visibility, SymbolVisibility::Public)
    }

    /// Check if this is a type symbol
    pub fn is_type(&self) -> bool {
        matches!(
            self.kind,
            SymbolKind::Class |
            SymbolKind::Interface |
            SymbolKind::Trait |
            SymbolKind::Struct |
            SymbolKind::Enum |
            SymbolKind::Union
        )
    }

    /// Check if this is a function/method
    pub fn is_function(&self) -> bool {
        matches!(
            self.kind,
            SymbolKind::Function |
            SymbolKind::Method |
            SymbolKind::Constructor
        )
    }

    /// Get display name with signature
    pub fn display_name(&self) -> String {
        if self.signature.is_empty() {
            self.name.clone()
        } else {
            format!("{}{}", self.name, self.signature)
        }
    }
}

impl std::fmt::Display for SymbolKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SymbolKind::Module => write!(f, "module"),
            SymbolKind::Package => write!(f, "package"),
            SymbolKind::Namespace => write!(f, "namespace"),
            SymbolKind::Class => write!(f, "class"),
            SymbolKind::Interface => write!(f, "interface"),
            SymbolKind::Trait => write!(f, "trait"),
            SymbolKind::Struct => write!(f, "struct"),
            SymbolKind::Enum => write!(f, "enum"),
            SymbolKind::Union => write!(f, "union"),
            SymbolKind::TypeAlias => write!(f, "type"),
            SymbolKind::Function => write!(f, "function"),
            SymbolKind::Method => write!(f, "method"),
            SymbolKind::Constructor => write!(f, "constructor"),
            SymbolKind::Destructor => write!(f, "destructor"),
            SymbolKind::Variable => write!(f, "variable"),
            SymbolKind::Field => write!(f, "field"),
            SymbolKind::Property => write!(f, "property"),
            SymbolKind::Parameter => write!(f, "parameter"),
            SymbolKind::Constant => write!(f, "constant"),
            SymbolKind::Macro => write!(f, "macro"),
            SymbolKind::Import => write!(f, "import"),
            SymbolKind::Export => write!(f, "export"),
            SymbolKind::Unknown => write!(f, "unknown"),
        }
    }
}

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

    #[test]
    fn test_symbol_id_creation() {
        let id = Symbol::create_id("src/main.rs", "test_func", &SymbolKind::Function, 42);
        assert!(id.contains("src_main_rs"));
        assert!(id.contains("test_func"));
        assert!(id.contains("42"));
    }

    #[test]
    fn test_qualified_name() {
        let symbol = Symbol {
            id: "test".to_string(),
            name: "method".to_string(),
            kind: SymbolKind::Method,
            file_path: "test.rs".to_string(),
            line: 10,
            column: 0,
            end_line: 15,
            signature: "()".to_string(),
            documentation: None,
            visibility: SymbolVisibility::Public,
            parent: Some("MyClass".to_string()),
            type_info: None,
            generics: vec![],
            annotations: vec![],
            attributes: vec![],
            metadata: HashMap::new(),
        };

        assert_eq!(symbol.qualified_name(), "MyClass.method");
    }

    #[test]
    fn test_symbol_type_checks() {
        let class_symbol = Symbol {
            id: "test".to_string(),
            name: "MyClass".to_string(),
            kind: SymbolKind::Class,
            file_path: "test.rs".to_string(),
            line: 10,
            column: 0,
            end_line: 15,
            signature: "".to_string(),
            documentation: None,
            visibility: SymbolVisibility::Public,
            parent: None,
            type_info: None,
            generics: vec![],
            annotations: vec![],
            attributes: vec![],
            metadata: HashMap::new(),
        };

        assert!(class_symbol.is_type());
        assert!(!class_symbol.is_function());

        let func_symbol = Symbol {
            id: "test2".to_string(),
            name: "my_func".to_string(),
            kind: SymbolKind::Function,
            file_path: "test.rs".to_string(),
            line: 20,
            column: 0,
            end_line: 25,
            signature: "()".to_string(),
            documentation: None,
            visibility: SymbolVisibility::Public,
            parent: None,
            type_info: None,
            generics: vec![],
            annotations: vec![],
            attributes: vec![],
            metadata: HashMap::new(),
        };

        assert!(!func_symbol.is_type());
        assert!(func_symbol.is_function());
    }
}