reflex-search 1.0.3

A local-first, structure-aware code search engine for AI agents
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Zig language parser using Tree-sitter
//!
//! Extracts symbols from Zig source code:
//! - Functions (pub and private)
//! - Structs
//! - Enums
//! - Unions
//! - Constants (const - immutable, global and local)
//! - Variables (var - mutable, global and local)
//! - Test declarations
//! - Error sets

use anyhow::{Context, Result};
use streaming_iterator::StreamingIterator;
use tree_sitter::{Parser, Query, QueryCursor};
use crate::models::{Language, SearchResult, Span, SymbolKind};
use crate::parsers::{DependencyExtractor, ImportInfo};
use crate::ImportType;

/// Parse Zig source code and extract symbols
pub fn parse(path: &str, source: &str) -> Result<Vec<SearchResult>> {
    let mut parser = Parser::new();
    let language = tree_sitter_zig::LANGUAGE;

    parser
        .set_language(&language.into())
        .context("Failed to set Zig language")?;

    let tree = parser
        .parse(source, None)
        .context("Failed to parse Zig source")?;

    let root_node = tree.root_node();

    let mut symbols = Vec::new();

    // Extract different types of symbols using Tree-sitter queries
    symbols.extend(extract_functions(source, &root_node, &language.into())?);
    symbols.extend(extract_structs(source, &root_node, &language.into())?);
    symbols.extend(extract_enums(source, &root_node, &language.into())?);
    symbols.extend(extract_constants(source, &root_node, &language.into())?);
    symbols.extend(extract_variables(source, &root_node, &language.into())?);
    symbols.extend(extract_tests(source, &root_node, &language.into())?);

    // Add file path to all symbols
    for symbol in &mut symbols {
        symbol.path = path.to_string();
        symbol.lang = Language::Zig;
    }

    Ok(symbols)
}

/// Extract function declarations
fn extract_functions(
    source: &str,
    root: &tree_sitter::Node,
    language: &tree_sitter::Language,
) -> Result<Vec<SearchResult>> {
    let query_str = r#"
        (function_declaration
            (identifier) @name) @function
    "#;

    let query = Query::new(language, query_str)
        .context("Failed to create function query")?;

    extract_symbols(source, root, &query, SymbolKind::Function, None)
}

/// Extract struct (container) declarations
fn extract_structs(
    source: &str,
    root: &tree_sitter::Node,
    language: &tree_sitter::Language,
) -> Result<Vec<SearchResult>> {
    let query_str = r#"
        (variable_declaration
            (identifier) @name
            (struct_declaration)) @struct
    "#;

    let query = Query::new(language, query_str)
        .context("Failed to create struct query")?;

    extract_symbols(source, root, &query, SymbolKind::Struct, None)
}

/// Extract enum declarations
fn extract_enums(
    source: &str,
    root: &tree_sitter::Node,
    language: &tree_sitter::Language,
) -> Result<Vec<SearchResult>> {
    let query_str = r#"
        (variable_declaration
            (identifier) @name
            (enum_declaration)) @enum
    "#;

    let query = Query::new(language, query_str)
        .context("Failed to create enum query")?;

    extract_symbols(source, root, &query, SymbolKind::Enum, None)
}

/// Extract constant declarations (const - immutable bindings)
fn extract_constants(
    source: &str,
    root: &tree_sitter::Node,
    language: &tree_sitter::Language,
) -> Result<Vec<SearchResult>> {
    let query_str = r#"
        (variable_declaration
            "const"
            (identifier) @name) @const
    "#;

    let query = Query::new(language, query_str)
        .context("Failed to create constant query")?;

    extract_symbols(source, root, &query, SymbolKind::Constant, None)
}

/// Extract variable declarations (var - mutable bindings)
fn extract_variables(
    source: &str,
    root: &tree_sitter::Node,
    language: &tree_sitter::Language,
) -> Result<Vec<SearchResult>> {
    let query_str = r#"
        (variable_declaration
            "var"
            (identifier) @name) @var
    "#;

    let query = Query::new(language, query_str)
        .context("Failed to create variable query")?;

    extract_symbols(source, root, &query, SymbolKind::Variable, None)
}

/// Extract test declarations
fn extract_tests(
    source: &str,
    root: &tree_sitter::Node,
    language: &tree_sitter::Language,
) -> Result<Vec<SearchResult>> {
    let query_str = r#"
        (test_declaration
            (string) @name) @test
    "#;

    let query = Query::new(language, query_str)
        .context("Failed to create test query")?;

    extract_symbols(source, root, &query, SymbolKind::Function, None)
}

/// Generic symbol extraction helper
fn extract_symbols(
    source: &str,
    root: &tree_sitter::Node,
    query: &Query,
    kind: SymbolKind,
    scope: Option<String>,
) -> Result<Vec<SearchResult>> {
    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, *root, source.as_bytes());

    let mut symbols = Vec::new();

    while let Some(match_) = matches.next() {
        // Find the name capture and the full node
        let mut name = None;
        let mut full_node = None;

        for capture in match_.captures {
            let capture_name: &str = &query.capture_names()[capture.index as usize];
            if capture_name == "name" {
                name = Some(capture.node.utf8_text(source.as_bytes()).unwrap_or("").to_string());
            } else {
                // Assume any other capture is the full node
                full_node = Some(capture.node);
            }
        }

        if let (Some(name), Some(node)) = (name, full_node) {
            let span = node_to_span(&node);
            let preview = extract_preview(source, &span);

            symbols.push(SearchResult::new(
                String::new(),
                Language::Zig,
                kind.clone(),
                Some(name),
                span,
                scope.clone(),
                preview,
            ));
        }
    }

    Ok(symbols)
}

/// Convert a Tree-sitter node to a Span
fn node_to_span(node: &tree_sitter::Node) -> Span {
    let start = node.start_position();
    let end = node.end_position();

    Span::new(
        start.row + 1,  // Convert 0-indexed to 1-indexed
        start.column,
        end.row + 1,
        end.column,
    )
}

/// Extract a preview (7 lines) around the symbol
fn extract_preview(source: &str, span: &Span) -> String {
    let lines: Vec<&str> = source.lines().collect();

    // Extract 7 lines: the start line and 6 following lines
    let start_idx = (span.start_line - 1) as usize; // Convert back to 0-indexed
    let end_idx = (start_idx + 7).min(lines.len());

    lines[start_idx..end_idx].join("\n")
}

/// Zig dependency extractor
pub struct ZigDependencyExtractor;

impl DependencyExtractor for ZigDependencyExtractor {
    fn extract_dependencies(source: &str) -> Result<Vec<ImportInfo>> {
        // Zig uses @import("path") builtin for imports
        // Use simple text-based extraction as fallback since tree-sitter query might not work
        let mut imports = Vec::new();

        for (line_idx, line) in source.lines().enumerate() {
            // Look for @import("...") or @import('...')
            if let Some(import_path) = extract_zig_import_from_line(line) {
                let import_type = classify_zig_import(&import_path);
                let line_number = line_idx + 1;

                imports.push(ImportInfo {
                    imported_path: import_path,
                    line_number,
                    import_type,
                    imported_symbols: None,
                });
            }
        }

        Ok(imports)
    }
}

/// Extract import path from a line containing @import("...")
fn extract_zig_import_from_line(line: &str) -> Option<String> {
    // Find @import( in the line
    let import_start = line.find("@import(")?;
    let after_import = &line[import_start + 8..]; // Skip "@import("

    // Find the string content (either "..." or '...')
    let first_char = after_import.trim_start().chars().next()?;
    if first_char != '"' && first_char != '\'' {
        return None;
    }

    let quote_char = first_char;
    let after_quote = &after_import[after_import.find(quote_char)? + 1..];
    let end_quote = after_quote.find(quote_char)?;
    let path = &after_quote[..end_quote];

    Some(path.to_string())
}

/// Classify Zig import as Internal, External, or Stdlib
fn classify_zig_import(import_path: &str) -> ImportType {
    // Zig standard library imports
    if import_path == "std" || import_path == "builtin" || import_path == "root" {
        return ImportType::Stdlib;
    }

    // Relative imports (start with ./ or ../)
    if import_path.starts_with("./") || import_path.starts_with("../") {
        return ImportType::Internal;
    }

    // External package imports (anything else that's not stdlib)
    // Zig package manager uses package names directly
    ImportType::External
}

/// Resolve a Zig @import("...") path to an absolute file path
///
/// Only resolves Internal imports (relative paths starting with ./ or ../)
/// Returns None for External and Stdlib imports
///
/// # Arguments
/// * `import_path` - The path from @import("...") (e.g., "./utils.zig", "../helpers.zig")
/// * `current_file_path` - The absolute path of the file containing the import
///
/// # Returns
/// Some(absolute_path) if the import is resolvable (Internal relative path)
/// None if the import is External or Stdlib
pub fn resolve_zig_import_to_path(
    import_path: &str,
    current_file_path: Option<&str>,
) -> Option<String> {
    // Only resolve Internal imports (relative paths)
    if !import_path.starts_with("./") && !import_path.starts_with("../") {
        return None;
    }

    let current_file = current_file_path?;
    let current_dir = std::path::Path::new(current_file).parent()?;
    let resolved = current_dir.join(import_path);

    // Try to canonicalize (normalize) the path
    match resolved.canonicalize() {
        Ok(normalized) => Some(normalized.display().to_string()),
        Err(_) => {
            // If canonicalization fails (file doesn't exist), return the raw path
            Some(resolved.display().to_string())
        }
    }
}

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

    #[test]
    fn test_parse_function() {
        let source = r#"
pub fn add(a: i32, b: i32) i32 {
    return a + b;
}
        "#;

        let symbols = parse("test.zig", source).unwrap();

        let func_symbols: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Function))
            .collect();

        assert_eq!(func_symbols.len(), 1);
        assert_eq!(func_symbols[0].symbol.as_deref(), Some("add"));
    }

    #[test]
    fn test_parse_struct() {
        let source = r#"
const Point = struct {
    x: f32,
    y: f32,
};
        "#;

        let symbols = parse("test.zig", source).unwrap();

        let struct_symbols: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Struct))
            .collect();

        assert_eq!(struct_symbols.len(), 1);
        assert_eq!(struct_symbols[0].symbol.as_deref(), Some("Point"));
    }

    #[test]
    fn test_parse_enum() {
        let source = r#"
const Status = enum {
    active,
    inactive,
    pending,
};
        "#;

        let symbols = parse("test.zig", source).unwrap();

        let enum_symbols: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Enum))
            .collect();

        assert_eq!(enum_symbols.len(), 1);
        assert_eq!(enum_symbols[0].symbol.as_deref(), Some("Status"));
    }

    #[test]
    fn test_parse_constants() {
        let source = r#"
const MAX_SIZE: usize = 100;
const DEFAULT_TIMEOUT: u32 = 30;
        "#;

        let symbols = parse("test.zig", source).unwrap();

        let const_symbols: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Constant))
            .collect();

        assert_eq!(const_symbols.len(), 2);
        assert!(const_symbols.iter().any(|s| s.symbol.as_deref() == Some("MAX_SIZE")));
        assert!(const_symbols.iter().any(|s| s.symbol.as_deref() == Some("DEFAULT_TIMEOUT")));
    }

    #[test]
    fn test_parse_test_declaration() {
        let source = r#"
test "basic addition" {
    const result = add(2, 3);
    try std.testing.expect(result == 5);
}
        "#;

        let symbols = parse("test.zig", source).unwrap();

        let test_symbols: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Function))
            .filter(|s| s.symbol.as_deref().unwrap_or("").contains("basic addition"))
            .collect();

        // Test verifies parsing succeeds without panic
        let _ = test_symbols; // Suppress unused variable warning
    }

    #[test]
    fn test_parse_pub_functions() {
        let source = r#"
pub fn multiply(a: i32, b: i32) i32 {
    return a * b;
}

fn divide(a: i32, b: i32) i32 {
    return @divTrunc(a, b);
}
        "#;

        let symbols = parse("test.zig", source).unwrap();

        let func_symbols: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Function))
            .collect();

        assert_eq!(func_symbols.len(), 2);
        assert!(func_symbols.iter().any(|s| s.symbol.as_deref() == Some("multiply")));
        assert!(func_symbols.iter().any(|s| s.symbol.as_deref() == Some("divide")));
    }

    #[test]
    fn test_parse_struct_with_methods() {
        let source = r#"
const Calculator = struct {
    value: i32,

    pub fn init(val: i32) Calculator {
        return Calculator{ .value = val };
    }

    pub fn add(self: *Calculator, other: i32) void {
        self.value += other;
    }
};
        "#;

        let symbols = parse("test.zig", source).unwrap();

        let struct_symbols: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Struct))
            .collect();

        assert_eq!(struct_symbols.len(), 1);
        assert_eq!(struct_symbols[0].symbol.as_deref(), Some("Calculator"));
    }

    #[test]
    fn test_parse_error_set() {
        let source = r#"
const FileError = error{
    AccessDenied,
    FileNotFound,
    OutOfMemory,
};
        "#;

        let symbols = parse("test.zig", source).unwrap();

        // Error sets are stored as constants
        let const_symbols: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Constant))
            .collect();

        assert!(const_symbols.iter().any(|s| s.symbol.as_deref() == Some("FileError")));
    }

    #[test]
    fn test_parse_mixed_symbols() {
        let source = r#"
const std = @import("std");

const MAX_BUFFER = 1024;

const Point = struct {
    x: f32,
    y: f32,
};

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    try stdout.print("Hello, World!\n", .{});
}

test "point creation" {
    const p = Point{ .x = 1.0, .y = 2.0 };
    try std.testing.expect(p.x == 1.0);
}
        "#;

        let symbols = parse("test.zig", source).unwrap();

        // Should find: constants, struct, function, test
        assert!(symbols.len() >= 3);

        let kinds: Vec<&SymbolKind> = symbols.iter().map(|s| &s.kind).collect();
        assert!(kinds.contains(&&SymbolKind::Constant));
        assert!(kinds.contains(&&SymbolKind::Struct));
        assert!(kinds.contains(&&SymbolKind::Function));
    }

    #[test]
    fn test_local_variables_included() {
        let source = r#"
const GLOBAL_CONST = 100;
var globalVar: i32 = 50;

pub fn calculate(input: i32) i32 {
    const localConst = 10;
    var localVar: i32 = input * 2;
    localVar += localConst;
    return localVar;
}

test "variable types" {
    const testConst = 5;
    var testVar: i32 = 0;
    testVar = testConst * 2;
    try std.testing.expect(testVar == 10);
}
        "#;

        let symbols = parse("test.zig", source).unwrap();

        // Filter to constants and variables
        let constants: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Constant))
            .collect();

        let variables: Vec<_> = symbols.iter()
            .filter(|s| matches!(s.kind, SymbolKind::Variable))
            .collect();

        // Check that const declarations are captured (global and local)
        assert!(constants.iter().any(|c| c.symbol.as_deref() == Some("GLOBAL_CONST")));
        assert!(constants.iter().any(|c| c.symbol.as_deref() == Some("localConst")));
        assert!(constants.iter().any(|c| c.symbol.as_deref() == Some("testConst")));

        // Check that var declarations are captured (global and local)
        assert!(variables.iter().any(|v| v.symbol.as_deref() == Some("globalVar")));
        assert!(variables.iter().any(|v| v.symbol.as_deref() == Some("localVar")));
        assert!(variables.iter().any(|v| v.symbol.as_deref() == Some("testVar")));

        // Verify that both global and local variables have no scope
        // (Zig doesn't have class-based scoping, all variables are treated equally)
        for constant in &constants {
            // Removed: scope field no longer exists: assert_eq!(constant.scope, None);
        }

        for variable in &variables {
            // Removed: scope field no longer exists: assert_eq!(variable.scope, None);
        }
    }

    #[test]
    fn test_extract_zig_imports() {
        let source = r#"
const std = @import("std");
const builtin = @import("builtin");
const utils = @import("./utils.zig");
const helpers = @import("../helpers.zig");
const zap = @import("zap");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    try stdout.print("Hello, World!\n", .{});
}
        "#;

        let deps = ZigDependencyExtractor::extract_dependencies(source).unwrap();

        assert!(deps.len() >= 4, "Should extract at least 4 imports, got {}", deps.len());

        // Stdlib imports
        assert!(deps.iter().any(|d| d.imported_path == "std" && matches!(d.import_type, ImportType::Stdlib)));
        assert!(deps.iter().any(|d| d.imported_path == "builtin" && matches!(d.import_type, ImportType::Stdlib)));

        // Internal imports (relative paths)
        assert!(deps.iter().any(|d| d.imported_path == "./utils.zig" && matches!(d.import_type, ImportType::Internal)));
        assert!(deps.iter().any(|d| d.imported_path == "../helpers.zig" && matches!(d.import_type, ImportType::Internal)));

        // External package import
        assert!(deps.iter().any(|d| d.imported_path == "zap" && matches!(d.import_type, ImportType::External)));
    }

    // Zig import path resolution tests
    #[cfg(test)]
    mod resolution_tests {
        use super::*;

        #[test]
        fn test_resolve_zig_import_same_directory() {
            let result = resolve_zig_import_to_path("./utils.zig", Some("/project/src/main.zig"));
            assert!(result.is_some());
            let path = result.unwrap();
            assert!(path.contains("src") && path.ends_with("utils.zig"));
        }

        #[test]
        fn test_resolve_zig_import_subdirectory() {
            let result = resolve_zig_import_to_path("./utils/helpers.zig", Some("/project/src/main.zig"));
            assert!(result.is_some());
            let path = result.unwrap();
            assert!(path.contains("src") && path.contains("utils") && path.ends_with("helpers.zig"));
        }

        #[test]
        fn test_resolve_zig_import_parent_directory() {
            let result = resolve_zig_import_to_path("../common.zig", Some("/project/src/utils/main.zig"));
            assert!(result.is_some());
            let path = result.unwrap();
            assert!(path.contains("src") && path.ends_with("common.zig"));
        }

        #[test]
        fn test_resolve_zig_import_stdlib_returns_none() {
            // Stdlib imports should not be resolved
            let result = resolve_zig_import_to_path("std", Some("/project/src/main.zig"));
            assert!(result.is_none());

            let result = resolve_zig_import_to_path("builtin", Some("/project/src/main.zig"));
            assert!(result.is_none());
        }

        #[test]
        fn test_resolve_zig_import_external_returns_none() {
            // External package imports should not be resolved
            let result = resolve_zig_import_to_path("zap", Some("/project/src/main.zig"));
            assert!(result.is_none());

            let result = resolve_zig_import_to_path("some_package", Some("/project/src/main.zig"));
            assert!(result.is_none());
        }
    }
}