1use 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
79static 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
86pub 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 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 for symbol in &mut symbols {
120 symbol.path = path.to_string();
121 symbol.lang = Language::Rust;
122 }
123
124 Ok(symbols)
125}
126
127fn 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
135fn 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
143fn 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
151fn 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
159fn extract_impls(
161 source: &str,
162 table: &crate::parsers::MatchTable<'_>,
163) -> Result<Vec<SearchResult>> {
164 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 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(), 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
232fn 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
240fn 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
248fn 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
256fn 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
264fn 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
272fn 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
280fn extract_attributes(
284 source: &str,
285 table: &crate::parsers::MatchTable<'_>,
286) -> Result<Vec<SearchResult>> {
287 let mut symbols = Vec::new();
288
289 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 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 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
414fn 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 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 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(), Language::Rust,
455 kind.clone(),
456 Some(name),
457 span,
458 scope.clone(),
459 preview,
460 ));
461 }
462 }
463
464 Ok(symbols)
465}
466
467fn 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, start.column,
475 end.row + 1,
476 end.column,
477 )
478}
479
480fn extract_preview(source: &str, node: &tree_sitter::Node) -> String {
482 crate::parsers::preview::extract_preview_for_node(source, node)
484}
485
486pub 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 imports.extend(extract_use_declarations(source, &root_node)?);
508
509 imports.extend(extract_mod_items(source, &root_node)?);
511
512 imports.extend(extract_extern_crates(source, &root_node)?);
514
515 Ok(imports)
516 }
517}
518
519fn 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 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
560fn 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 let has_body = node.child_by_field_name("body").is_some();
603
604 if !has_body {
605 let line_number = node.start_position().row + 1;
607
608 imports.push(ImportInfo {
609 imported_path: name,
610 import_type: crate::models::ImportType::ModDecl,
612 line_number,
613 imported_symbols: None,
614 });
615 }
616 }
617 }
618
619 Ok(imports)
620}
621
622fn 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
678fn 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 ImportType::External
692 }
693}
694
695fn parse_rust_use_declaration(text: &str) -> Vec<(String, Option<Vec<String>>)> {
704 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 if text.contains('{') {
725 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 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 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 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 }
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 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 let variables: Vec<_> = symbols
918 .iter()
919 .filter(|s| matches!(s.kind, SymbolKind::Variable))
920 .collect();
921
922 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 }
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 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 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 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 let macros: Vec<_> = symbols
1017 .iter()
1018 .filter(|s| matches!(s.kind, SymbolKind::Macro))
1019 .collect();
1020
1021 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 let attributes: Vec<_> = symbols
1058 .iter()
1059 .filter(|s| matches!(s.kind, SymbolKind::Attribute))
1060 .collect();
1061
1062 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 assert!(
1076 !attributes
1077 .iter()
1078 .any(|a| a.symbol.as_deref() == Some("helper"))
1079 );
1080
1081 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 let attributes: Vec<_> = symbols
1115 .iter()
1116 .filter(|s| matches!(s.kind, SymbolKind::Attribute))
1117 .collect();
1118
1119 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 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 assert_eq!(deps.len(), 4);
1158
1159 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 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 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 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 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 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 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 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 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 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
1324fn 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 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 if current.ends_with("src")
1343 && let Some(parent) = current.parent()
1344 {
1345 return Some(parent.to_string_lossy().to_string());
1346 }
1347
1348 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
1357pub 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 if !import_path.starts_with("crate::")
1375 && !import_path.starts_with("super::")
1376 && !import_path.starts_with("self::")
1377 {
1378 if import_path.contains("::") {
1380 return None; }
1382 }
1384
1385 let current_file = current_file_path?;
1386
1387 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 let crate_root = find_crate_root(¤t_file)?;
1403 let crate_root_path = std::path::Path::new(&crate_root);
1404
1405 let resolved = if import_path.starts_with("crate::") {
1406 let module_path = import_path.strip_prefix("crate::").unwrap();
1408 let parts: Vec<&str> = module_path.split("::").collect();
1409
1410 let src_root = crate_root_path.join("src");
1412 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 let module_path = import_path.strip_prefix("super::").unwrap();
1420 let parts: Vec<&str> = module_path.split("::").collect();
1421
1422 let current_dir = if current_path.file_name().unwrap() == "mod.rs" {
1424 current_path.parent()?.parent()?
1426 } else {
1427 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 let module_path = import_path.strip_prefix("self::").unwrap();
1436 let parts: Vec<&str> = module_path.split("::").collect();
1437
1438 let current_dir = if current_path.file_name().unwrap() == "mod.rs" {
1440 current_path.parent()?
1442 } else {
1443 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 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 Some(module_file.to_string_lossy().to_string())
1464 }
1465 };
1466
1467 resolved.map(|path| relativize_to_project_root(&path, project_root))
1470}
1471
1472fn 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
1492fn 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
1512fn resolve_rust_module_path(base_dir: &std::path::Path, parts: &[&str]) -> Option<String> {
1518 if parts.is_empty() {
1519 return None;
1520 }
1521
1522 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 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 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 Some(file_path.to_string_lossy().to_string());
1542 }
1543 } else {
1544 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 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 assert!(path.contains("models.rs") || path.contains("models/mod.rs"));
1569 }
1570
1571 #[test]
1572 fn test_resolve_super_import() {
1573 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 assert!(path.contains("src") && path.contains("utils.rs"));
1584 }
1585
1586 #[test]
1587 fn test_resolve_self_import() {
1588 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 assert!(path.contains("models") && path.contains("helper.rs"));
1599 }
1600
1601 #[test]
1602 fn test_resolve_mod_declaration() {
1603 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 assert!(path.contains("parser.rs"));
1614 }
1615
1616 #[test]
1617 fn test_resolve_nested_crate_import() {
1618 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 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 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 assert!(result.is_none());
1645 }
1646
1647 #[test]
1648 fn test_stdlib_import_not_supported() {
1649 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 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 assert!(result.is_none());
1666 }
1667
1668 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 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 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"), 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 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 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 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 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#[derive(Debug, Clone)]
1777pub struct RustCrate {
1778 pub name: String,
1780 pub root_path: std::path::PathBuf,
1781}
1782
1783pub fn parse_all_rust_crates(root: &std::path::Path) -> anyhow::Result<Vec<RustCrate>> {
1788 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
1804pub 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 name: name.replace('-', "_"),
1816 root_path: crate_root.to_path_buf(),
1817 });
1818 }
1819 }
1820 Ok(crates)
1821}
1822
1823fn 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
1833pub 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
1847pub 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 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 fs::write(
1898 dir.join("Cargo.toml"),
1899 r#"[workspace]
1900members = ["crate_a", "crate_b"]
1901"#,
1902 )
1903 .unwrap();
1904
1905 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 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 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 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 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 let result = resolve_rust_workspace_path("crate_a", &crates);
2025 assert!(result.is_some());
2026 assert!(result.unwrap().ends_with("lib.rs"));
2027
2028 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 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 let result = resolve_rust_workspace_path("unknown_crate::foo", &crates);
2040 assert!(result.is_none());
2041 }
2042}