1use crate::models::{ImportType, Language, SearchResult, Span, SymbolKind};
16use crate::parsers::{DependencyExtractor, ImportInfo};
17use anyhow::{Context, Result};
18use streaming_iterator::StreamingIterator;
19use tree_sitter::{Parser, QueryCursor};
20
21const SYMQ_0: &str = r#"
22 (module
23 name: (constant) @name) @module
24 "#;
25const SYMQ_1: &str = r#"
26 (class
27 name: (constant) @name) @class
28 "#;
29const SYMQ_2: &str = r#"
30 (class
31 name: (constant) @class_name
32 (body_statement
33 (method
34 name: (_) @method_name))) @class
35
36 (module
37 name: (constant) @module_name
38 (body_statement
39 (method
40 name: (_) @method_name))) @module
41 "#;
42const SYMQ_3: &str = r#"
43 (singleton_method
44 object: (_) @class_name
45 name: (_) @method_name) @method
46 "#;
47const SYMQ_4: &str = r#"
48 (assignment
49 left: (constant) @name
50 right: (_)) @const
51 "#;
52const SYMQ_5: &str = r#"
53 (assignment
54 left: (identifier) @name) @assignment
55 "#;
56const SYMQ_6: &str = r#"
57 (instance_variable) @name
58 "#;
59const SYMQ_7: &str = r#"
60 (class_variable) @name
61 "#;
62const SYMQ_8: &str = r#"
63 (call
64 method: (identifier) @method_type
65 arguments: (argument_list
66 (simple_symbol) @name))
67
68 (#match? @method_type "^(attr_reader|attr_writer|attr_accessor)$")
69 "#;
70
71static SYMBOL_QUERIES: crate::parsers::LanguageQueries = crate::parsers::LanguageQueries::new(&[
74 SYMQ_0, SYMQ_1, SYMQ_2, SYMQ_3, SYMQ_4, SYMQ_5, SYMQ_6, SYMQ_7, SYMQ_8,
75]);
76
77pub fn parse(path: &str, source: &str) -> Result<Vec<SearchResult>> {
79 let mut parser = Parser::new();
80 let language = tree_sitter_ruby::LANGUAGE;
81
82 parser
83 .set_language(&language.into())
84 .context("Failed to set Ruby language")?;
85
86 let tree = parser
87 .parse(source, None)
88 .context("Failed to parse Ruby source")?;
89
90 let root_node = tree.root_node();
91 let table = SYMBOL_QUERIES.run(&language.into(), &root_node, source)?;
92
93 let mut symbols = Vec::new();
94
95 symbols.extend(extract_modules(source, &table)?);
97 symbols.extend(extract_classes(source, &table)?);
98 symbols.extend(extract_methods(source, &table)?);
99 symbols.extend(extract_singleton_methods(source, &table)?);
100 symbols.extend(extract_constants(source, &table)?);
101 symbols.extend(extract_instance_variables(source, &table)?);
102 symbols.extend(extract_class_variables(source, &table)?);
103 symbols.extend(extract_attr_accessors(source, &table)?);
104 symbols.extend(extract_local_variables(source, &table)?);
105
106 for symbol in &mut symbols {
108 symbol.path = path.to_string();
109 symbol.lang = Language::Ruby;
110 }
111
112 Ok(symbols)
113}
114
115fn extract_modules(
117 source: &str,
118 table: &crate::parsers::MatchTable<'_>,
119) -> Result<Vec<SearchResult>> {
120 extract_symbols(source, table, 0, SymbolKind::Module, None)
121}
122
123fn extract_classes(
125 source: &str,
126 table: &crate::parsers::MatchTable<'_>,
127) -> Result<Vec<SearchResult>> {
128 extract_symbols(source, table, 1, SymbolKind::Class, None)
129}
130
131fn extract_methods(
133 source: &str,
134 table: &crate::parsers::MatchTable<'_>,
135) -> Result<Vec<SearchResult>> {
136 let query = table.query();
137 let matches = table.sub(2);
138
139 let mut symbols = Vec::new();
140
141 for match_ in matches {
142 let mut scope_name = None;
143 let mut scope_type = None;
144 let mut method_name = None;
145 let mut method_node = None;
146
147 for capture in &match_.captures {
148 let capture_name: &str = query.capture_names()[capture.index as usize];
149 match capture_name {
150 "class_name" => {
151 scope_name = Some(
152 capture
153 .node
154 .utf8_text(source.as_bytes())
155 .unwrap_or("")
156 .to_string(),
157 );
158 scope_type = Some("class");
159 }
160 "module_name" => {
161 scope_name = Some(
162 capture
163 .node
164 .utf8_text(source.as_bytes())
165 .unwrap_or("")
166 .to_string(),
167 );
168 scope_type = Some("module");
169 }
170 "method_name" => {
171 method_name = Some(
172 capture
173 .node
174 .utf8_text(source.as_bytes())
175 .unwrap_or("")
176 .to_string(),
177 );
178 let mut current = capture.node;
180 while let Some(parent) = current.parent() {
181 if parent.kind() == "method" {
182 method_node = Some(parent);
183 break;
184 }
185 current = parent;
186 }
187 }
188 _ => {}
189 }
190 }
191
192 if let (Some(scope_name), Some(scope_type), Some(method_name), Some(node)) =
193 (scope_name, scope_type, method_name, method_node)
194 {
195 let scope = format!("{} {}", scope_type, scope_name);
196 let span = node_to_span(&node);
197 let preview = extract_preview(source, &node);
198
199 symbols.push(SearchResult::new(
200 String::new(),
201 Language::Ruby,
202 SymbolKind::Method,
203 Some(method_name),
204 span,
205 Some(scope),
206 preview,
207 ));
208 }
209 }
210
211 Ok(symbols)
212}
213
214fn extract_singleton_methods(
216 source: &str,
217 table: &crate::parsers::MatchTable<'_>,
218) -> Result<Vec<SearchResult>> {
219 let query = table.query();
220 let matches = table.sub(3);
221
222 let mut symbols = Vec::new();
223
224 for match_ in matches {
225 let mut class_name = None;
226 let mut method_name = None;
227 let mut method_node = None;
228
229 for capture in &match_.captures {
230 let capture_name: &str = query.capture_names()[capture.index as usize];
231 match capture_name {
232 "class_name" => {
233 class_name = Some(
234 capture
235 .node
236 .utf8_text(source.as_bytes())
237 .unwrap_or("")
238 .to_string(),
239 );
240 }
241 "method_name" => {
242 method_name = Some(
243 capture
244 .node
245 .utf8_text(source.as_bytes())
246 .unwrap_or("")
247 .to_string(),
248 );
249 }
250 "method" => {
251 method_node = Some(capture.node);
252 }
253 _ => {}
254 }
255 }
256
257 if let (Some(class_name), Some(method_name), Some(node)) =
258 (class_name, method_name, method_node)
259 {
260 let scope = format!("class {}", class_name);
261 let span = node_to_span(&node);
262 let preview = extract_preview(source, &node);
263
264 symbols.push(SearchResult::new(
265 String::new(),
266 Language::Ruby,
267 SymbolKind::Method,
268 Some(format!("{}.{}", class_name, method_name)),
269 span,
270 Some(scope),
271 preview,
272 ));
273 }
274 }
275
276 Ok(symbols)
277}
278
279fn extract_constants(
281 source: &str,
282 table: &crate::parsers::MatchTable<'_>,
283) -> Result<Vec<SearchResult>> {
284 extract_symbols(source, table, 4, SymbolKind::Constant, None)
285}
286
287fn extract_local_variables(
289 source: &str,
290 table: &crate::parsers::MatchTable<'_>,
291) -> Result<Vec<SearchResult>> {
292 let query = table.query();
293 let matches = table.sub(5);
294
295 let mut symbols = Vec::new();
296
297 for match_ in matches {
298 let mut name = None;
299 let mut assignment_node = None;
300
301 for capture in &match_.captures {
302 let capture_name: &str = query.capture_names()[capture.index as usize];
303 match capture_name {
304 "name" => {
305 name = Some(
306 capture
307 .node
308 .utf8_text(source.as_bytes())
309 .unwrap_or("")
310 .to_string(),
311 );
312 }
313 "assignment" => {
314 assignment_node = Some(capture.node);
315 }
316 _ => {}
317 }
318 }
319
320 if let (Some(name), Some(node)) = (name, assignment_node) {
321 let mut is_in_method = false;
323 let mut current = node;
324
325 while let Some(parent) = current.parent() {
326 if parent.kind() == "method" || parent.kind() == "singleton_method" {
327 is_in_method = true;
328 break;
329 }
330 if parent.kind() == "program"
332 || parent.kind() == "module"
333 || parent.kind() == "class"
334 {
335 break;
336 }
337 current = parent;
338 }
339
340 if is_in_method {
341 let span = node_to_span(&node);
342 let preview = extract_preview(source, &node);
343
344 symbols.push(SearchResult::new(
345 String::new(),
346 Language::Ruby,
347 SymbolKind::Variable,
348 Some(name),
349 span,
350 None,
351 preview,
352 ));
353 }
354 }
355 }
356
357 Ok(symbols)
358}
359
360fn extract_instance_variables(
362 source: &str,
363 table: &crate::parsers::MatchTable<'_>,
364) -> Result<Vec<SearchResult>> {
365 let matches = table.sub(6);
366
367 let mut symbols = Vec::new();
368 let mut seen = std::collections::HashSet::new();
369
370 for match_ in matches {
371 for capture in &match_.captures {
372 let name_text = capture.node.utf8_text(source.as_bytes()).unwrap_or("");
373
374 if !seen.contains(name_text) {
376 seen.insert(name_text.to_string());
377
378 let span = node_to_span(&capture.node);
379 let preview = extract_preview(source, &capture.node);
380
381 symbols.push(SearchResult::new(
382 String::new(),
383 Language::Ruby,
384 SymbolKind::Variable,
385 Some(name_text.to_string()),
386 span,
387 None,
388 preview,
389 ));
390 }
391 }
392 }
393
394 Ok(symbols)
395}
396
397fn extract_class_variables(
399 source: &str,
400 table: &crate::parsers::MatchTable<'_>,
401) -> Result<Vec<SearchResult>> {
402 let matches = table.sub(7);
403
404 let mut symbols = Vec::new();
405 let mut seen = std::collections::HashSet::new();
406
407 for match_ in matches {
408 for capture in &match_.captures {
409 let name_text = capture.node.utf8_text(source.as_bytes()).unwrap_or("");
410
411 if !seen.contains(name_text) {
413 seen.insert(name_text.to_string());
414
415 let span = node_to_span(&capture.node);
416 let preview = extract_preview(source, &capture.node);
417
418 symbols.push(SearchResult::new(
419 String::new(),
420 Language::Ruby,
421 SymbolKind::Variable,
422 Some(name_text.to_string()),
423 span,
424 None,
425 preview,
426 ));
427 }
428 }
429 }
430
431 Ok(symbols)
432}
433
434fn extract_attr_accessors(
436 source: &str,
437 table: &crate::parsers::MatchTable<'_>,
438) -> Result<Vec<SearchResult>> {
439 let query = table.query();
440 let matches = table.sub(8);
441
442 let mut symbols = Vec::new();
443
444 for match_ in matches {
445 let mut method_type = None;
446 let mut name = None;
447 let mut call_node = None;
448
449 for capture in &match_.captures {
450 let capture_name: &str = query.capture_names()[capture.index as usize];
451 match capture_name {
452 "method_type" => {
453 method_type = Some(
454 capture
455 .node
456 .utf8_text(source.as_bytes())
457 .unwrap_or("")
458 .to_string(),
459 );
460 }
461 "name" => {
462 let symbol_text = capture.node.utf8_text(source.as_bytes()).unwrap_or("");
463 name = Some(symbol_text.trim_start_matches(':').to_string());
465
466 let mut current = capture.node;
468 while let Some(parent) = current.parent() {
469 if parent.kind() == "call" {
470 call_node = Some(parent);
471 break;
472 }
473 current = parent;
474 }
475 }
476 _ => {}
477 }
478 }
479
480 if let (Some(_method_type), Some(name), Some(node)) = (method_type, name, call_node) {
481 let span = node_to_span(&node);
482 let preview = extract_preview(source, &node);
483
484 symbols.push(SearchResult::new(
485 String::new(),
486 Language::Ruby,
487 SymbolKind::Property,
488 Some(name),
489 span,
490 None,
491 preview,
492 ));
493 }
494 }
495
496 Ok(symbols)
497}
498
499fn extract_symbols(
501 source: &str,
502 table: &crate::parsers::MatchTable<'_>,
503 sub: usize,
504 kind: SymbolKind,
505 scope: Option<String>,
506) -> Result<Vec<SearchResult>> {
507 let query = table.query();
508 let matches = table.sub(sub);
509
510 let mut symbols = Vec::new();
511
512 for match_ in matches {
513 let mut name = None;
515 let mut full_node = None;
516
517 for capture in &match_.captures {
518 let capture_name: &str = query.capture_names()[capture.index as usize];
519 if capture_name == "name" {
520 name = Some(
521 capture
522 .node
523 .utf8_text(source.as_bytes())
524 .unwrap_or("")
525 .to_string(),
526 );
527 } else {
528 full_node = Some(capture.node);
530 }
531 }
532
533 if let (Some(name), Some(node)) = (name, full_node) {
534 let span = node_to_span(&node);
535 let preview = extract_preview(source, &node);
536
537 symbols.push(SearchResult::new(
538 String::new(),
539 Language::Ruby,
540 kind.clone(),
541 Some(name),
542 span,
543 scope.clone(),
544 preview,
545 ));
546 }
547 }
548
549 Ok(symbols)
550}
551
552fn node_to_span(node: &tree_sitter::Node) -> Span {
554 let start = node.start_position();
555 let end = node.end_position();
556
557 Span::new(
558 start.row + 1, start.column,
560 end.row + 1,
561 end.column,
562 )
563}
564
565fn extract_preview(source: &str, node: &tree_sitter::Node) -> String {
567 crate::parsers::preview::extract_preview_for_node(source, node)
569}
570
571pub struct RubyDependencyExtractor;
573
574impl DependencyExtractor for RubyDependencyExtractor {
575 fn extract_dependencies(source: &str) -> Result<Vec<ImportInfo>> {
576 let mut parser = Parser::new();
577 let language = tree_sitter_ruby::LANGUAGE;
578
579 parser
580 .set_language(&language.into())
581 .context("Failed to set Ruby language")?;
582
583 let tree = parser
584 .parse(source, None)
585 .context("Failed to parse Ruby source")?;
586
587 let root_node = tree.root_node();
588
589 let query_str = r#"
592 (call
593 method: (identifier) @method_name
594 arguments: (argument_list) @args) @call
595
596 (#match? @method_name "^(require|require_relative|load)$")
597 "#;
598
599 static QUERY_1: crate::parsers::CachedQuery = crate::parsers::CachedQuery::new();
600 let query = crate::parsers::cached_query(&QUERY_1, language, query_str)
601 .context("Failed to create Ruby require query")?;
602
603 let mut cursor = QueryCursor::new();
604 let mut matches = cursor.matches(query, root_node, source.as_bytes());
605
606 let mut imports = Vec::new();
607 let mut seen = std::collections::HashSet::new(); while let Some(match_) = matches.next() {
610 let mut method_name = None;
611 let mut args_node = None;
612
613 for capture in match_.captures {
614 let capture_name: &str = query.capture_names()[capture.index as usize];
615 match capture_name {
616 "method_name" => {
617 method_name = Some(
618 capture
619 .node
620 .utf8_text(source.as_bytes())
621 .unwrap_or("")
622 .to_string(),
623 );
624 }
625 "args" => {
626 args_node = Some(capture.node);
627 }
628 _ => {}
629 }
630 }
631
632 if let (Some(method), Some(args)) = (method_name, args_node) {
633 if !matches!(method.as_str(), "require" | "require_relative" | "load") {
636 continue;
637 }
638
639 let mut cursor = args.walk();
642 for child in args.children(&mut cursor) {
643 match child.kind() {
644 "string" => {
645 let mut is_interpolated = false;
647 let mut child_cursor = child.walk();
648 for grandchild in child.children(&mut child_cursor) {
649 if grandchild.kind() == "interpolation" {
650 is_interpolated = true;
651 break;
652 }
653 }
654 if is_interpolated {
655 continue; }
657
658 let mut content = None;
660 let mut child_cursor = child.walk();
661 for grandchild in child.children(&mut child_cursor) {
662 if grandchild.kind() == "string_content" {
663 content = Some(
664 grandchild
665 .utf8_text(source.as_bytes())
666 .unwrap_or("")
667 .to_string(),
668 );
669 break;
670 }
671 }
672
673 if let Some(path) = content {
674 if path.is_empty() {
676 continue;
677 }
678
679 let line_number = child.start_position().row + 1;
680 let key = (path.clone(), line_number);
681
682 if seen.contains(&key) {
684 continue;
685 }
686 seen.insert(key);
687
688 let path = if method == "require_relative"
690 && !path.starts_with("./")
691 && !path.starts_with("../")
692 && !path.starts_with('/')
693 {
694 format!("./{path}")
695 } else {
696 path
697 };
698 let import_type = classify_ruby_import(&path, &method);
699
700 imports.push(ImportInfo {
701 imported_path: path,
702 line_number,
703 import_type,
704 imported_symbols: None,
705 });
706 }
707 }
708 "simple_symbol" => {
709 let mut path =
710 child.utf8_text(source.as_bytes()).unwrap_or("").to_string();
711 if path.starts_with(':') {
713 path = path.trim_start_matches(':').to_string();
714 }
715
716 let line_number = child.start_position().row + 1;
717 let key = (path.clone(), line_number);
718
719 if seen.contains(&key) {
721 continue;
722 }
723 seen.insert(key);
724
725 let import_type = classify_ruby_import(&path, &method);
726
727 imports.push(ImportInfo {
728 imported_path: path,
729 line_number,
730 import_type,
731 imported_symbols: None,
732 });
733 }
734 _ => {}
737 }
738 }
739 }
740 }
741
742 Ok(imports)
743 }
744}
745
746#[derive(Debug, Clone)]
748pub struct RubyProject {
749 pub gem_name: String, pub project_root: String, pub abs_project_root: String, pub provides: Vec<String>,
756}
757
758impl RubyProject {
759 pub fn serves(&self, first: &str) -> bool {
762 gem_name_to_require_paths(&self.gem_name)
763 .iter()
764 .any(|variant| variant == first)
765 || self
766 .provides
767 .binary_search_by(|p| p.as_str().cmp(first))
768 .is_ok()
769 }
770}
771
772fn lib_provides(project_abs: &std::path::Path) -> Vec<String> {
774 let mut names: Vec<String> = std::fs::read_dir(project_abs.join("lib"))
775 .into_iter()
776 .flatten()
777 .flatten()
778 .filter_map(|e| {
779 let name = e.file_name().to_string_lossy().to_string();
780 if e.file_type().ok()?.is_dir() {
781 Some(name)
782 } else {
783 name.strip_suffix(".rb").map(str::to_string)
784 }
785 })
786 .collect();
787 names.sort();
788 names.dedup();
789 names
790}
791
792pub fn find_all_gemspec_files(root: &std::path::Path) -> Result<Vec<std::path::PathBuf>> {
794 let mut gemspec_files = Vec::new();
795
796 let walker = ignore::WalkBuilder::new(root)
797 .follow_links(false)
798 .git_ignore(true)
799 .build();
800
801 for entry in walker {
802 let entry = entry?;
803 let path = entry.path();
804 if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("gemspec") {
805 gemspec_files.push(path.to_path_buf());
806 }
807 }
808
809 Ok(gemspec_files)
810}
811
812pub fn parse_all_ruby_projects(root: &std::path::Path) -> Result<Vec<RubyProject>> {
814 let gemspec_files = find_all_gemspec_files(root)?;
815 parse_ruby_projects_from(root, &gemspec_files)
816}
817
818pub fn parse_ruby_projects_from(
820 root: &std::path::Path,
821 gemspec_files: &[std::path::PathBuf],
822) -> Result<Vec<RubyProject>> {
823 let mut projects = Vec::new();
824 let root_abs = root.canonicalize()?;
825
826 for gemspec_path in gemspec_files {
827 if let Some(project_dir) = gemspec_path.parent()
828 && let Some(gem_name) = parse_gemspec_name(gemspec_path)
829 {
830 let project_abs = project_dir.canonicalize()?;
831 let project_rel = project_abs
832 .strip_prefix(&root_abs)
833 .unwrap_or(project_dir)
834 .to_string_lossy()
835 .to_string();
836
837 projects.push(RubyProject {
838 gem_name: gem_name.clone(),
839 project_root: project_rel,
840 abs_project_root: project_abs.to_string_lossy().to_string(),
841 provides: lib_provides(&project_abs),
842 });
843 }
844 }
845
846 Ok(projects)
847}
848
849pub fn find_ruby_gem_names(root: &std::path::Path) -> Vec<String> {
852 parse_all_ruby_projects(root)
853 .unwrap_or_default()
854 .into_iter()
855 .map(|p| p.gem_name)
856 .collect()
857}
858
859fn parse_gemspec_name(gemspec_path: &std::path::Path) -> Option<String> {
861 let content = std::fs::read_to_string(gemspec_path).ok()?;
862
863 for line in content.lines() {
864 let trimmed = line.trim();
865
866 if (trimmed.starts_with("s.name") || trimmed.starts_with("spec.name"))
869 && trimmed.contains('=')
870 {
871 if let Some(equals_pos) = trimmed.find('=') {
873 let after_equals = &trimmed[equals_pos + 1..].trim();
874
875 for quote in ['"', '\''] {
877 if let Some(start) = after_equals.find(quote)
878 && let Some(end) = after_equals[start + 1..].find(quote)
879 {
880 let name = &after_equals[start + 1..start + 1 + end];
881 return Some(name.to_string());
882 }
883 }
884 }
885 }
886 }
887
888 None
889}
890
891fn gem_name_to_require_paths(gem_name: &str) -> Vec<String> {
894 let mut paths = Vec::new();
895
896 paths.push(gem_name.to_string());
898
899 if gem_name.contains('-') {
901 paths.push(gem_name.replace('-', "_"));
902 }
903
904 if gem_name.contains('_') {
906 paths.push(gem_name.replace('_', "-"));
907 }
908
909 paths
910}
911
912pub fn resolve_ruby_require_to_path(
915 require_path: &str,
916 projects: &[RubyProject],
917 current_file_path: Option<&str>,
918) -> Option<String> {
919 ruby_require_candidates(require_path, projects, current_file_path)
920 .into_iter()
921 .next()
922}
923
924pub fn ruby_require_candidates(
929 require_path: &str,
930 projects: &[RubyProject],
931 current_file_path: Option<&str>,
932) -> Vec<String> {
933 let with_rb = |p: String| {
934 if p.ends_with(".rb") {
935 p
936 } else {
937 format!("{p}.rb")
938 }
939 };
940 if require_path.starts_with("./") || require_path.starts_with("../") {
941 return current_file_path
943 .and_then(|f| {
944 crate::dependency_resolve::fold_path(
945 crate::dependency_resolve::parent_dir(f),
946 require_path,
947 )
948 })
949 .map(with_rb)
950 .into_iter()
951 .collect();
952 }
953
954 let first_component = require_path.split('/').next().unwrap_or(require_path);
956 let names_gem = |project: &RubyProject| project.serves(first_component);
957 let in_lib = |project: &RubyProject| {
958 crate::dependency_resolve::fold_path(
960 &project.project_root,
961 &with_rb(format!("lib/{}", require_path.replace("::", "/"))),
962 )
963 };
964 let mut out: Vec<String> = projects
965 .iter()
966 .filter(|p| names_gem(p))
967 .filter_map(in_lib)
968 .collect();
969 if out.is_empty() {
970 return out;
971 }
972 for project in projects.iter().filter(|p| !names_gem(p)) {
973 if let Some(path) = in_lib(project)
974 && !out.contains(&path)
975 {
976 out.push(path);
977 }
978 }
979 out
980}
981
982pub fn reclassify_ruby_import(import_path: &str, gem_names: &[String]) -> ImportType {
985 if import_path.starts_with("./") || import_path.starts_with("../") {
987 return ImportType::Internal;
988 }
989
990 let first_component = import_path.split('/').next().unwrap_or(import_path);
992
993 for gem_name in gem_names {
995 for variant in gem_name_to_require_paths(gem_name) {
996 if first_component == variant {
997 return ImportType::Internal;
998 }
999 }
1000 }
1001
1002 if is_ruby_stdlib(import_path) {
1004 return ImportType::Stdlib;
1005 }
1006
1007 ImportType::External
1009}
1010
1011fn is_ruby_stdlib(path: &str) -> bool {
1013 let stdlib_prefixes = [
1014 "json",
1015 "csv",
1016 "yaml",
1017 "uri",
1018 "net/",
1019 "open-uri",
1020 "openssl",
1021 "digest",
1022 "base64",
1023 "securerandom",
1024 "time",
1025 "date",
1026 "set",
1027 "fileutils",
1028 "pathname",
1029 "tempfile",
1030 "logger",
1031 "benchmark",
1032 "ostruct",
1033 "forwardable",
1034 "singleton",
1035 "observer",
1036 "delegate",
1037 "abbrev",
1038 "cgi",
1039 "erb",
1040 "optparse",
1041 "shellwords",
1042 "stringio",
1043 "strscan",
1044 "socket",
1045 "thread",
1046 "mutex_m",
1047 "monitor",
1048 "sync",
1049 "timeout",
1050 "weakref",
1051 "English",
1052 "fiddle",
1053 "rbconfig",
1054 ];
1055
1056 for prefix in &stdlib_prefixes {
1057 if path == *prefix || path.starts_with(&format!("{}/", prefix)) {
1058 return true;
1059 }
1060 }
1061
1062 false
1063}
1064
1065fn classify_ruby_import(path: &str, method: &str) -> ImportType {
1067 if method == "require_relative" {
1069 return ImportType::Internal;
1070 }
1071
1072 if is_ruby_stdlib(path) {
1074 return ImportType::Stdlib;
1075 }
1076
1077 if path.starts_with("./") || path.starts_with("../") {
1079 return ImportType::Internal;
1080 }
1081
1082 ImportType::External
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088 use super::*;
1089
1090 #[test]
1091 fn test_parse_class() {
1092 let source = r#"
1093class User
1094 attr_accessor :name, :email
1095end
1096 "#;
1097
1098 let symbols = parse("test.rb", source).unwrap();
1099
1100 let class_symbols: Vec<_> = symbols
1101 .iter()
1102 .filter(|s| matches!(s.kind, SymbolKind::Class))
1103 .collect();
1104
1105 assert_eq!(class_symbols.len(), 1);
1106 assert_eq!(class_symbols[0].symbol.as_deref(), Some("User"));
1107 }
1108
1109 #[test]
1110 fn test_parse_module() {
1111 let source = r#"
1112module Authentication
1113 def login
1114 # implementation
1115 end
1116end
1117 "#;
1118
1119 let symbols = parse("test.rb", source).unwrap();
1120
1121 let module_symbols: Vec<_> = symbols
1122 .iter()
1123 .filter(|s| matches!(s.kind, SymbolKind::Module))
1124 .collect();
1125
1126 assert_eq!(module_symbols.len(), 1);
1127 assert_eq!(module_symbols[0].symbol.as_deref(), Some("Authentication"));
1128 }
1129
1130 #[test]
1131 fn test_parse_methods() {
1132 let source = r#"
1133class Calculator
1134 def add(a, b)
1135 a + b
1136 end
1137
1138 def subtract(a, b)
1139 a - b
1140 end
1141end
1142 "#;
1143
1144 let symbols = parse("test.rb", source).unwrap();
1145
1146 let method_symbols: Vec<_> = symbols
1147 .iter()
1148 .filter(|s| matches!(s.kind, SymbolKind::Method))
1149 .collect();
1150
1151 assert_eq!(method_symbols.len(), 2);
1152 assert!(
1153 method_symbols
1154 .iter()
1155 .any(|s| s.symbol.as_deref() == Some("add"))
1156 );
1157 assert!(
1158 method_symbols
1159 .iter()
1160 .any(|s| s.symbol.as_deref() == Some("subtract"))
1161 );
1162
1163 for _method in method_symbols {
1165 }
1167 }
1168
1169 #[test]
1170 fn test_parse_singleton_method() {
1171 let source = r#"
1172class User
1173 def self.create(attributes)
1174 new(attributes).save
1175 end
1176end
1177 "#;
1178
1179 let symbols = parse("test.rb", source).unwrap();
1180
1181 let method_symbols: Vec<_> = symbols
1182 .iter()
1183 .filter(|s| matches!(s.kind, SymbolKind::Method))
1184 .collect();
1185
1186 assert!(!method_symbols.is_empty());
1187 assert!(
1188 method_symbols
1189 .iter()
1190 .any(|s| s.symbol.as_deref().unwrap_or("").contains("create"))
1191 );
1192 }
1193
1194 #[test]
1195 fn test_parse_constants() {
1196 let source = r#"
1197MAX_SIZE = 100
1198DEFAULT_TIMEOUT = 30
1199API_KEY = "secret123"
1200 "#;
1201
1202 let symbols = parse("test.rb", source).unwrap();
1203
1204 let const_symbols: Vec<_> = symbols
1205 .iter()
1206 .filter(|s| matches!(s.kind, SymbolKind::Constant))
1207 .collect();
1208
1209 assert_eq!(const_symbols.len(), 3);
1210 assert!(
1211 const_symbols
1212 .iter()
1213 .any(|s| s.symbol.as_deref() == Some("MAX_SIZE"))
1214 );
1215 assert!(
1216 const_symbols
1217 .iter()
1218 .any(|s| s.symbol.as_deref() == Some("DEFAULT_TIMEOUT"))
1219 );
1220 assert!(
1221 const_symbols
1222 .iter()
1223 .any(|s| s.symbol.as_deref() == Some("API_KEY"))
1224 );
1225 }
1226
1227 #[test]
1228 fn test_parse_nested_class() {
1229 let source = r#"
1230module MyApp
1231 class User
1232 def initialize(name)
1233 @name = name
1234 end
1235 end
1236end
1237 "#;
1238
1239 let symbols = parse("test.rb", source).unwrap();
1240
1241 let module_symbols: Vec<_> = symbols
1242 .iter()
1243 .filter(|s| matches!(s.kind, SymbolKind::Module))
1244 .collect();
1245
1246 let class_symbols: Vec<_> = symbols
1247 .iter()
1248 .filter(|s| matches!(s.kind, SymbolKind::Class))
1249 .collect();
1250
1251 assert_eq!(module_symbols.len(), 1);
1252 assert_eq!(class_symbols.len(), 1);
1253 assert_eq!(module_symbols[0].symbol.as_deref(), Some("MyApp"));
1254 assert_eq!(class_symbols[0].symbol.as_deref(), Some("User"));
1255 }
1256
1257 #[test]
1258 fn test_parse_rails_controller() {
1259 let source = r#"
1260class UsersController < ApplicationController
1261 before_action :authenticate_user!
1262
1263 def index
1264 @users = User.all
1265 end
1266
1267 def show
1268 @user = User.find(params[:id])
1269 end
1270
1271 def create
1272 @user = User.new(user_params)
1273 @user.save
1274 end
1275end
1276 "#;
1277
1278 let symbols = parse("test.rb", source).unwrap();
1279
1280 let class_symbols: Vec<_> = symbols
1281 .iter()
1282 .filter(|s| matches!(s.kind, SymbolKind::Class))
1283 .collect();
1284
1285 let method_symbols: Vec<_> = symbols
1286 .iter()
1287 .filter(|s| matches!(s.kind, SymbolKind::Method))
1288 .collect();
1289
1290 assert_eq!(class_symbols.len(), 1);
1291 assert_eq!(method_symbols.len(), 3);
1292 assert!(
1293 method_symbols
1294 .iter()
1295 .any(|s| s.symbol.as_deref() == Some("index"))
1296 );
1297 assert!(
1298 method_symbols
1299 .iter()
1300 .any(|s| s.symbol.as_deref() == Some("show"))
1301 );
1302 assert!(
1303 method_symbols
1304 .iter()
1305 .any(|s| s.symbol.as_deref() == Some("create"))
1306 );
1307 }
1308
1309 #[test]
1310 fn test_parse_mixed_symbols() {
1311 let source = r#"
1312MAX_RETRIES = 3
1313
1314module Authentication
1315 class Session
1316 def login(username, password)
1317 # implementation
1318 end
1319
1320 def self.destroy_all
1321 # implementation
1322 end
1323 end
1324end
1325 "#;
1326
1327 let symbols = parse("test.rb", source).unwrap();
1328
1329 assert!(symbols.len() >= 4);
1331
1332 let kinds: Vec<&SymbolKind> = symbols.iter().map(|s| &s.kind).collect();
1333 assert!(kinds.contains(&&SymbolKind::Constant));
1334 assert!(kinds.contains(&&SymbolKind::Module));
1335 assert!(kinds.contains(&&SymbolKind::Class));
1336 assert!(kinds.contains(&&SymbolKind::Method));
1337 }
1338
1339 #[test]
1340 fn test_local_variables_included() {
1341 let source = r#"
1342GLOBAL_CONSTANT = 100
1343
1344class Calculator
1345 def calculate(input)
1346 local_var = input * 2
1347 result = local_var + 10
1348 temp = result / 2
1349 temp
1350 end
1351
1352 def self.process(value)
1353 squared = value * value
1354 doubled = squared * 2
1355 doubled
1356 end
1357end
1358 "#;
1359
1360 let symbols = parse("test.rb", source).unwrap();
1361
1362 let variables: Vec<_> = symbols
1364 .iter()
1365 .filter(|s| matches!(s.kind, SymbolKind::Variable))
1366 .collect();
1367
1368 assert!(
1370 variables
1371 .iter()
1372 .any(|v| v.symbol.as_deref() == Some("local_var"))
1373 );
1374 assert!(
1375 variables
1376 .iter()
1377 .any(|v| v.symbol.as_deref() == Some("result"))
1378 );
1379 assert!(
1380 variables
1381 .iter()
1382 .any(|v| v.symbol.as_deref() == Some("temp"))
1383 );
1384 assert!(
1385 variables
1386 .iter()
1387 .any(|v| v.symbol.as_deref() == Some("squared"))
1388 );
1389 assert!(
1390 variables
1391 .iter()
1392 .any(|v| v.symbol.as_deref() == Some("doubled"))
1393 );
1394
1395 for _var in variables {
1397 }
1399
1400 let var_names: Vec<_> = symbols
1402 .iter()
1403 .filter(|s| matches!(s.kind, SymbolKind::Variable))
1404 .filter_map(|s| s.symbol.as_deref())
1405 .collect();
1406 assert!(!var_names.contains(&"GLOBAL_CONSTANT"));
1407 }
1408
1409 #[test]
1410 fn test_instance_and_class_variables() {
1411 let source = r#"
1412class Counter
1413 @@total_count = 0
1414
1415 def initialize(name)
1416 @name = name
1417 @count = 0
1418 @@total_count += 1
1419 end
1420
1421 def increment
1422 @count += 1
1423 end
1424
1425 def self.get_total
1426 @@total_count
1427 end
1428end
1429 "#;
1430
1431 let symbols = parse("test.rb", source).unwrap();
1432
1433 let variables: Vec<_> = symbols
1435 .iter()
1436 .filter(|s| matches!(s.kind, SymbolKind::Variable))
1437 .collect();
1438
1439 assert!(
1441 variables
1442 .iter()
1443 .any(|v| v.symbol.as_deref() == Some("@name"))
1444 );
1445 assert!(
1446 variables
1447 .iter()
1448 .any(|v| v.symbol.as_deref() == Some("@count"))
1449 );
1450
1451 assert!(
1453 variables
1454 .iter()
1455 .any(|v| v.symbol.as_deref() == Some("@@total_count"))
1456 );
1457 }
1458
1459 #[test]
1460 fn test_attr_accessors() {
1461 let source = r#"
1462class Person
1463 attr_reader :name, :age
1464 attr_writer :email
1465 attr_accessor :phone, :address
1466
1467 def initialize(name, age)
1468 @name = name
1469 @age = age
1470 end
1471end
1472 "#;
1473
1474 let symbols = parse("test.rb", source).unwrap();
1475
1476 let properties: Vec<_> = symbols
1478 .iter()
1479 .filter(|s| matches!(s.kind, SymbolKind::Property))
1480 .collect();
1481
1482 assert!(
1484 properties
1485 .iter()
1486 .any(|p| p.symbol.as_deref() == Some("name"))
1487 );
1488 assert!(
1489 properties
1490 .iter()
1491 .any(|p| p.symbol.as_deref() == Some("age"))
1492 );
1493 assert!(
1494 properties
1495 .iter()
1496 .any(|p| p.symbol.as_deref() == Some("email"))
1497 );
1498 assert!(
1499 properties
1500 .iter()
1501 .any(|p| p.symbol.as_deref() == Some("phone"))
1502 );
1503 assert!(
1504 properties
1505 .iter()
1506 .any(|p| p.symbol.as_deref() == Some("address"))
1507 );
1508
1509 assert_eq!(properties.len(), 5);
1510 }
1511
1512 #[test]
1513 fn test_extract_ruby_requires() {
1514 let source = r#"
1515 require 'json'
1516 require 'rails'
1517 require 'activerecord'
1518 require_relative '../models/user'
1519 require_relative './helpers/auth'
1520
1521 class UsersController
1522 def index
1523 # implementation
1524 end
1525 end
1526 "#;
1527
1528 let deps = RubyDependencyExtractor::extract_dependencies(source).unwrap();
1529
1530 assert_eq!(deps.len(), 5, "Should extract 5 require statements");
1531 assert!(deps.iter().any(|d| d.imported_path == "json"));
1532 assert!(deps.iter().any(|d| d.imported_path == "rails"));
1533 assert!(deps.iter().any(|d| d.imported_path == "activerecord"));
1534 assert!(deps.iter().any(|d| d.imported_path == "../models/user"));
1535 assert!(deps.iter().any(|d| d.imported_path == "./helpers/auth"));
1536
1537 let json_dep = deps.iter().find(|d| d.imported_path == "json").unwrap();
1539 assert!(
1540 matches!(json_dep.import_type, ImportType::Stdlib),
1541 "json should be classified as Stdlib"
1542 );
1543
1544 let rails_dep = deps.iter().find(|d| d.imported_path == "rails").unwrap();
1546 assert!(
1547 matches!(rails_dep.import_type, ImportType::External),
1548 "rails should be classified as External"
1549 );
1550
1551 let user_dep = deps
1553 .iter()
1554 .find(|d| d.imported_path == "../models/user")
1555 .unwrap();
1556 assert!(
1557 matches!(user_dep.import_type, ImportType::Internal),
1558 "require_relative should be classified as Internal"
1559 );
1560 }
1561
1562 #[test]
1563 fn test_dynamic_requires_filtered() {
1564 let source = r##"
1565 require 'json'
1566 require 'rails'
1567 require_relative '../models/user'
1568
1569 # Dynamic requires - should be filtered out
1570 require variable
1571 require CONSTANT
1572 require File.join('path', 'to', 'file')
1573 require_relative File.dirname(__FILE__) + '/dynamic'
1574 load "#{Rails.root}/lib/dynamic.rb"
1575 "##;
1576
1577 let deps = RubyDependencyExtractor::extract_dependencies(source).unwrap();
1578
1579 assert_eq!(deps.len(), 3, "Should extract 3 static requires only");
1582
1583 assert!(deps.iter().any(|d| d.imported_path == "json"));
1584 assert!(deps.iter().any(|d| d.imported_path == "rails"));
1585 assert!(deps.iter().any(|d| d.imported_path == "../models/user"));
1586
1587 assert!(!deps.iter().any(|d| d.imported_path.contains("variable")));
1589 assert!(!deps.iter().any(|d| d.imported_path.contains("CONSTANT")));
1590 assert!(!deps.iter().any(|d| d.imported_path.contains("File")));
1591 assert!(!deps.iter().any(|d| d.imported_path.contains("Rails")));
1592 }
1593}
1594
1595#[cfg(test)]
1596mod monorepo_tests {
1597 use super::*;
1598
1599 #[test]
1600 fn test_resolve_ruby_require_lib_structure() {
1601 let projects = vec![RubyProject {
1602 gem_name: "activerecord".to_string(),
1603 project_root: "gems/activerecord".to_string(),
1604 abs_project_root: "/path/to/gems/activerecord".to_string(),
1605 provides: vec![],
1606 }];
1607
1608 let result = resolve_ruby_require_to_path("activerecord/base", &projects, None);
1610
1611 assert_eq!(
1612 result,
1613 Some("gems/activerecord/lib/activerecord/base.rb".to_string())
1614 );
1615 }
1616
1617 #[test]
1618 fn test_resolve_ruby_require_root_structure() {
1619 let projects = vec![RubyProject {
1620 gem_name: "my-gem".to_string(),
1621 project_root: "gems/my-gem".to_string(),
1622 abs_project_root: "/path/to/gems/my-gem".to_string(),
1623 provides: vec![],
1624 }];
1625
1626 let result = resolve_ruby_require_to_path("my_gem/utils", &projects, None);
1629
1630 assert_eq!(result, Some("gems/my-gem/lib/my_gem/utils.rb".to_string()));
1632 }
1633
1634 #[test]
1635 fn test_resolve_ruby_require_no_match() {
1636 let projects = vec![RubyProject {
1637 gem_name: "activerecord".to_string(),
1638 project_root: "gems/activerecord".to_string(),
1639 abs_project_root: "/path/to/gems/activerecord".to_string(),
1640 provides: vec![],
1641 }];
1642
1643 let result = resolve_ruby_require_to_path("rails/application", &projects, None);
1645
1646 assert_eq!(result, None);
1647 }
1648
1649 #[test]
1650 fn test_resolve_ruby_require_hyphen_underscore_conversion() {
1651 let projects = vec![RubyProject {
1652 gem_name: "active-record".to_string(),
1653 project_root: "gems/active-record".to_string(),
1654 abs_project_root: "/path/to/gems/active-record".to_string(),
1655 provides: vec![],
1656 }];
1657
1658 let result = resolve_ruby_require_to_path("active_record/base", &projects, None);
1660
1661 assert_eq!(
1662 result,
1663 Some("gems/active-record/lib/active_record/base.rb".to_string())
1664 );
1665 }
1666
1667 #[test]
1668 fn test_resolve_ruby_require_monorepo() {
1669 let projects = vec![
1670 RubyProject {
1671 gem_name: "activerecord".to_string(),
1672 project_root: "gems/activerecord".to_string(),
1673 abs_project_root: "/path/to/gems/activerecord".to_string(),
1674 provides: vec![],
1675 },
1676 RubyProject {
1677 gem_name: "activesupport".to_string(),
1678 project_root: "gems/activesupport".to_string(),
1679 abs_project_root: "/path/to/gems/activesupport".to_string(),
1680 provides: vec![],
1681 },
1682 RubyProject {
1683 gem_name: "actionpack".to_string(),
1684 project_root: "gems/actionpack".to_string(),
1685 abs_project_root: "/path/to/gems/actionpack".to_string(),
1686 provides: vec![],
1687 },
1688 ];
1689
1690 let ar_result = resolve_ruby_require_to_path("activerecord/base", &projects, None);
1692 assert_eq!(
1693 ar_result,
1694 Some("gems/activerecord/lib/activerecord/base.rb".to_string())
1695 );
1696
1697 let as_result = resolve_ruby_require_to_path("activesupport/core_ext", &projects, None);
1698 assert_eq!(
1699 as_result,
1700 Some("gems/activesupport/lib/activesupport/core_ext.rb".to_string())
1701 );
1702
1703 let ap_result = resolve_ruby_require_to_path("actionpack/controller", &projects, None);
1704 assert_eq!(
1705 ap_result,
1706 Some("gems/actionpack/lib/actionpack/controller.rb".to_string())
1707 );
1708 }
1709}