1use crate::ImportType;
14use crate::models::{Language, SearchResult, Span, SymbolKind};
15use crate::parsers::{DependencyExtractor, ImportInfo};
16use anyhow::{Context, Result};
17use tree_sitter::Parser;
18
19const SYMQ_0: &str = r#"
20 (function_declaration
21 (identifier) @name) @function
22 "#;
23const SYMQ_1: &str = r#"
24 (variable_declaration
25 (identifier) @name
26 (struct_declaration)) @struct
27 "#;
28const SYMQ_2: &str = r#"
29 (variable_declaration
30 (identifier) @name
31 (enum_declaration)) @enum
32 "#;
33const SYMQ_3: &str = r#"
34 (variable_declaration
35 "const"
36 (identifier) @name) @const
37 "#;
38const SYMQ_4: &str = r#"
39 (variable_declaration
40 "var"
41 (identifier) @name) @var
42 "#;
43const SYMQ_5: &str = r#"
44 (test_declaration
45 (string) @name) @test
46 "#;
47
48static SYMBOL_QUERIES: crate::parsers::LanguageQueries =
51 crate::parsers::LanguageQueries::new(&[SYMQ_0, SYMQ_1, SYMQ_2, SYMQ_3, SYMQ_4, SYMQ_5]);
52
53pub fn parse(path: &str, source: &str) -> Result<Vec<SearchResult>> {
55 let mut parser = Parser::new();
56 let language = tree_sitter_zig::LANGUAGE;
57
58 parser
59 .set_language(&language.into())
60 .context("Failed to set Zig language")?;
61
62 let tree = parser
63 .parse(source, None)
64 .context("Failed to parse Zig source")?;
65
66 let root_node = tree.root_node();
67 let table = SYMBOL_QUERIES.run(&language.into(), &root_node, source)?;
68
69 let mut symbols = Vec::new();
70
71 symbols.extend(extract_functions(source, &table)?);
73 symbols.extend(extract_structs(source, &table)?);
74 symbols.extend(extract_enums(source, &table)?);
75 symbols.extend(extract_constants(source, &table)?);
76 symbols.extend(extract_variables(source, &table)?);
77 symbols.extend(extract_tests(source, &table)?);
78
79 for symbol in &mut symbols {
81 symbol.path = path.to_string();
82 symbol.lang = Language::Zig;
83 }
84
85 Ok(symbols)
86}
87
88fn extract_functions(
90 source: &str,
91 table: &crate::parsers::MatchTable<'_>,
92) -> Result<Vec<SearchResult>> {
93 extract_symbols(source, table, 0, SymbolKind::Function, None)
94}
95
96fn extract_structs(
98 source: &str,
99 table: &crate::parsers::MatchTable<'_>,
100) -> Result<Vec<SearchResult>> {
101 extract_symbols(source, table, 1, SymbolKind::Struct, None)
102}
103
104fn extract_enums(
106 source: &str,
107 table: &crate::parsers::MatchTable<'_>,
108) -> Result<Vec<SearchResult>> {
109 extract_symbols(source, table, 2, SymbolKind::Enum, None)
110}
111
112fn extract_constants(
114 source: &str,
115 table: &crate::parsers::MatchTable<'_>,
116) -> Result<Vec<SearchResult>> {
117 extract_symbols(source, table, 3, SymbolKind::Constant, None)
118}
119
120fn extract_variables(
122 source: &str,
123 table: &crate::parsers::MatchTable<'_>,
124) -> Result<Vec<SearchResult>> {
125 extract_symbols(source, table, 4, SymbolKind::Variable, None)
126}
127
128fn extract_tests(
130 source: &str,
131 table: &crate::parsers::MatchTable<'_>,
132) -> Result<Vec<SearchResult>> {
133 extract_symbols(source, table, 5, SymbolKind::Function, None)
134}
135
136fn extract_symbols(
138 source: &str,
139 table: &crate::parsers::MatchTable<'_>,
140 sub: usize,
141 kind: SymbolKind,
142 scope: Option<String>,
143) -> Result<Vec<SearchResult>> {
144 let query = table.query();
145 let matches = table.sub(sub);
146
147 let mut symbols = Vec::new();
148
149 for match_ in matches {
150 let mut name = None;
152 let mut full_node = None;
153
154 for capture in &match_.captures {
155 let capture_name: &str = query.capture_names()[capture.index as usize];
156 if capture_name == "name" {
157 name = Some(
158 capture
159 .node
160 .utf8_text(source.as_bytes())
161 .unwrap_or("")
162 .to_string(),
163 );
164 } else {
165 full_node = Some(capture.node);
167 }
168 }
169
170 if let (Some(name), Some(node)) = (name, full_node) {
171 let span = node_to_span(&node);
172 let preview = extract_preview(source, &node);
173
174 symbols.push(SearchResult::new(
175 String::new(),
176 Language::Zig,
177 kind.clone(),
178 Some(name),
179 span,
180 scope.clone(),
181 preview,
182 ));
183 }
184 }
185
186 Ok(symbols)
187}
188
189fn node_to_span(node: &tree_sitter::Node) -> Span {
191 let start = node.start_position();
192 let end = node.end_position();
193
194 Span::new(
195 start.row + 1, start.column,
197 end.row + 1,
198 end.column,
199 )
200}
201
202fn extract_preview(source: &str, node: &tree_sitter::Node) -> String {
204 crate::parsers::preview::extract_preview_for_node(source, node)
206}
207
208pub struct ZigDependencyExtractor;
210
211impl DependencyExtractor for ZigDependencyExtractor {
212 fn extract_dependencies(source: &str) -> Result<Vec<ImportInfo>> {
213 let mut imports = Vec::new();
216
217 for (line_idx, line) in source.lines().enumerate() {
218 if let Some(import_path) = extract_zig_import_from_line(line) {
220 let import_type = classify_zig_import(&import_path);
221 let line_number = line_idx + 1;
222
223 imports.push(ImportInfo {
224 imported_path: import_path,
225 line_number,
226 import_type,
227 imported_symbols: None,
228 });
229 }
230 }
231
232 Ok(imports)
233 }
234}
235
236fn extract_zig_import_from_line(line: &str) -> Option<String> {
238 let import_start = line.find("@import(")?;
240 let after_import = &line[import_start + 8..]; let first_char = after_import.trim_start().chars().next()?;
244 if first_char != '"' && first_char != '\'' {
245 return None;
246 }
247
248 let quote_char = first_char;
249 let after_quote = &after_import[after_import.find(quote_char)? + 1..];
250 let end_quote = after_quote.find(quote_char)?;
251 let path = &after_quote[..end_quote];
252
253 Some(path.to_string())
254}
255
256fn classify_zig_import(import_path: &str) -> ImportType {
258 if import_path == "std" || import_path == "builtin" || import_path == "root" {
260 return ImportType::Stdlib;
261 }
262
263 if is_zig_file_import(import_path) {
265 return ImportType::Internal;
266 }
267
268 ImportType::External
271}
272
273pub fn is_zig_file_import(import_path: &str) -> bool {
276 import_path.starts_with("./")
277 || import_path.starts_with("../")
278 || import_path.ends_with(".zig")
279 || import_path.ends_with(".zon")
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct ZigModule {
286 pub dir: String,
287 pub name: String,
288 pub root: String,
289}
290
291pub fn parse_build_zig_modules(rel: &str, source: &str) -> Vec<ZigModule> {
296 let dir = crate::dependency_resolve::parent_dir(rel);
297 let quoted = |s: &str| -> Option<String> {
298 let s = s.trim_start().strip_prefix('"')?;
299 Some(s[..s.find('"')?].to_string())
300 };
301 let root_file = |stmt: &str| -> Option<String> {
302 let at = stmt.find(".root_source_file")?;
303 let rest = &stmt[at..];
304 let call = rest.find("path(")?;
305 quoted(&rest[call + "path(".len()..])
306 };
307 let mut named: Vec<(String, String)> = Vec::new();
308 let mut vars: std::collections::HashMap<String, String> = std::collections::HashMap::new();
309 let mut imports: Vec<(String, String)> = Vec::new();
310 for stmt in source.split(';') {
311 let trimmed = stmt.trim_start();
312 let var = trimmed
313 .strip_prefix("const ")
314 .or_else(|| trimmed.strip_prefix("var "))
315 .and_then(|r| r.split_once('='))
316 .map(|(name, _)| name.trim().to_string());
317 if let Some(path) = root_file(stmt) {
318 if let Some(at) = stmt.find("addModule(")
319 && let Some(name) = quoted(&stmt[at + "addModule(".len()..])
320 {
321 named.push((name, path.clone()));
322 }
323 if let Some(var) = &var
324 && (stmt.contains("addModule(") || stmt.contains("createModule("))
325 {
326 vars.insert(var.clone(), path);
327 }
328 }
329 let mut rest = stmt;
330 while let Some(at) = rest.find(".addImport(") {
331 rest = &rest[at + ".addImport(".len()..];
332 let Some(name) = quoted(rest) else { continue };
333 let after = &rest[rest.find(',').map_or(rest.len(), |i| i + 1)..];
334 let expr: String = after
335 .trim_start()
336 .chars()
337 .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.')
338 .collect();
339 if let Some(var) = expr.rsplit('.').next().filter(|v| !v.is_empty()) {
340 imports.push((name, var.to_string()));
341 }
342 }
343 }
344 for (name, var) in imports {
345 if let Some(path) = vars.get(&var)
346 && !named.iter().any(|(n, _)| *n == name)
347 {
348 named.push((name, path.clone()));
349 }
350 }
351 named
352 .into_iter()
353 .filter_map(|(name, path)| {
354 Some(ZigModule {
355 dir: dir.to_string(),
356 root: crate::dependency_resolve::fold_path(dir, &path)?,
357 name,
358 })
359 })
360 .collect()
361}
362
363pub fn find_zig_module<'a>(
366 name: &str,
367 rel: &str,
368 modules: &'a [ZigModule],
369) -> Option<&'a ZigModule> {
370 modules
371 .iter()
372 .filter(|m| m.name == name && (m.dir.is_empty() || rel.starts_with(&format!("{}/", m.dir))))
373 .max_by_key(|m| m.dir.len())
374}
375
376pub fn resolve_zig_import_to_path(
389 import_path: &str,
390 current_file_path: Option<&str>,
391) -> Option<String> {
392 if !is_zig_file_import(import_path) {
394 return None;
395 }
396
397 let current_file = current_file_path?;
399 crate::dependency_resolve::fold_path(
400 crate::dependency_resolve::parent_dir(current_file),
401 import_path,
402 )
403}
404
405#[cfg(test)]
406mod tests {
407 use super::*;
408
409 #[test]
410 fn test_parse_function() {
411 let source = r#"
412pub fn add(a: i32, b: i32) i32 {
413 return a + b;
414}
415 "#;
416
417 let symbols = parse("test.zig", source).unwrap();
418
419 let func_symbols: Vec<_> = symbols
420 .iter()
421 .filter(|s| matches!(s.kind, SymbolKind::Function))
422 .collect();
423
424 assert_eq!(func_symbols.len(), 1);
425 assert_eq!(func_symbols[0].symbol.as_deref(), Some("add"));
426 }
427
428 #[test]
429 fn test_parse_struct() {
430 let source = r#"
431const Point = struct {
432 x: f32,
433 y: f32,
434};
435 "#;
436
437 let symbols = parse("test.zig", source).unwrap();
438
439 let struct_symbols: Vec<_> = symbols
440 .iter()
441 .filter(|s| matches!(s.kind, SymbolKind::Struct))
442 .collect();
443
444 assert_eq!(struct_symbols.len(), 1);
445 assert_eq!(struct_symbols[0].symbol.as_deref(), Some("Point"));
446 }
447
448 #[test]
449 fn test_parse_enum() {
450 let source = r#"
451const Status = enum {
452 active,
453 inactive,
454 pending,
455};
456 "#;
457
458 let symbols = parse("test.zig", source).unwrap();
459
460 let enum_symbols: Vec<_> = symbols
461 .iter()
462 .filter(|s| matches!(s.kind, SymbolKind::Enum))
463 .collect();
464
465 assert_eq!(enum_symbols.len(), 1);
466 assert_eq!(enum_symbols[0].symbol.as_deref(), Some("Status"));
467 }
468
469 #[test]
470 fn test_parse_constants() {
471 let source = r#"
472const MAX_SIZE: usize = 100;
473const DEFAULT_TIMEOUT: u32 = 30;
474 "#;
475
476 let symbols = parse("test.zig", source).unwrap();
477
478 let const_symbols: Vec<_> = symbols
479 .iter()
480 .filter(|s| matches!(s.kind, SymbolKind::Constant))
481 .collect();
482
483 assert_eq!(const_symbols.len(), 2);
484 assert!(
485 const_symbols
486 .iter()
487 .any(|s| s.symbol.as_deref() == Some("MAX_SIZE"))
488 );
489 assert!(
490 const_symbols
491 .iter()
492 .any(|s| s.symbol.as_deref() == Some("DEFAULT_TIMEOUT"))
493 );
494 }
495
496 #[test]
497 fn test_parse_test_declaration() {
498 let source = r#"
499test "basic addition" {
500 const result = add(2, 3);
501 try std.testing.expect(result == 5);
502}
503 "#;
504
505 let symbols = parse("test.zig", source).unwrap();
506
507 let test_symbols: Vec<_> = symbols
508 .iter()
509 .filter(|s| matches!(s.kind, SymbolKind::Function))
510 .filter(|s| s.symbol.as_deref().unwrap_or("").contains("basic addition"))
511 .collect();
512
513 let _ = test_symbols; }
516
517 #[test]
518 fn test_parse_pub_functions() {
519 let source = r#"
520pub fn multiply(a: i32, b: i32) i32 {
521 return a * b;
522}
523
524fn divide(a: i32, b: i32) i32 {
525 return @divTrunc(a, b);
526}
527 "#;
528
529 let symbols = parse("test.zig", source).unwrap();
530
531 let func_symbols: Vec<_> = symbols
532 .iter()
533 .filter(|s| matches!(s.kind, SymbolKind::Function))
534 .collect();
535
536 assert_eq!(func_symbols.len(), 2);
537 assert!(
538 func_symbols
539 .iter()
540 .any(|s| s.symbol.as_deref() == Some("multiply"))
541 );
542 assert!(
543 func_symbols
544 .iter()
545 .any(|s| s.symbol.as_deref() == Some("divide"))
546 );
547 }
548
549 #[test]
550 fn test_parse_struct_with_methods() {
551 let source = r#"
552const Calculator = struct {
553 value: i32,
554
555 pub fn init(val: i32) Calculator {
556 return Calculator{ .value = val };
557 }
558
559 pub fn add(self: *Calculator, other: i32) void {
560 self.value += other;
561 }
562};
563 "#;
564
565 let symbols = parse("test.zig", source).unwrap();
566
567 let struct_symbols: Vec<_> = symbols
568 .iter()
569 .filter(|s| matches!(s.kind, SymbolKind::Struct))
570 .collect();
571
572 assert_eq!(struct_symbols.len(), 1);
573 assert_eq!(struct_symbols[0].symbol.as_deref(), Some("Calculator"));
574 }
575
576 #[test]
577 fn test_parse_error_set() {
578 let source = r#"
579const FileError = error{
580 AccessDenied,
581 FileNotFound,
582 OutOfMemory,
583};
584 "#;
585
586 let symbols = parse("test.zig", source).unwrap();
587
588 let const_symbols: Vec<_> = symbols
590 .iter()
591 .filter(|s| matches!(s.kind, SymbolKind::Constant))
592 .collect();
593
594 assert!(
595 const_symbols
596 .iter()
597 .any(|s| s.symbol.as_deref() == Some("FileError"))
598 );
599 }
600
601 #[test]
602 fn test_parse_mixed_symbols() {
603 let source = r#"
604const std = @import("std");
605
606const MAX_BUFFER = 1024;
607
608const Point = struct {
609 x: f32,
610 y: f32,
611};
612
613pub fn main() !void {
614 const stdout = std.io.getStdOut().writer();
615 try stdout.print("Hello, World!\n", .{});
616}
617
618test "point creation" {
619 const p = Point{ .x = 1.0, .y = 2.0 };
620 try std.testing.expect(p.x == 1.0);
621}
622 "#;
623
624 let symbols = parse("test.zig", source).unwrap();
625
626 assert!(symbols.len() >= 3);
628
629 let kinds: Vec<&SymbolKind> = symbols.iter().map(|s| &s.kind).collect();
630 assert!(kinds.contains(&&SymbolKind::Constant));
631 assert!(kinds.contains(&&SymbolKind::Struct));
632 assert!(kinds.contains(&&SymbolKind::Function));
633 }
634
635 #[test]
636 fn test_local_variables_included() {
637 let source = r#"
638const GLOBAL_CONST = 100;
639var globalVar: i32 = 50;
640
641pub fn calculate(input: i32) i32 {
642 const localConst = 10;
643 var localVar: i32 = input * 2;
644 localVar += localConst;
645 return localVar;
646}
647
648test "variable types" {
649 const testConst = 5;
650 var testVar: i32 = 0;
651 testVar = testConst * 2;
652 try std.testing.expect(testVar == 10);
653}
654 "#;
655
656 let symbols = parse("test.zig", source).unwrap();
657
658 let constants: Vec<_> = symbols
660 .iter()
661 .filter(|s| matches!(s.kind, SymbolKind::Constant))
662 .collect();
663
664 let variables: Vec<_> = symbols
665 .iter()
666 .filter(|s| matches!(s.kind, SymbolKind::Variable))
667 .collect();
668
669 assert!(
671 constants
672 .iter()
673 .any(|c| c.symbol.as_deref() == Some("GLOBAL_CONST"))
674 );
675 assert!(
676 constants
677 .iter()
678 .any(|c| c.symbol.as_deref() == Some("localConst"))
679 );
680 assert!(
681 constants
682 .iter()
683 .any(|c| c.symbol.as_deref() == Some("testConst"))
684 );
685
686 assert!(
688 variables
689 .iter()
690 .any(|v| v.symbol.as_deref() == Some("globalVar"))
691 );
692 assert!(
693 variables
694 .iter()
695 .any(|v| v.symbol.as_deref() == Some("localVar"))
696 );
697 assert!(
698 variables
699 .iter()
700 .any(|v| v.symbol.as_deref() == Some("testVar"))
701 );
702
703 for _constant in &constants {
706 }
708
709 for _variable in &variables {
710 }
712 }
713
714 #[test]
715 fn test_extract_zig_imports() {
716 let source = r#"
717const std = @import("std");
718const builtin = @import("builtin");
719const utils = @import("./utils.zig");
720const helpers = @import("../helpers.zig");
721const zap = @import("zap");
722
723pub fn main() !void {
724 const stdout = std.io.getStdOut().writer();
725 try stdout.print("Hello, World!\n", .{});
726}
727 "#;
728
729 let deps = ZigDependencyExtractor::extract_dependencies(source).unwrap();
730
731 assert!(
732 deps.len() >= 4,
733 "Should extract at least 4 imports, got {}",
734 deps.len()
735 );
736
737 assert!(
739 deps.iter()
740 .any(|d| d.imported_path == "std" && matches!(d.import_type, ImportType::Stdlib))
741 );
742 assert!(
743 deps.iter().any(
744 |d| d.imported_path == "builtin" && matches!(d.import_type, ImportType::Stdlib)
745 )
746 );
747
748 assert!(
750 deps.iter().any(|d| d.imported_path == "./utils.zig"
751 && matches!(d.import_type, ImportType::Internal))
752 );
753 assert!(deps.iter().any(|d| d.imported_path == "../helpers.zig"
754 && matches!(d.import_type, ImportType::Internal)));
755
756 assert!(
758 deps.iter()
759 .any(|d| d.imported_path == "zap" && matches!(d.import_type, ImportType::External))
760 );
761 }
762
763 #[cfg(test)]
765 mod resolution_tests {
766 use super::*;
767
768 #[test]
769 fn test_resolve_zig_import_same_directory() {
770 let result = resolve_zig_import_to_path("./utils.zig", Some("/project/src/main.zig"));
771 assert!(result.is_some());
772 let path = result.unwrap();
773 assert!(path.contains("src") && path.ends_with("utils.zig"));
774 }
775
776 #[test]
777 fn test_resolve_zig_import_subdirectory() {
778 let result =
779 resolve_zig_import_to_path("./utils/helpers.zig", Some("/project/src/main.zig"));
780 assert!(result.is_some());
781 let path = result.unwrap();
782 assert!(
783 path.contains("src") && path.contains("utils") && path.ends_with("helpers.zig")
784 );
785 }
786
787 #[test]
788 fn test_resolve_zig_import_parent_directory() {
789 let result =
790 resolve_zig_import_to_path("../common.zig", Some("/project/src/utils/main.zig"));
791 assert!(result.is_some());
792 let path = result.unwrap();
793 assert!(path.contains("src") && path.ends_with("common.zig"));
794 }
795
796 #[test]
797 fn test_resolve_zig_import_stdlib_returns_none() {
798 let result = resolve_zig_import_to_path("std", Some("/project/src/main.zig"));
800 assert!(result.is_none());
801
802 let result = resolve_zig_import_to_path("builtin", Some("/project/src/main.zig"));
803 assert!(result.is_none());
804 }
805
806 #[test]
807 fn test_resolve_zig_import_external_returns_none() {
808 let result = resolve_zig_import_to_path("zap", Some("/project/src/main.zig"));
810 assert!(result.is_none());
811
812 let result = resolve_zig_import_to_path("some_package", Some("/project/src/main.zig"));
813 assert!(result.is_none());
814 }
815 }
816}