Skip to main content

reflex/parsers/
rust.rs

1//! Rust language parser using Tree-sitter
2//!
3//! Extracts symbols from Rust source code:
4//! - Functions (fn)
5//! - Structs
6//! - Enums
7//! - Traits
8//! - Impl blocks
9//! - Constants
10//! - Static variables
11//! - Local variables (let bindings)
12//! - Modules
13//! - Type aliases
14//! - Macros (macro_rules! definitions)
15
16use crate::models::{Language, SearchResult, Span, SymbolKind};
17use crate::parsers::{DependencyExtractor, ImportInfo};
18use anyhow::{Context, Result};
19use streaming_iterator::StreamingIterator;
20use tree_sitter::{Parser, QueryCursor};
21
22const SYMQ_0: &str = r#"
23        (function_item
24            name: (identifier) @name) @function
25    "#;
26const SYMQ_1: &str = r#"
27        (struct_item
28            name: (type_identifier) @name) @struct
29    "#;
30const SYMQ_2: &str = r#"
31        (enum_item
32            name: (type_identifier) @name) @enum
33    "#;
34const SYMQ_3: &str = r#"
35        (trait_item
36            name: (type_identifier) @name) @trait
37    "#;
38const SYMQ_4: &str = r#"
39        (impl_item
40            type: (type_identifier) @impl_name
41            body: (declaration_list
42                (function_item
43                    name: (identifier) @method_name))) @impl
44    "#;
45const SYMQ_5: &str = r#"
46        (const_item
47            name: (identifier) @name) @const
48    "#;
49const SYMQ_6: &str = r#"
50        (static_item
51            name: (identifier) @name) @static
52    "#;
53const SYMQ_7: &str = r#"
54        (let_declaration
55            pattern: (identifier) @name) @let
56    "#;
57const SYMQ_8: &str = r#"
58        (mod_item
59            name: (identifier) @name) @module
60    "#;
61const SYMQ_9: &str = r#"
62        (type_item
63            name: (type_identifier) @name) @type
64    "#;
65const SYMQ_10: &str = r#"
66        (macro_definition
67            name: (identifier) @name) @macro
68    "#;
69const SYMQ_11: &str = r#"
70        (attribute_item
71            (attribute
72                (identifier) @attr_name)) @attr
73    "#;
74const SYMQ_12: &str = r#"
75        (function_item
76            name: (identifier) @name) @function
77    "#;
78
79/// Every symbol query of this module, run as ONE query per file (see
80/// `crate::parsers::LanguageQueries`).
81static SYMBOL_QUERIES: crate::parsers::LanguageQueries = crate::parsers::LanguageQueries::new(&[
82    SYMQ_0, SYMQ_1, SYMQ_2, SYMQ_3, SYMQ_4, SYMQ_5, SYMQ_6, SYMQ_7, SYMQ_8, SYMQ_9, SYMQ_10,
83    SYMQ_11, SYMQ_12,
84]);
85
86/// Parse Rust source code and extract symbols
87pub fn parse(path: &str, source: &str) -> Result<Vec<SearchResult>> {
88    let mut parser = Parser::new();
89    let language = tree_sitter_rust::LANGUAGE;
90
91    parser
92        .set_language(&language.into())
93        .context("Failed to set Rust language")?;
94
95    let tree = parser
96        .parse(source, None)
97        .context("Failed to parse Rust source")?;
98
99    let root_node = tree.root_node();
100    let table = SYMBOL_QUERIES.run(&language.into(), &root_node, source)?;
101
102    let mut symbols = Vec::new();
103
104    // Extract different types of symbols using Tree-sitter queries
105    symbols.extend(extract_functions(source, &table)?);
106    symbols.extend(extract_structs(source, &table)?);
107    symbols.extend(extract_enums(source, &table)?);
108    symbols.extend(extract_traits(source, &table)?);
109    symbols.extend(extract_impls(source, &table)?);
110    symbols.extend(extract_constants(source, &table)?);
111    symbols.extend(extract_statics(source, &table)?);
112    symbols.extend(extract_local_variables(source, &table)?);
113    symbols.extend(extract_modules(source, &table)?);
114    symbols.extend(extract_type_aliases(source, &table)?);
115    symbols.extend(extract_macros(source, &table)?);
116    symbols.extend(extract_attributes(source, &table)?);
117
118    // Add file path to all symbols
119    for symbol in &mut symbols {
120        symbol.path = path.to_string();
121        symbol.lang = Language::Rust;
122    }
123
124    Ok(symbols)
125}
126
127/// Extract function definitions
128fn extract_functions(
129    source: &str,
130    table: &crate::parsers::MatchTable<'_>,
131) -> Result<Vec<SearchResult>> {
132    extract_symbols(source, table, 0, SymbolKind::Function, None)
133}
134
135/// Extract struct definitions
136fn extract_structs(
137    source: &str,
138    table: &crate::parsers::MatchTable<'_>,
139) -> Result<Vec<SearchResult>> {
140    extract_symbols(source, table, 1, SymbolKind::Struct, None)
141}
142
143/// Extract enum definitions
144fn extract_enums(
145    source: &str,
146    table: &crate::parsers::MatchTable<'_>,
147) -> Result<Vec<SearchResult>> {
148    extract_symbols(source, table, 2, SymbolKind::Enum, None)
149}
150
151/// Extract trait definitions
152fn extract_traits(
153    source: &str,
154    table: &crate::parsers::MatchTable<'_>,
155) -> Result<Vec<SearchResult>> {
156    extract_symbols(source, table, 3, SymbolKind::Trait, None)
157}
158
159/// Extract impl blocks
160fn extract_impls(
161    source: &str,
162    table: &crate::parsers::MatchTable<'_>,
163) -> Result<Vec<SearchResult>> {
164    // Extract methods from impl blocks
165
166    let query = table.query();
167    let matches = table.sub(4);
168
169    let mut symbols = Vec::new();
170
171    for match_ in matches {
172        let mut impl_name = None;
173        let mut method_name = None;
174        let mut method_node = None;
175
176        for capture in &match_.captures {
177            let capture_name: &str = query.capture_names()[capture.index as usize];
178            match capture_name {
179                "impl_name" => {
180                    impl_name = Some(
181                        capture
182                            .node
183                            .utf8_text(source.as_bytes())
184                            .unwrap_or("")
185                            .to_string(),
186                    );
187                }
188                "method_name" => {
189                    method_name = Some(
190                        capture
191                            .node
192                            .utf8_text(source.as_bytes())
193                            .unwrap_or("")
194                            .to_string(),
195                    );
196                    // Find the parent function_item node
197                    let mut current = capture.node;
198                    while let Some(parent) = current.parent() {
199                        if parent.kind() == "function_item" {
200                            method_node = Some(parent);
201                            break;
202                        }
203                        current = parent;
204                    }
205                }
206                _ => {}
207            }
208        }
209
210        if let (Some(impl_name), Some(method_name), Some(node)) =
211            (impl_name, method_name, method_node)
212        {
213            let scope = format!("impl {}", impl_name);
214            let span = node_to_span(&node);
215            let preview = extract_preview(source, &node);
216
217            symbols.push(SearchResult::new(
218                String::new(), // Path will be filled in later
219                Language::Rust,
220                SymbolKind::Method,
221                Some(method_name),
222                span,
223                Some(scope),
224                preview,
225            ));
226        }
227    }
228
229    Ok(symbols)
230}
231
232/// Extract constants
233fn extract_constants(
234    source: &str,
235    table: &crate::parsers::MatchTable<'_>,
236) -> Result<Vec<SearchResult>> {
237    extract_symbols(source, table, 5, SymbolKind::Constant, None)
238}
239
240/// Extract static variables
241fn extract_statics(
242    source: &str,
243    table: &crate::parsers::MatchTable<'_>,
244) -> Result<Vec<SearchResult>> {
245    extract_symbols(source, table, 6, SymbolKind::Variable, None)
246}
247
248/// Extract local variable bindings (let statements)
249fn extract_local_variables(
250    source: &str,
251    table: &crate::parsers::MatchTable<'_>,
252) -> Result<Vec<SearchResult>> {
253    extract_symbols(source, table, 7, SymbolKind::Variable, None)
254}
255
256/// Extract module declarations
257fn extract_modules(
258    source: &str,
259    table: &crate::parsers::MatchTable<'_>,
260) -> Result<Vec<SearchResult>> {
261    extract_symbols(source, table, 8, SymbolKind::Module, None)
262}
263
264/// Extract type aliases
265fn extract_type_aliases(
266    source: &str,
267    table: &crate::parsers::MatchTable<'_>,
268) -> Result<Vec<SearchResult>> {
269    extract_symbols(source, table, 9, SymbolKind::Type, None)
270}
271
272/// Extract macro definitions (macro_rules!)
273fn extract_macros(
274    source: &str,
275    table: &crate::parsers::MatchTable<'_>,
276) -> Result<Vec<SearchResult>> {
277    extract_symbols(source, table, 10, SymbolKind::Macro, None)
278}
279
280/// Extract attributes: BOTH definitions and uses
281/// Definitions: #[proc_macro_attribute] pub fn route(...)
282/// Uses: #[test] fn my_test(), #[derive(Debug)] struct Foo
283fn extract_attributes(
284    source: &str,
285    table: &crate::parsers::MatchTable<'_>,
286) -> Result<Vec<SearchResult>> {
287    let mut symbols = Vec::new();
288
289    // Part 1: Extract attribute DEFINITIONS (proc macro attributes)
290
291    let func_query = table.query();
292    let matches = table.sub(12);
293
294    for match_ in matches {
295        let mut name = None;
296        let mut func_node = None;
297
298        for capture in &match_.captures {
299            let capture_name: &str = func_query.capture_names()[capture.index as usize];
300            match capture_name {
301                "name" => {
302                    name = Some(
303                        capture
304                            .node
305                            .utf8_text(source.as_bytes())
306                            .unwrap_or("")
307                            .to_string(),
308                    );
309                }
310                "function" => {
311                    func_node = Some(capture.node);
312                }
313                _ => {}
314            }
315        }
316
317        // Check if this function has #[proc_macro_attribute] attribute
318        if let (Some(name), Some(func_node)) = (name, func_node) {
319            let mut has_proc_macro_attr = false;
320
321            if let Some(parent) = func_node.parent() {
322                let mut func_index = None;
323                for i in 0..parent.child_count() {
324                    if let Some(child) = parent.child(i as u32)
325                        && child.id() == func_node.id()
326                    {
327                        func_index = Some(i);
328                        break;
329                    }
330                }
331
332                if let Some(func_idx) = func_index {
333                    for i in (0..func_idx).rev() {
334                        if let Some(child) = parent.child(i as u32) {
335                            if child.kind() == "attribute_item" {
336                                let attr_text = child.utf8_text(source.as_bytes()).unwrap_or("");
337                                if attr_text.contains("proc_macro_attribute") {
338                                    has_proc_macro_attr = true;
339                                }
340                            } else if !child.kind().contains("comment")
341                                && child.kind() != "line_comment"
342                            {
343                                break;
344                            }
345                        }
346                    }
347                }
348            }
349
350            if has_proc_macro_attr {
351                let span = node_to_span(&func_node);
352                let preview = extract_preview(source, &func_node);
353
354                symbols.push(SearchResult::new(
355                    String::new(),
356                    Language::Rust,
357                    SymbolKind::Attribute,
358                    Some(name),
359                    span,
360                    None,
361                    preview,
362                ));
363            }
364        }
365    }
366
367    // Part 2: Extract attribute USES (#[test], #[derive(...)], etc.)
368
369    let attr_query = table.query();
370    let matches = table.sub(11);
371
372    for match_ in matches {
373        let mut attr_name = None;
374        let mut attr_node = None;
375
376        for capture in &match_.captures {
377            let capture_name: &str = attr_query.capture_names()[capture.index as usize];
378            match capture_name {
379                "attr_name" => {
380                    attr_name = Some(
381                        capture
382                            .node
383                            .utf8_text(source.as_bytes())
384                            .unwrap_or("")
385                            .to_string(),
386                    );
387                }
388                "attr" => {
389                    attr_node = Some(capture.node);
390                }
391                _ => {}
392            }
393        }
394
395        if let (Some(name), Some(node)) = (attr_name, attr_node) {
396            let span = node_to_span(&node);
397            let preview = extract_preview(source, &node);
398
399            symbols.push(SearchResult::new(
400                String::new(),
401                Language::Rust,
402                SymbolKind::Attribute,
403                Some(name),
404                span,
405                None,
406                preview,
407            ));
408        }
409    }
410
411    Ok(symbols)
412}
413
414/// Generic symbol extraction helper
415fn extract_symbols(
416    source: &str,
417    table: &crate::parsers::MatchTable<'_>,
418    sub: usize,
419    kind: SymbolKind,
420    scope: Option<String>,
421) -> Result<Vec<SearchResult>> {
422    let query = table.query();
423    let matches = table.sub(sub);
424
425    let mut symbols = Vec::new();
426
427    for match_ in matches {
428        // Find the name capture and the full node
429        let mut name = None;
430        let mut full_node = None;
431
432        for capture in &match_.captures {
433            let capture_name: &str = query.capture_names()[capture.index as usize];
434            if capture_name == "name" {
435                name = Some(
436                    capture
437                        .node
438                        .utf8_text(source.as_bytes())
439                        .unwrap_or("")
440                        .to_string(),
441                );
442            } else {
443                // Assume any other capture is the full node
444                full_node = Some(capture.node);
445            }
446        }
447
448        if let (Some(name), Some(node)) = (name, full_node) {
449            let span = node_to_span(&node);
450            let preview = extract_preview(source, &node);
451
452            symbols.push(SearchResult::new(
453                String::new(), // Path will be filled in later
454                Language::Rust,
455                kind.clone(),
456                Some(name),
457                span,
458                scope.clone(),
459                preview,
460            ));
461        }
462    }
463
464    Ok(symbols)
465}
466
467/// Convert a Tree-sitter node to a Span
468fn node_to_span(node: &tree_sitter::Node) -> Span {
469    let start = node.start_position();
470    let end = node.end_position();
471
472    Span::new(
473        start.row + 1, // Convert 0-indexed to 1-indexed
474        start.column,
475        end.row + 1,
476        end.column,
477    )
478}
479
480/// Extract a preview (5-7 lines) around the symbol
481fn extract_preview(source: &str, node: &tree_sitter::Node) -> String {
482    // Starts at the node, not at byte 0: see `crate::parsers::preview`.
483    crate::parsers::preview::extract_preview_for_node(source, node)
484}
485
486/// Rust dependency extractor implementation
487pub struct RustDependencyExtractor;
488
489impl DependencyExtractor for RustDependencyExtractor {
490    fn extract_dependencies(source: &str) -> Result<Vec<ImportInfo>> {
491        let mut parser = Parser::new();
492        let language = tree_sitter_rust::LANGUAGE;
493
494        parser
495            .set_language(&language.into())
496            .context("Failed to set Rust language")?;
497
498        let tree = parser
499            .parse(source, None)
500            .context("Failed to parse Rust source")?;
501
502        let root_node = tree.root_node();
503
504        let mut imports = Vec::new();
505
506        // Extract use declarations
507        imports.extend(extract_use_declarations(source, &root_node)?);
508
509        // Extract mod items (module declarations)
510        imports.extend(extract_mod_items(source, &root_node)?);
511
512        // Extract extern crate declarations
513        imports.extend(extract_extern_crates(source, &root_node)?);
514
515        Ok(imports)
516    }
517}
518
519/// Extract use declarations (use std::collections::HashMap)
520fn extract_use_declarations(source: &str, root: &tree_sitter::Node) -> Result<Vec<ImportInfo>> {
521    let language = tree_sitter_rust::LANGUAGE;
522    let query_str = r#"
523        (use_declaration) @use
524    "#;
525
526    static QUERY_12: crate::parsers::CachedQuery = crate::parsers::CachedQuery::new();
527    let query = crate::parsers::cached_query(&QUERY_12, language, query_str)
528        .context("Failed to create use declaration query")?;
529
530    let mut cursor = QueryCursor::new();
531    let mut matches = cursor.matches(query, *root, source.as_bytes());
532
533    let mut imports = Vec::new();
534
535    while let Some(match_) = matches.next() {
536        for capture in match_.captures {
537            let node = capture.node;
538            let text = node.utf8_text(source.as_bytes()).unwrap_or("");
539            let line_number = node.start_position().row + 1;
540
541            // Parse the use declaration text
542            let path_info = parse_rust_use_declaration(text);
543
544            for (path, symbols) in path_info {
545                let import_type = classify_rust_import(&path);
546
547                imports.push(ImportInfo {
548                    imported_path: path,
549                    import_type,
550                    line_number,
551                    imported_symbols: symbols,
552                });
553            }
554        }
555    }
556
557    Ok(imports)
558}
559
560/// Extract mod items (mod parser;)
561fn extract_mod_items(source: &str, root: &tree_sitter::Node) -> Result<Vec<ImportInfo>> {
562    let language = tree_sitter_rust::LANGUAGE;
563    let query_str = r#"
564        (mod_item
565            name: (identifier) @name) @mod
566    "#;
567
568    static QUERY_13: crate::parsers::CachedQuery = crate::parsers::CachedQuery::new();
569    let query = crate::parsers::cached_query(&QUERY_13, language, query_str)
570        .context("Failed to create mod item query")?;
571
572    let mut cursor = QueryCursor::new();
573    let mut matches = cursor.matches(query, *root, source.as_bytes());
574
575    let mut imports = Vec::new();
576
577    while let Some(match_) = matches.next() {
578        let mut name = None;
579        let mut mod_node = None;
580
581        for capture in match_.captures {
582            let capture_name: &str = query.capture_names()[capture.index as usize];
583            match capture_name {
584                "name" => {
585                    name = Some(
586                        capture
587                            .node
588                            .utf8_text(source.as_bytes())
589                            .unwrap_or("")
590                            .to_string(),
591                    );
592                }
593                "mod" => {
594                    mod_node = Some(capture.node);
595                }
596                _ => {}
597            }
598        }
599
600        if let (Some(name), Some(node)) = (name, mod_node) {
601            // Check if this is an external module declaration (no body)
602            let has_body = node.child_by_field_name("body").is_some();
603
604            if !has_body {
605                // This is an external module reference (mod parser;)
606                let line_number = node.start_position().row + 1;
607
608                imports.push(ImportInfo {
609                    imported_path: name,
610                    // ModDecl marks parent→child ownership; excluded from cycle detection (REF-88)
611                    import_type: crate::models::ImportType::ModDecl,
612                    line_number,
613                    imported_symbols: None,
614                });
615            }
616        }
617    }
618
619    Ok(imports)
620}
621
622/// Extract extern crate declarations (extern crate serde;)
623fn extract_extern_crates(source: &str, root: &tree_sitter::Node) -> Result<Vec<ImportInfo>> {
624    let language = tree_sitter_rust::LANGUAGE;
625    let query_str = r#"
626        (extern_crate_declaration
627            name: (identifier) @name) @extern
628    "#;
629
630    static QUERY_14: crate::parsers::CachedQuery = crate::parsers::CachedQuery::new();
631    let query = crate::parsers::cached_query(&QUERY_14, language, query_str)
632        .context("Failed to create extern crate query")?;
633
634    let mut cursor = QueryCursor::new();
635    let mut matches = cursor.matches(query, *root, source.as_bytes());
636
637    let mut imports = Vec::new();
638
639    while let Some(match_) = matches.next() {
640        let mut name = None;
641        let mut extern_node = None;
642
643        for capture in match_.captures {
644            let capture_name: &str = query.capture_names()[capture.index as usize];
645            match capture_name {
646                "name" => {
647                    name = Some(
648                        capture
649                            .node
650                            .utf8_text(source.as_bytes())
651                            .unwrap_or("")
652                            .to_string(),
653                    );
654                }
655                "extern" => {
656                    extern_node = Some(capture.node);
657                }
658                _ => {}
659            }
660        }
661
662        if let (Some(name), Some(node)) = (name, extern_node) {
663            let line_number = node.start_position().row + 1;
664            let import_type = classify_rust_import(&name);
665
666            imports.push(ImportInfo {
667                imported_path: name,
668                import_type,
669                line_number,
670                imported_symbols: None,
671            });
672        }
673    }
674
675    Ok(imports)
676}
677
678/// Classify a Rust import path as Internal, External, or Stdlib
679fn classify_rust_import(path: &str) -> crate::models::ImportType {
680    use crate::models::ImportType;
681
682    if path.starts_with("std::") || path.starts_with("core::") || path.starts_with("alloc::") {
683        ImportType::Stdlib
684    } else if path.starts_with("crate::")
685        || path.starts_with("super::")
686        || path.starts_with("self::")
687    {
688        ImportType::Internal
689    } else {
690        // External crate
691        ImportType::External
692    }
693}
694
695/// Parse a Rust use declaration and extract path(s) and symbols
696///
697/// Handles:
698/// - Simple: use std::collections::HashMap;
699/// - With symbols: use std::collections::{HashMap, HashSet};
700/// - Nested: use std::{io, fs};
701/// - With aliases: use std::io::Result as IoResult;
702/// - Glob: use std::collections::*;
703fn parse_rust_use_declaration(text: &str) -> Vec<(String, Option<Vec<String>>)> {
704    // Remove visibility modifiers and keywords
705    let text = text
706        .trim()
707        .strip_prefix("pub(crate)")
708        .unwrap_or(text)
709        .trim()
710        .strip_prefix("pub(super)")
711        .unwrap_or(text)
712        .trim()
713        .strip_prefix("pub")
714        .unwrap_or(text)
715        .trim()
716        .strip_prefix("use")
717        .unwrap_or(text)
718        .trim()
719        .strip_suffix(";")
720        .unwrap_or(text)
721        .trim();
722
723    // Handle different patterns
724    if text.contains('{') {
725        // Has braces - extract base path and symbols
726        if let Some(idx) = text.find('{') {
727            let base_path = text[..idx].trim_end_matches("::").to_string();
728
729            if let Some(end) = text.find('}') {
730                let symbols_str = &text[idx + 1..end];
731                let symbols: Vec<String> = symbols_str
732                    .split(',')
733                    .map(|s| {
734                        // Handle aliases like "HashMap as Map" - extract the imported name
735                        let trimmed = s.trim();
736                        if let Some(as_idx) = trimmed.find(" as ") {
737                            trimmed[..as_idx].trim().to_string()
738                        } else {
739                            trimmed.to_string()
740                        }
741                    })
742                    .filter(|s| !s.is_empty() && s != "*")
743                    .collect();
744
745                if !symbols.is_empty() {
746                    return vec![(base_path, Some(symbols))];
747                }
748            }
749        }
750    }
751
752    // Simple path (possibly with alias)
753    let path = if let Some(as_idx) = text.find(" as ") {
754        text[..as_idx].trim().to_string()
755    } else {
756        text.to_string()
757    };
758
759    vec![(path, None)]
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765
766    #[test]
767    fn test_parse_function() {
768        let source = r#"
769            fn hello_world() {
770                println!("Hello, world!");
771            }
772        "#;
773
774        let symbols = parse("test.rs", source).unwrap();
775        assert_eq!(symbols.len(), 1);
776        assert_eq!(symbols[0].symbol.as_deref(), Some("hello_world"));
777        assert!(matches!(symbols[0].kind, SymbolKind::Function));
778    }
779
780    #[test]
781    fn test_parse_struct() {
782        let source = r#"
783            struct User {
784                name: String,
785                age: u32,
786            }
787        "#;
788
789        let symbols = parse("test.rs", source).unwrap();
790        assert_eq!(symbols.len(), 1);
791        assert_eq!(symbols[0].symbol.as_deref(), Some("User"));
792        assert!(matches!(symbols[0].kind, SymbolKind::Struct));
793    }
794
795    #[test]
796    fn test_parse_impl() {
797        let source = r#"
798            struct User {
799                name: String,
800            }
801
802            impl User {
803                fn new(name: String) -> Self {
804                    User { name }
805                }
806
807                fn get_name(&self) -> &str {
808                    &self.name
809                }
810            }
811        "#;
812
813        let symbols = parse("test.rs", source).unwrap();
814
815        // Should find: struct User, method new, method get_name
816        assert!(symbols.len() >= 3);
817
818        let method_symbols: Vec<_> = symbols
819            .iter()
820            .filter(|s| matches!(s.kind, SymbolKind::Method))
821            .collect();
822
823        assert_eq!(method_symbols.len(), 2);
824        assert!(
825            method_symbols
826                .iter()
827                .any(|s| s.symbol.as_deref() == Some("new"))
828        );
829        assert!(
830            method_symbols
831                .iter()
832                .any(|s| s.symbol.as_deref() == Some("get_name"))
833        );
834
835        // Note: scope field was removed from SearchResult for token optimization
836        // Methods are identified by SymbolKind::Method
837    }
838
839    #[test]
840    fn test_parse_enum() {
841        let source = r#"
842            enum Status {
843                Active,
844                Inactive,
845            }
846        "#;
847
848        let symbols = parse("test.rs", source).unwrap();
849        assert_eq!(symbols.len(), 1);
850        assert_eq!(symbols[0].symbol.as_deref(), Some("Status"));
851        assert!(matches!(symbols[0].kind, SymbolKind::Enum));
852    }
853
854    #[test]
855    fn test_parse_trait() {
856        let source = r#"
857            trait Drawable {
858                fn draw(&self);
859            }
860        "#;
861
862        let symbols = parse("test.rs", source).unwrap();
863        assert_eq!(symbols.len(), 1);
864        assert_eq!(symbols[0].symbol.as_deref(), Some("Drawable"));
865        assert!(matches!(symbols[0].kind, SymbolKind::Trait));
866    }
867
868    #[test]
869    fn test_parse_multiple_symbols() {
870        let source = r#"
871            const MAX_SIZE: usize = 100;
872
873            struct Config {
874                size: usize,
875            }
876
877            fn create_config() -> Config {
878                Config { size: MAX_SIZE }
879            }
880        "#;
881
882        let symbols = parse("test.rs", source).unwrap();
883
884        // Should find: const, struct, function
885        assert_eq!(symbols.len(), 3);
886
887        let kinds: Vec<&SymbolKind> = symbols.iter().map(|s| &s.kind).collect();
888        assert!(kinds.contains(&&SymbolKind::Constant));
889        assert!(kinds.contains(&&SymbolKind::Struct));
890        assert!(kinds.contains(&&SymbolKind::Function));
891    }
892
893    #[test]
894    fn test_local_variables_included() {
895        let source = r#"
896            fn calculate(input: i32) -> i32 {
897                let local_var = input * 2;
898                let result = local_var + 10;
899                result
900            }
901
902            struct Calculator;
903
904            impl Calculator {
905                fn compute(&self, value: i32) -> i32 {
906                    let temp = value * 3;
907                    let mut final_value = temp + 5;
908                    final_value += 1;
909                    final_value
910                }
911            }
912        "#;
913
914        let symbols = parse("test.rs", source).unwrap();
915
916        // Filter to just variables
917        let variables: Vec<_> = symbols
918            .iter()
919            .filter(|s| matches!(s.kind, SymbolKind::Variable))
920            .collect();
921
922        // Check that local variables are captured
923        assert!(
924            variables
925                .iter()
926                .any(|v| v.symbol.as_deref() == Some("local_var"))
927        );
928        assert!(
929            variables
930                .iter()
931                .any(|v| v.symbol.as_deref() == Some("result"))
932        );
933        assert!(
934            variables
935                .iter()
936                .any(|v| v.symbol.as_deref() == Some("temp"))
937        );
938        assert!(
939            variables
940                .iter()
941                .any(|v| v.symbol.as_deref() == Some("final_value"))
942        );
943
944        // Note: scope field was removed from SearchResult for token optimization
945    }
946
947    #[test]
948    fn test_static_variables() {
949        let source = r#"
950            static GLOBAL_COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
951            static mut MUTABLE_GLOBAL: i32 = 0;
952
953            const MAX_SIZE: usize = 100;
954
955            fn increment() {
956                GLOBAL_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
957            }
958        "#;
959
960        let symbols = parse("test.rs", source).unwrap();
961
962        // Filter to statics and constants
963        let statics: Vec<_> = symbols
964            .iter()
965            .filter(|s| matches!(s.kind, SymbolKind::Variable))
966            .collect();
967
968        let constants: Vec<_> = symbols
969            .iter()
970            .filter(|s| matches!(s.kind, SymbolKind::Constant))
971            .collect();
972
973        // Check that static variables are captured
974        assert!(
975            statics
976                .iter()
977                .any(|v| v.symbol.as_deref() == Some("GLOBAL_COUNTER"))
978        );
979        assert!(
980            statics
981                .iter()
982                .any(|v| v.symbol.as_deref() == Some("MUTABLE_GLOBAL"))
983        );
984
985        // Check that constants are still separate
986        assert!(
987            constants
988                .iter()
989                .any(|c| c.symbol.as_deref() == Some("MAX_SIZE"))
990        );
991    }
992
993    #[test]
994    fn test_macros() {
995        let source = r#"
996            macro_rules! say_hello {
997                () => {
998                    println!("Hello!");
999                };
1000            }
1001
1002            macro_rules! vec_of_strings {
1003                ($($x:expr),*) => {
1004                    vec![$($x.to_string()),*]
1005                };
1006            }
1007
1008            fn main() {
1009                say_hello!();
1010            }
1011        "#;
1012
1013        let symbols = parse("test.rs", source).unwrap();
1014
1015        // Filter to macros
1016        let macros: Vec<_> = symbols
1017            .iter()
1018            .filter(|s| matches!(s.kind, SymbolKind::Macro))
1019            .collect();
1020
1021        // Check that macros are captured
1022        assert!(
1023            macros
1024                .iter()
1025                .any(|m| m.symbol.as_deref() == Some("say_hello"))
1026        );
1027        assert!(
1028            macros
1029                .iter()
1030                .any(|m| m.symbol.as_deref() == Some("vec_of_strings"))
1031        );
1032        assert_eq!(macros.len(), 2);
1033    }
1034
1035    #[test]
1036    fn test_attribute_proc_macros() {
1037        let source = r#"
1038            use proc_macro::TokenStream;
1039
1040            #[proc_macro_attribute]
1041            pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream {
1042                item
1043            }
1044
1045            #[proc_macro_attribute]
1046            pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
1047                item
1048            }
1049
1050            // Regular function - should NOT be captured
1051            pub fn helper() {}
1052        "#;
1053
1054        let symbols = parse("test.rs", source).unwrap();
1055
1056        // Filter to attributes
1057        let attributes: Vec<_> = symbols
1058            .iter()
1059            .filter(|s| matches!(s.kind, SymbolKind::Attribute))
1060            .collect();
1061
1062        // Check that attribute proc macro DEFINITIONS are captured
1063        assert!(
1064            attributes
1065                .iter()
1066                .any(|a| a.symbol.as_deref() == Some("test"))
1067        );
1068        assert!(
1069            attributes
1070                .iter()
1071                .any(|a| a.symbol.as_deref() == Some("route"))
1072        );
1073
1074        // Verify helper function is NOT captured as attribute
1075        assert!(
1076            !attributes
1077                .iter()
1078                .any(|a| a.symbol.as_deref() == Some("helper"))
1079        );
1080
1081        // Should find 2 proc macro definitions + 2 attribute uses (#[proc_macro_attribute])
1082        assert_eq!(attributes.len(), 4);
1083    }
1084
1085    #[test]
1086    fn test_attribute_uses() {
1087        let source = r#"
1088            #[test]
1089            fn test_something() {
1090                assert_eq!(1, 1);
1091            }
1092
1093            #[test]
1094            #[should_panic]
1095            fn test_panic() {
1096                panic!("expected");
1097            }
1098
1099            #[derive(Debug, Clone)]
1100            struct MyStruct {
1101                field: i32
1102            }
1103
1104            #[cfg(test)]
1105            mod tests {
1106                #[test]
1107                fn nested_test() {}
1108            }
1109        "#;
1110
1111        let symbols = parse("test.rs", source).unwrap();
1112
1113        // Filter to attributes
1114        let attributes: Vec<_> = symbols
1115            .iter()
1116            .filter(|s| matches!(s.kind, SymbolKind::Attribute))
1117            .collect();
1118
1119        // Check that attribute USES are captured
1120        assert!(
1121            attributes
1122                .iter()
1123                .any(|a| a.symbol.as_deref() == Some("test"))
1124        );
1125        assert!(
1126            attributes
1127                .iter()
1128                .any(|a| a.symbol.as_deref() == Some("should_panic"))
1129        );
1130        assert!(
1131            attributes
1132                .iter()
1133                .any(|a| a.symbol.as_deref() == Some("derive"))
1134        );
1135        assert!(
1136            attributes
1137                .iter()
1138                .any(|a| a.symbol.as_deref() == Some("cfg"))
1139        );
1140
1141        // Should find: test (3x), should_panic (1x), derive (1x), cfg (1x) = 6 total
1142        assert_eq!(attributes.len(), 6);
1143    }
1144
1145    #[test]
1146    fn test_extract_dependencies_use_declarations() {
1147        let source = r#"
1148            use std::collections::HashMap;
1149            use crate::models::{Language, SearchResult};
1150            use super::utils;
1151            use anyhow::Result;
1152        "#;
1153
1154        let deps = RustDependencyExtractor::extract_dependencies(source).unwrap();
1155
1156        // Should find 4 imports
1157        assert_eq!(deps.len(), 4);
1158
1159        // Check std import
1160        let std_import = deps
1161            .iter()
1162            .find(|d| d.imported_path == "std::collections::HashMap")
1163            .unwrap();
1164        assert!(matches!(
1165            std_import.import_type,
1166            crate::models::ImportType::Stdlib
1167        ));
1168
1169        // Check crate import with symbols
1170        let crate_import = deps
1171            .iter()
1172            .find(|d| d.imported_path == "crate::models")
1173            .unwrap();
1174        assert!(matches!(
1175            crate_import.import_type,
1176            crate::models::ImportType::Internal
1177        ));
1178        assert!(crate_import.imported_symbols.is_some());
1179        let symbols = crate_import.imported_symbols.as_ref().unwrap();
1180        assert_eq!(symbols.len(), 2);
1181        assert!(symbols.contains(&"Language".to_string()));
1182        assert!(symbols.contains(&"SearchResult".to_string()));
1183
1184        // Check super import
1185        let super_import = deps
1186            .iter()
1187            .find(|d| d.imported_path == "super::utils")
1188            .unwrap();
1189        assert!(matches!(
1190            super_import.import_type,
1191            crate::models::ImportType::Internal
1192        ));
1193
1194        // Check external import
1195        let external_import = deps
1196            .iter()
1197            .find(|d| d.imported_path == "anyhow::Result")
1198            .unwrap();
1199        assert!(matches!(
1200            external_import.import_type,
1201            crate::models::ImportType::External
1202        ));
1203    }
1204
1205    #[test]
1206    fn test_extract_dependencies_mod_declarations() {
1207        let source = r#"
1208            mod parser;
1209            mod utils;
1210
1211            mod inline {
1212                fn test() {}
1213            }
1214        "#;
1215
1216        let deps = RustDependencyExtractor::extract_dependencies(source).unwrap();
1217
1218        // Should find 2 external mod declarations (not the inline one)
1219        assert_eq!(deps.len(), 2);
1220        assert!(deps.iter().any(|d| d.imported_path == "parser"));
1221        assert!(deps.iter().any(|d| d.imported_path == "utils"));
1222        assert!(
1223            deps.iter()
1224                .all(|d| matches!(d.import_type, crate::models::ImportType::ModDecl))
1225        );
1226    }
1227
1228    #[test]
1229    fn test_extract_dependencies_extern_crate() {
1230        let source = r#"
1231            extern crate serde;
1232            extern crate serde_json;
1233        "#;
1234
1235        let deps = RustDependencyExtractor::extract_dependencies(source).unwrap();
1236
1237        // Should find 2 extern crate declarations
1238        assert_eq!(deps.len(), 2);
1239        assert!(deps.iter().any(|d| d.imported_path == "serde"));
1240        assert!(deps.iter().any(|d| d.imported_path == "serde_json"));
1241        assert!(
1242            deps.iter()
1243                .all(|d| matches!(d.import_type, crate::models::ImportType::External))
1244        );
1245    }
1246
1247    #[test]
1248    fn test_parse_use_with_aliases() {
1249        let source = r#"
1250            use std::io::Result as IoResult;
1251            use std::collections::{HashMap as Map, HashSet};
1252        "#;
1253
1254        let deps = RustDependencyExtractor::extract_dependencies(source).unwrap();
1255
1256        // Check alias handling - should extract the original name
1257        let io_import = deps
1258            .iter()
1259            .find(|d| d.imported_path == "std::io::Result")
1260            .unwrap();
1261        assert!(matches!(
1262            io_import.import_type,
1263            crate::models::ImportType::Stdlib
1264        ));
1265
1266        let collections_import = deps
1267            .iter()
1268            .find(|d| d.imported_path == "std::collections")
1269            .unwrap();
1270        let symbols = collections_import.imported_symbols.as_ref().unwrap();
1271        assert_eq!(symbols.len(), 2);
1272        assert!(symbols.contains(&"HashMap".to_string()));
1273        assert!(symbols.contains(&"HashSet".to_string()));
1274    }
1275
1276    #[test]
1277    fn test_classify_rust_imports() {
1278        use crate::models::ImportType;
1279
1280        // Stdlib
1281        assert!(matches!(
1282            classify_rust_import("std::collections::HashMap"),
1283            ImportType::Stdlib
1284        ));
1285        assert!(matches!(
1286            classify_rust_import("core::ptr"),
1287            ImportType::Stdlib
1288        ));
1289        assert!(matches!(
1290            classify_rust_import("alloc::vec::Vec"),
1291            ImportType::Stdlib
1292        ));
1293
1294        // Internal
1295        assert!(matches!(
1296            classify_rust_import("crate::models::Language"),
1297            ImportType::Internal
1298        ));
1299        assert!(matches!(
1300            classify_rust_import("super::utils"),
1301            ImportType::Internal
1302        ));
1303        assert!(matches!(
1304            classify_rust_import("self::helper"),
1305            ImportType::Internal
1306        ));
1307
1308        // External
1309        assert!(matches!(
1310            classify_rust_import("serde::Serialize"),
1311            ImportType::External
1312        ));
1313        assert!(matches!(
1314            classify_rust_import("anyhow::Result"),
1315            ImportType::External
1316        ));
1317        assert!(matches!(
1318            classify_rust_import("tokio::runtime"),
1319            ImportType::External
1320        ));
1321    }
1322}
1323
1324// ============================================================================
1325// Path Resolution
1326// ============================================================================
1327
1328/// Find the crate root (directory containing Cargo.toml) by walking up from a given path
1329fn find_crate_root(start_path: &str) -> Option<String> {
1330    let path = std::path::Path::new(start_path);
1331    let mut current = path.parent()?;
1332
1333    // Walk up until we find Cargo.toml
1334    loop {
1335        let cargo_toml = current.join("Cargo.toml");
1336        if cargo_toml.exists() {
1337            return Some(current.to_string_lossy().to_string());
1338        }
1339
1340        // For test paths that don't exist, assume standard Rust structure:
1341        // If we find "/src" in the path, the parent of "src" is likely the crate root
1342        if current.ends_with("src")
1343            && let Some(parent) = current.parent()
1344        {
1345            return Some(parent.to_string_lossy().to_string());
1346        }
1347
1348        // Move up to parent directory
1349        current = match current.parent() {
1350            Some(p) if p.as_os_str().is_empty() => return None,
1351            Some(p) => p,
1352            None => return None,
1353        };
1354    }
1355}
1356
1357/// Resolve a Rust use statement to a file path
1358///
1359/// Handles:
1360/// - `crate::` imports: `crate::models::Language` → `src/models.rs` or `src/models/mod.rs`
1361/// - `super::` imports: relative to parent module
1362/// - `self::` imports: relative to current module
1363/// - `mod parser;`: look for `parser.rs` or `parser/mod.rs`
1364///
1365/// Does NOT handle:
1366/// - External crate imports (would require parsing Cargo.toml dependencies)
1367/// - Stdlib imports (std::, core::, alloc::)
1368pub fn resolve_rust_use_to_path(
1369    import_path: &str,
1370    current_file_path: Option<&str>,
1371    project_root: Option<&str>,
1372) -> Option<String> {
1373    // Only handle internal imports (crate::, super::, self::, or bare module names)
1374    if !import_path.starts_with("crate::")
1375        && !import_path.starts_with("super::")
1376        && !import_path.starts_with("self::")
1377    {
1378        // Check if it's a simple module name (no :: separator at all)
1379        if import_path.contains("::") {
1380            return None; // External or stdlib import
1381        }
1382        // Fall through for simple module names like "parser"
1383    }
1384
1385    let current_file = current_file_path?;
1386
1387    // Resolve the current file to an absolute path (against project_root when it is
1388    // relative) so that all `.exists()` checks below are independent of the process's
1389    // current working directory. The resolved path is converted back to a
1390    // workspace-relative path before returning (see `relativize_to_project_root`), so it
1391    // matches the paths stored in the dependency index.
1392    let abs_current = match project_root {
1393        Some(root) if !root.is_empty() && std::path::Path::new(current_file).is_relative() => {
1394            std::path::Path::new(root).join(current_file)
1395        }
1396        _ => std::path::PathBuf::from(current_file),
1397    };
1398    let current_file = abs_current.to_string_lossy().to_string();
1399    let current_path = abs_current.as_path();
1400
1401    // Find the crate root
1402    let crate_root = find_crate_root(&current_file)?;
1403    let crate_root_path = std::path::Path::new(&crate_root);
1404
1405    let resolved = if import_path.starts_with("crate::") {
1406        // Resolve from crate root (typically src/)
1407        let module_path = import_path.strip_prefix("crate::").unwrap();
1408        let parts: Vec<&str> = module_path.split("::").collect();
1409
1410        // Try src/ first (standard Rust project structure)
1411        let src_root = crate_root_path.join("src");
1412        // Resolve the longest prefix of `parts` that names a real module file, popping
1413        // trailing item segments (a type/fn/const/trait is not a module). Fall back to a
1414        // best-guess path so the indexer can still attempt a lookup.
1415        resolve_longest_module_prefix(&src_root, &parts)
1416            .or_else(|| resolve_rust_module_path(&src_root, &parts))
1417    } else if import_path.starts_with("super::") {
1418        // Resolve relative to parent module
1419        let module_path = import_path.strip_prefix("super::").unwrap();
1420        let parts: Vec<&str> = module_path.split("::").collect();
1421
1422        // Get parent directory (go up one level)
1423        let current_dir = if current_path.file_name().unwrap() == "mod.rs" {
1424            // If current file is mod.rs, go up two levels
1425            current_path.parent()?.parent()?
1426        } else {
1427            // Otherwise, go up one level
1428            current_path.parent()?
1429        };
1430
1431        resolve_longest_module_prefix(current_dir, &parts)
1432            .or_else(|| resolve_rust_module_path(current_dir, &parts))
1433    } else if import_path.starts_with("self::") {
1434        // Resolve relative to current module
1435        let module_path = import_path.strip_prefix("self::").unwrap();
1436        let parts: Vec<&str> = module_path.split("::").collect();
1437
1438        // Get current module directory
1439        let current_dir = if current_path.file_name().unwrap() == "mod.rs" {
1440            // If current file is mod.rs, use parent directory
1441            current_path.parent()?
1442        } else {
1443            // Otherwise, use current directory
1444            current_path.parent()?
1445        };
1446
1447        resolve_longest_module_prefix(current_dir, &parts)
1448            .or_else(|| resolve_rust_module_path(current_dir, &parts))
1449    } else {
1450        // Simple module name (e.g., "parser" in "mod parser;")
1451        // Look for parser.rs or parser/mod.rs in the current directory
1452        let current_dir = current_path.parent()?;
1453        let module_file = current_dir.join(format!("{}.rs", import_path));
1454        let module_dir = current_dir.join(import_path).join("mod.rs");
1455
1456        if module_file.exists() {
1457            Some(module_file.to_string_lossy().to_string())
1458        } else if module_dir.exists() {
1459            Some(module_dir.to_string_lossy().to_string())
1460        } else {
1461            // Return the most likely candidate even if it doesn't exist
1462            // The indexer will check if the file is actually in the index
1463            Some(module_file.to_string_lossy().to_string())
1464        }
1465    };
1466
1467    // Convert the resolved absolute path back to a workspace-relative path so it matches
1468    // the paths stored in the dependency index (see `abs_current` above).
1469    resolved.map(|path| relativize_to_project_root(&path, project_root))
1470}
1471
1472/// Resolve the longest prefix of `parts` that names a real module file under `base_dir`.
1473///
1474/// Pops trailing item segments (a type/fn/const/trait is not a module) until a prefix
1475/// resolves to a file that actually exists. Returns `None` if even the one-segment prefix
1476/// has no backing file, leaving the caller to fall back to a best guess or cross-crate
1477/// resolution. Unlike `resolve_rust_module_path`, every returned candidate is checked for
1478/// existence, so that function's best-guess return is harmless here.
1479fn resolve_longest_module_prefix(base_dir: &std::path::Path, parts: &[&str]) -> Option<String> {
1480    let mut k = parts.len();
1481    while k >= 1 {
1482        if let Some(path) = resolve_rust_module_path(base_dir, &parts[..k])
1483            && std::path::Path::new(&path).exists()
1484        {
1485            return Some(path);
1486        }
1487        k -= 1;
1488    }
1489    None
1490}
1491
1492/// Strip `project_root` from an absolute resolved path to yield a workspace-relative path.
1493///
1494/// Returns the path (still normalized to forward slashes) unchanged when `project_root` is
1495/// absent/empty or is not a prefix of `path` (e.g. the input was already relative).
1496///
1497/// The result always uses forward slashes so resolved import paths are deterministic and
1498/// match the forward-slash paths stored in the dependency index on every platform. Without
1499/// this, `PathBuf::join` yields backslash-separated paths on Windows, which would neither
1500/// match the index nor equal the expected output (see the other parsers, which normalize
1501/// the same way).
1502fn relativize_to_project_root(path: &str, project_root: Option<&str>) -> String {
1503    if let Some(root) = project_root
1504        && !root.is_empty()
1505        && let Ok(rel) = std::path::Path::new(path).strip_prefix(root)
1506    {
1507        return rel.to_string_lossy().replace('\\', "/");
1508    }
1509    path.replace('\\', "/")
1510}
1511
1512/// Resolve a Rust module path (list of components) to a file path
1513///
1514/// Examples:
1515/// - `["models"]` → `models.rs` or `models/mod.rs`
1516/// - `["models", "language"]` → `models/language.rs` or `models/language/mod.rs`
1517fn resolve_rust_module_path(base_dir: &std::path::Path, parts: &[&str]) -> Option<String> {
1518    if parts.is_empty() {
1519        return None;
1520    }
1521
1522    // Build the path incrementally
1523    let mut current_path = base_dir.to_path_buf();
1524
1525    for (i, part) in parts.iter().enumerate() {
1526        if i == parts.len() - 1 {
1527            // Last component - try both .rs file and mod.rs
1528            let file_path = current_path.join(format!("{}.rs", part));
1529            let mod_path = current_path.join(part).join("mod.rs");
1530
1531            log::trace!("Checking Rust module path: {}", file_path.display());
1532            log::trace!("Checking Rust module path: {}", mod_path.display());
1533
1534            // Return the first candidate (indexer will validate it exists)
1535            if file_path.exists() {
1536                return Some(file_path.to_string_lossy().to_string());
1537            } else if mod_path.exists() {
1538                return Some(mod_path.to_string_lossy().to_string());
1539            } else {
1540                // Return most likely candidate even if it doesn't exist
1541                return Some(file_path.to_string_lossy().to_string());
1542            }
1543        } else {
1544            // Intermediate component - must be a directory
1545            current_path = current_path.join(part);
1546        }
1547    }
1548
1549    None
1550}
1551
1552#[cfg(test)]
1553mod path_resolution_tests {
1554    use super::*;
1555
1556    #[test]
1557    fn test_resolve_crate_import() {
1558        // crate::models::Language
1559        let result = resolve_rust_use_to_path(
1560            "crate::models",
1561            Some("/home/user/project/src/main.rs"),
1562            Some("/home/user/project"),
1563        );
1564
1565        assert!(result.is_some());
1566        let path = result.unwrap();
1567        // Should resolve to src/models.rs or src/models/mod.rs
1568        assert!(path.contains("models.rs") || path.contains("models/mod.rs"));
1569    }
1570
1571    #[test]
1572    fn test_resolve_super_import() {
1573        // super::utils from src/commands/index.rs
1574        let result = resolve_rust_use_to_path(
1575            "super::utils",
1576            Some("/home/user/project/src/commands/index.rs"),
1577            Some("/home/user/project"),
1578        );
1579
1580        assert!(result.is_some());
1581        let path = result.unwrap();
1582        // Should resolve to src/utils.rs
1583        assert!(path.contains("src") && path.contains("utils.rs"));
1584    }
1585
1586    #[test]
1587    fn test_resolve_self_import() {
1588        // self::helper from src/models/mod.rs
1589        let result = resolve_rust_use_to_path(
1590            "self::helper",
1591            Some("/home/user/project/src/models/mod.rs"),
1592            Some("/home/user/project"),
1593        );
1594
1595        assert!(result.is_some());
1596        let path = result.unwrap();
1597        // Should resolve to src/models/helper.rs
1598        assert!(path.contains("models") && path.contains("helper.rs"));
1599    }
1600
1601    #[test]
1602    fn test_resolve_mod_declaration() {
1603        // mod parser; from src/main.rs
1604        let result = resolve_rust_use_to_path(
1605            "parser",
1606            Some("/home/user/project/src/main.rs"),
1607            Some("/home/user/project"),
1608        );
1609
1610        assert!(result.is_some());
1611        let path = result.unwrap();
1612        // Should resolve to src/parser.rs
1613        assert!(path.contains("parser.rs"));
1614    }
1615
1616    #[test]
1617    fn test_resolve_nested_crate_import() {
1618        // crate::models::language::Language
1619        let result = resolve_rust_use_to_path(
1620            "crate::models::language",
1621            Some("/home/user/project/src/main.rs"),
1622            Some("/home/user/project"),
1623        );
1624
1625        assert!(result.is_some());
1626        let path = result.unwrap();
1627        // Should resolve to src/models/language.rs or src/models/language/mod.rs
1628        assert!(
1629            path.contains("models")
1630                && (path.contains("language.rs") || path.contains("language/mod.rs"))
1631        );
1632    }
1633
1634    #[test]
1635    fn test_external_import_not_supported() {
1636        // anyhow::Result (external crate)
1637        let result = resolve_rust_use_to_path(
1638            "anyhow::Result",
1639            Some("/home/user/project/src/main.rs"),
1640            Some("/home/user/project"),
1641        );
1642
1643        // Should return None for external imports
1644        assert!(result.is_none());
1645    }
1646
1647    #[test]
1648    fn test_stdlib_import_not_supported() {
1649        // std::collections::HashMap (stdlib)
1650        let result = resolve_rust_use_to_path(
1651            "std::collections::HashMap",
1652            Some("/home/user/project/src/main.rs"),
1653            Some("/home/user/project"),
1654        );
1655
1656        // Should return None for stdlib imports
1657        assert!(result.is_none());
1658    }
1659
1660    #[test]
1661    fn test_resolve_without_current_file() {
1662        let result = resolve_rust_use_to_path("crate::models", None, Some("/home/user/project"));
1663
1664        // Should return None if no current file provided
1665        assert!(result.is_none());
1666    }
1667
1668    // ------------------------------------------------------------------
1669    // Filesystem-backed tests for trailing-item resolution (P1) and
1670    // CWD-independence (P2). These build a real temp workspace because the
1671    // resolver gates candidates on `.exists()`; string-only fixtures (above)
1672    // cannot exercise the prefix-popping path.
1673    // ------------------------------------------------------------------
1674
1675    use std::io::Write;
1676    use tempfile::TempDir;
1677
1678    fn write_file(root: &std::path::Path, rel: &str, contents: &str) {
1679        let path = root.join(rel);
1680        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1681        let mut f = std::fs::File::create(&path).unwrap();
1682        f.write_all(contents.as_bytes()).unwrap();
1683    }
1684
1685    /// Build a single-crate workspace `<tmp>/crates/a` with a few modules.
1686    fn make_workspace() -> TempDir {
1687        let tmp = TempDir::new().unwrap();
1688        let root = tmp.path();
1689        write_file(root, "crates/a/Cargo.toml", "[package]\nname = \"a\"\n");
1690        write_file(
1691            root,
1692            "crates/a/src/lib.rs",
1693            "pub mod thing;\npub mod user;\n",
1694        );
1695        write_file(root, "crates/a/src/thing.rs", "pub struct Thing;\n");
1696        write_file(root, "crates/a/src/thing/inner.rs", "pub struct Deep;\n");
1697        write_file(root, "crates/a/src/user.rs", "use crate::thing::Thing;\n");
1698        tmp
1699    }
1700
1701    #[test]
1702    fn test_trailing_item_single_module() {
1703        // crate::thing::Thing  ->  crates/a/src/thing.rs  (Thing is an item, not a module)
1704        let tmp = make_workspace();
1705        let root = tmp.path().to_str().unwrap();
1706        let result = resolve_rust_use_to_path(
1707            "crate::thing::Thing",
1708            Some("crates/a/src/user.rs"), // workspace-RELATIVE, as the indexer passes it
1709            Some(root),
1710        );
1711        assert_eq!(result.as_deref(), Some("crates/a/src/thing.rs"));
1712    }
1713
1714    #[test]
1715    fn test_trailing_item_nested_module() {
1716        // crate::thing::inner::Deep  ->  crates/a/src/thing/inner.rs
1717        let tmp = make_workspace();
1718        let root = tmp.path().to_str().unwrap();
1719        let result = resolve_rust_use_to_path(
1720            "crate::thing::inner::Deep",
1721            Some("crates/a/src/user.rs"),
1722            Some(root),
1723        );
1724        assert_eq!(result.as_deref(), Some("crates/a/src/thing/inner.rs"));
1725    }
1726
1727    #[test]
1728    fn test_module_only_import_still_resolves() {
1729        // Regression guard: crate::thing (no trailing item) -> crates/a/src/thing.rs
1730        let tmp = make_workspace();
1731        let root = tmp.path().to_str().unwrap();
1732        let result =
1733            resolve_rust_use_to_path("crate::thing", Some("crates/a/src/user.rs"), Some(root));
1734        assert_eq!(result.as_deref(), Some("crates/a/src/thing.rs"));
1735    }
1736
1737    #[test]
1738    fn test_super_trailing_item() {
1739        // From crates/a/src/sub/mod.rs, super::thing::Thing -> crates/a/src/thing.rs
1740        let tmp = make_workspace();
1741        write_file(
1742            tmp.path(),
1743            "crates/a/src/sub/mod.rs",
1744            "use super::thing::Thing;\n",
1745        );
1746        let root = tmp.path().to_str().unwrap();
1747        let result = resolve_rust_use_to_path(
1748            "super::thing::Thing",
1749            Some("crates/a/src/sub/mod.rs"),
1750            Some(root),
1751        );
1752        assert_eq!(result.as_deref(), Some("crates/a/src/thing.rs"));
1753    }
1754
1755    #[test]
1756    fn test_resolution_is_cwd_independent() {
1757        // P2: with a relative current_file and an absolute project_root, resolution must
1758        // not depend on the process CWD. The test process CWD is the repo root, never the
1759        // temp dir, so a correct result here proves CWD-independence.
1760        let tmp = make_workspace();
1761        let root = tmp.path().to_str().unwrap();
1762        let result = resolve_rust_use_to_path(
1763            "crate::thing::Thing",
1764            Some("crates/a/src/user.rs"),
1765            Some(root),
1766        );
1767        assert_eq!(result.as_deref(), Some("crates/a/src/thing.rs"));
1768    }
1769}
1770
1771// ============================================================================
1772// Workspace Support
1773// ============================================================================
1774
1775/// A Rust crate discovered by scanning for Cargo.toml files.
1776#[derive(Debug, Clone)]
1777pub struct RustCrate {
1778    /// The name code imports it by (`-` in the package name becomes `_`).
1779    pub name: String,
1780    pub root_path: std::path::PathBuf,
1781}
1782
1783/// Find all Rust crates in the workspace by scanning for Cargo.toml files.
1784///
1785/// Only runs if a root Cargo.toml exists (to avoid wasted work on non-Rust projects).
1786/// Uses the `ignore` crate to respect .gitignore patterns.
1787pub fn parse_all_rust_crates(root: &std::path::Path) -> anyhow::Result<Vec<RustCrate>> {
1788    // Gate: only scan if this looks like a Rust project
1789    if !root.join("Cargo.toml").exists() {
1790        return Ok(Vec::new());
1791    }
1792
1793    let walker = ignore::WalkBuilder::new(root).git_ignore(true).build();
1794    let mut manifests = Vec::new();
1795    for entry in walker {
1796        let entry = entry?;
1797        if entry.file_name() == "Cargo.toml" {
1798            manifests.push(entry.path().to_path_buf());
1799        }
1800    }
1801    parse_rust_crates_from(&manifests)
1802}
1803
1804/// [`parse_all_rust_crates`] for `Cargo.toml` entries already found (in walk order).
1805/// The caller applies the root `Cargo.toml` gate.
1806pub fn parse_rust_crates_from(manifests: &[std::path::PathBuf]) -> anyhow::Result<Vec<RustCrate>> {
1807    let mut crates = Vec::new();
1808    for path in manifests {
1809        let content = std::fs::read_to_string(path)?;
1810        if let Some(name) = extract_crate_name(&content)
1811            && let Some(crate_root) = path.parent()
1812        {
1813            crates.push(RustCrate {
1814                // Code names a crate `b-core` as `b_core`
1815                name: name.replace('-', "_"),
1816                root_path: crate_root.to_path_buf(),
1817            });
1818        }
1819    }
1820    Ok(crates)
1821}
1822
1823/// Extract the package name from a Cargo.toml file using the `toml` crate.
1824fn extract_crate_name(content: &str) -> Option<String> {
1825    let table: toml::Table = content.parse().ok()?;
1826    table
1827        .get("package")?
1828        .get("name")?
1829        .as_str()
1830        .map(|s| s.to_string())
1831}
1832
1833/// Reclassify an import based on known workspace crates.
1834///
1835/// If the import path matches a workspace crate name (e.g., `my_crate` or
1836/// `my_crate::module`), reclassify it as Internal. Otherwise, fall back to
1837/// the default Rust import classification.
1838pub fn reclassify_rust_import(path: &str, crates: &[RustCrate]) -> crate::models::ImportType {
1839    for krate in crates {
1840        if path == krate.name || path.starts_with(&format!("{}::", krate.name)) {
1841            return crate::models::ImportType::Internal;
1842        }
1843    }
1844    classify_rust_import(path)
1845}
1846
1847/// Resolve a workspace crate import to a file path.
1848///
1849/// Handles imports like `my_crate::config` by finding the matching workspace
1850/// crate and resolving the module path within its `src/` directory.
1851pub fn resolve_rust_workspace_path(import_path: &str, crates: &[RustCrate]) -> Option<String> {
1852    for krate in crates {
1853        if import_path == krate.name || import_path.starts_with(&format!("{}::", krate.name)) {
1854            let relative_module = if import_path == krate.name {
1855                ""
1856            } else {
1857                import_path
1858                    .strip_prefix(&format!("{}::", krate.name))
1859                    .unwrap_or("")
1860            };
1861
1862            let src_root = krate.root_path.join("src");
1863            let parts: Vec<&str> = if relative_module.is_empty() {
1864                Vec::new()
1865            } else {
1866                relative_module.split("::").collect()
1867            };
1868
1869            // The longest module path that is a file (the rest names items in it),
1870            // else the crate root: `b::thing` is a function in b's lib.rs
1871            for n in (1..=parts.len()).rev() {
1872                if let Some(path) = resolve_rust_module_path(&src_root, &parts[..n])
1873                    && std::path::Path::new(&path).exists()
1874                {
1875                    return Some(path);
1876                }
1877            }
1878            for root_file in ["lib.rs", "main.rs"] {
1879                let path = src_root.join(root_file);
1880                if path.exists() {
1881                    return Some(path.to_string_lossy().to_string());
1882                }
1883            }
1884        }
1885    }
1886    None
1887}
1888
1889#[cfg(test)]
1890mod workspace_tests {
1891    use super::*;
1892    use std::fs;
1893    use tempfile::TempDir;
1894
1895    fn create_workspace(dir: &std::path::Path) {
1896        // Root Cargo.toml with workspace
1897        fs::write(
1898            dir.join("Cargo.toml"),
1899            r#"[workspace]
1900members = ["crate_a", "crate_b"]
1901"#,
1902        )
1903        .unwrap();
1904
1905        // crate_a
1906        let crate_a = dir.join("crate_a");
1907        fs::create_dir_all(crate_a.join("src")).unwrap();
1908        fs::write(
1909            crate_a.join("Cargo.toml"),
1910            r#"[package]
1911name = "crate_a"
1912version = "0.1.0"
1913"#,
1914        )
1915        .unwrap();
1916        fs::write(crate_a.join("src/lib.rs"), "pub mod config;").unwrap();
1917        fs::write(crate_a.join("src/config.rs"), "pub struct Config;").unwrap();
1918
1919        // crate_b with inline table syntax
1920        let crate_b = dir.join("crate_b");
1921        fs::create_dir_all(crate_b.join("src")).unwrap();
1922        fs::write(
1923            crate_b.join("Cargo.toml"),
1924            r#"[package]
1925name = "crate_b" # a comment
1926version = "0.1.0"
1927"#,
1928        )
1929        .unwrap();
1930        fs::write(crate_b.join("src/lib.rs"), "").unwrap();
1931    }
1932
1933    #[test]
1934    fn test_extract_crate_name_standard() {
1935        let toml = r#"[package]
1936name = "my_crate"
1937version = "0.1.0"
1938"#;
1939        assert_eq!(extract_crate_name(toml), Some("my_crate".to_string()));
1940    }
1941
1942    #[test]
1943    fn test_extract_crate_name_inline_table() {
1944        // The toml crate handles this correctly
1945        let toml = r#"[package]
1946name = "inline_crate"
1947version = "0.1.0"
1948edition = "2021"
1949"#;
1950        assert_eq!(extract_crate_name(toml), Some("inline_crate".to_string()));
1951    }
1952
1953    #[test]
1954    fn test_extract_crate_name_with_comment() {
1955        let toml = r#"[package]
1956name = "commented_crate" # my crate
1957version = "0.1.0"
1958"#;
1959        assert_eq!(
1960            extract_crate_name(toml),
1961            Some("commented_crate".to_string())
1962        );
1963    }
1964
1965    #[test]
1966    fn test_extract_crate_name_no_package() {
1967        let toml = r#"[workspace]
1968members = ["crate_a"]
1969"#;
1970        assert_eq!(extract_crate_name(toml), None);
1971    }
1972
1973    #[test]
1974    fn test_parse_all_rust_crates() {
1975        let dir = TempDir::new().unwrap();
1976        create_workspace(dir.path());
1977
1978        let crates = parse_all_rust_crates(dir.path()).unwrap();
1979        assert_eq!(crates.len(), 2);
1980
1981        let names: Vec<&str> = crates.iter().map(|c| c.name.as_str()).collect();
1982        assert!(names.contains(&"crate_a"));
1983        assert!(names.contains(&"crate_b"));
1984    }
1985
1986    #[test]
1987    fn test_parse_all_rust_crates_non_rust_project() {
1988        let dir = TempDir::new().unwrap();
1989        // No Cargo.toml -> should return empty
1990        let crates = parse_all_rust_crates(dir.path()).unwrap();
1991        assert!(crates.is_empty());
1992    }
1993
1994    #[test]
1995    fn test_reclassify_rust_import_workspace_crate() {
1996        let crates = vec![RustCrate {
1997            name: "crate_a".to_string(),
1998            root_path: std::path::PathBuf::from("/workspace/crate_a"),
1999        }];
2000
2001        assert!(matches!(
2002            reclassify_rust_import("crate_a", &crates),
2003            crate::models::ImportType::Internal
2004        ));
2005        assert!(matches!(
2006            reclassify_rust_import("crate_a::config", &crates),
2007            crate::models::ImportType::Internal
2008        ));
2009        // External crate should stay External
2010        assert!(matches!(
2011            reclassify_rust_import("serde::Serialize", &crates),
2012            crate::models::ImportType::External
2013        ));
2014    }
2015
2016    #[test]
2017    fn test_resolve_rust_workspace_path() {
2018        let dir = TempDir::new().unwrap();
2019        create_workspace(dir.path());
2020
2021        let crates = parse_all_rust_crates(dir.path()).unwrap();
2022
2023        // Bare crate import -> lib.rs
2024        let result = resolve_rust_workspace_path("crate_a", &crates);
2025        assert!(result.is_some());
2026        assert!(result.unwrap().ends_with("lib.rs"));
2027
2028        // Module import -> config.rs
2029        let result = resolve_rust_workspace_path("crate_a::config", &crates);
2030        assert!(result.is_some());
2031        assert!(result.unwrap().ends_with("config.rs"));
2032
2033        // Item import -> resolves to the module file
2034        let result = resolve_rust_workspace_path("crate_a::config::Config", &crates);
2035        assert!(result.is_some());
2036        assert!(result.unwrap().ends_with("config.rs"));
2037
2038        // Unknown crate -> None
2039        let result = resolve_rust_workspace_path("unknown_crate::foo", &crates);
2040        assert!(result.is_none());
2041    }
2042}