reflex-search 2.3.1

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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! 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 crate::ImportType;
use crate::models::{Language, SearchResult, Span, SymbolKind};
use crate::parsers::{DependencyExtractor, ImportInfo};
use anyhow::{Context, Result};
use tree_sitter::Parser;

const SYMQ_0: &str = r#"
        (function_declaration
            (identifier) @name) @function
    "#;
const SYMQ_1: &str = r#"
        (variable_declaration
            (identifier) @name
            (struct_declaration)) @struct
    "#;
const SYMQ_2: &str = r#"
        (variable_declaration
            (identifier) @name
            (enum_declaration)) @enum
    "#;
const SYMQ_3: &str = r#"
        (variable_declaration
            "const"
            (identifier) @name) @const
    "#;
const SYMQ_4: &str = r#"
        (variable_declaration
            "var"
            (identifier) @name) @var
    "#;
const SYMQ_5: &str = r#"
        (test_declaration
            (string) @name) @test
    "#;

/// Every symbol query of this module, run as ONE query per file (see
/// `crate::parsers::LanguageQueries`).
static SYMBOL_QUERIES: crate::parsers::LanguageQueries =
    crate::parsers::LanguageQueries::new(&[SYMQ_0, SYMQ_1, SYMQ_2, SYMQ_3, SYMQ_4, SYMQ_5]);

/// 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 table = SYMBOL_QUERIES.run(&language.into(), &root_node, source)?;

    let mut symbols = Vec::new();

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

    // 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,
    table: &crate::parsers::MatchTable<'_>,
) -> Result<Vec<SearchResult>> {
    extract_symbols(source, table, 0, SymbolKind::Function, None)
}

/// Extract struct (container) declarations
fn extract_structs(
    source: &str,
    table: &crate::parsers::MatchTable<'_>,
) -> Result<Vec<SearchResult>> {
    extract_symbols(source, table, 1, SymbolKind::Struct, None)
}

/// Extract enum declarations
fn extract_enums(
    source: &str,
    table: &crate::parsers::MatchTable<'_>,
) -> Result<Vec<SearchResult>> {
    extract_symbols(source, table, 2, SymbolKind::Enum, None)
}

/// Extract constant declarations (const - immutable bindings)
fn extract_constants(
    source: &str,
    table: &crate::parsers::MatchTable<'_>,
) -> Result<Vec<SearchResult>> {
    extract_symbols(source, table, 3, SymbolKind::Constant, None)
}

/// Extract variable declarations (var - mutable bindings)
fn extract_variables(
    source: &str,
    table: &crate::parsers::MatchTable<'_>,
) -> Result<Vec<SearchResult>> {
    extract_symbols(source, table, 4, SymbolKind::Variable, None)
}

/// Extract test declarations
fn extract_tests(
    source: &str,
    table: &crate::parsers::MatchTable<'_>,
) -> Result<Vec<SearchResult>> {
    extract_symbols(source, table, 5, SymbolKind::Function, None)
}

/// Generic symbol extraction helper
fn extract_symbols(
    source: &str,
    table: &crate::parsers::MatchTable<'_>,
    sub: usize,
    kind: SymbolKind,
    scope: Option<String>,
) -> Result<Vec<SearchResult>> {
    let query = table.query();
    let matches = table.sub(sub);

    let mut symbols = Vec::new();

    for match_ in matches {
        // 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, &node);

            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, node: &tree_sitter::Node) -> String {
    // Starts at the node, not at byte 0: see `crate::parsers::preview`.
    crate::parsers::preview::extract_preview_for_node(source, node)
}

/// 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;
    }

    // A file path, relative to the importer with or without `./`
    if is_zig_file_import(import_path) {
        return ImportType::Internal;
    }

    // A module name: a package-manager dependency, or a module the workspace's
    // build.zig defines (reclassified with `ZigModule`s)
    ImportType::External
}

/// Whether `@import("…")` names a file (Zig imports `*.zig` and `*.zon` files by
/// path, relative to the importer) rather than a module.
pub fn is_zig_file_import(import_path: &str) -> bool {
    import_path.starts_with("./")
        || import_path.starts_with("../")
        || import_path.ends_with(".zig")
        || import_path.ends_with(".zon")
}

/// A named module a `build.zig` defines: `@import(name)` in the workspace under
/// `dir` reaches `root` (both relative to the index root).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZigModule {
    pub dir: String,
    pub name: String,
    pub root: String,
}

/// The named modules of the `build.zig` at `rel` (relative to the index root):
/// `b.addModule("name", .{ .root_source_file = b.path("p") })`, and modules made
/// by `b.createModule(…)` into a variable that `.addImport("name", var)` names
/// (`options.var` counts as `var`). A text scan, statement by statement.
pub fn parse_build_zig_modules(rel: &str, source: &str) -> Vec<ZigModule> {
    let dir = crate::dependency_resolve::parent_dir(rel);
    let quoted = |s: &str| -> Option<String> {
        let s = s.trim_start().strip_prefix('"')?;
        Some(s[..s.find('"')?].to_string())
    };
    let root_file = |stmt: &str| -> Option<String> {
        let at = stmt.find(".root_source_file")?;
        let rest = &stmt[at..];
        let call = rest.find("path(")?;
        quoted(&rest[call + "path(".len()..])
    };
    let mut named: Vec<(String, String)> = Vec::new();
    let mut vars: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    let mut imports: Vec<(String, String)> = Vec::new();
    for stmt in source.split(';') {
        let trimmed = stmt.trim_start();
        let var = trimmed
            .strip_prefix("const ")
            .or_else(|| trimmed.strip_prefix("var "))
            .and_then(|r| r.split_once('='))
            .map(|(name, _)| name.trim().to_string());
        if let Some(path) = root_file(stmt) {
            if let Some(at) = stmt.find("addModule(")
                && let Some(name) = quoted(&stmt[at + "addModule(".len()..])
            {
                named.push((name, path.clone()));
            }
            if let Some(var) = &var
                && (stmt.contains("addModule(") || stmt.contains("createModule("))
            {
                vars.insert(var.clone(), path);
            }
        }
        let mut rest = stmt;
        while let Some(at) = rest.find(".addImport(") {
            rest = &rest[at + ".addImport(".len()..];
            let Some(name) = quoted(rest) else { continue };
            let after = &rest[rest.find(',').map_or(rest.len(), |i| i + 1)..];
            let expr: String = after
                .trim_start()
                .chars()
                .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.')
                .collect();
            if let Some(var) = expr.rsplit('.').next().filter(|v| !v.is_empty()) {
                imports.push((name, var.to_string()));
            }
        }
    }
    for (name, var) in imports {
        if let Some(path) = vars.get(&var)
            && !named.iter().any(|(n, _)| *n == name)
        {
            named.push((name, path.clone()));
        }
    }
    named
        .into_iter()
        .filter_map(|(name, path)| {
            Some(ZigModule {
                dir: dir.to_string(),
                root: crate::dependency_resolve::fold_path(dir, &path)?,
                name,
            })
        })
        .collect()
}

/// The module `name` means in the file at `rel`: the nearest `build.zig` above it
/// that defines `name`.
pub fn find_zig_module<'a>(
    name: &str,
    rel: &str,
    modules: &'a [ZigModule],
) -> Option<&'a ZigModule> {
    modules
        .iter()
        .filter(|m| m.name == name && (m.dir.is_empty() || rel.starts_with(&format!("{}/", m.dir))))
        .max_by_key(|m| m.dir.len())
}

/// 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 file imports; module names go through `find_zig_module`
    if !is_zig_file_import(import_path) {
        return None;
    }

    // Relative to the importing file, folded without reading the disk
    let current_file = current_file_path?;
    crate::dependency_resolve::fold_path(
        crate::dependency_resolve::parent_dir(current_file),
        import_path,
    )
}

#[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());
        }
    }
}