1use std::collections::{HashMap, HashSet};
7use std::fs;
8use std::path::{Path, PathBuf};
9
10use serde::{Deserialize, Serialize};
11use serde_json::{Value, json};
12
13macro_rules! static_regex {
16 ($pattern:expr_2021) => {{
17 static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
18 RE.get_or_init(|| regex::Regex::new($pattern).expect("valid static regex"))
19 }};
20}
21
22#[derive(Clone, Debug, Serialize, Deserialize)]
24pub struct OptimizeFinding {
25 pub line: usize,
26 pub category: String,
27 pub severity: String,
28 pub current: String,
29 pub recommended: String,
30 pub loc_impact: i32,
31}
32
33#[derive(Clone, Debug, Serialize, Deserialize)]
35pub struct OptimizeReport {
36 pub findings: Vec<OptimizeFinding>,
37 pub summary: OptimizeSummary,
38}
39
40#[derive(Clone, Debug, Serialize, Deserialize)]
42pub struct OptimizeSummary {
43 pub total_findings: usize,
44 pub estimated_loc_reduction: i32,
45 pub by_category: HashMap<String, usize>,
46}
47
48pub fn analyze_file(content: &str, path: &str, project_root: &Path) -> OptimizeReport {
50 let mut findings = Vec::new();
51 findings.extend(detect_single_impl_traits(content));
52 findings.extend(detect_single_product_factories(content));
53 findings.extend(detect_stdlib_alternatives(content));
54 findings.extend(detect_native_feature_replacements(content, project_root));
55 findings.extend(detect_yagni(content));
56 findings.extend(detect_oneline_candidates(content));
57 findings.extend(detect_reuse_candidates(content, path, project_root));
58
59 findings.sort_by(|left, right| {
60 finding_score(right)
61 .cmp(&finding_score(left))
62 .then_with(|| left.line.cmp(&right.line))
63 .then_with(|| left.category.cmp(&right.category))
64 });
65 findings.dedup_by(|left, right| {
66 left.line == right.line
67 && left.category == right.category
68 && left.current == right.current
69 && left.recommended == right.recommended
70 });
71
72 let mut by_category = HashMap::new();
73 for finding in &findings {
74 *by_category.entry(finding.category.clone()).or_insert(0) += 1;
75 }
76
77 OptimizeReport {
78 summary: OptimizeSummary {
79 total_findings: findings.len(),
80 estimated_loc_reduction: findings.iter().map(|finding| finding.loc_impact).sum(),
81 by_category,
82 },
83 findings,
84 }
85}
86
87pub fn detect_single_impl_traits(content: &str) -> Vec<OptimizeFinding> {
89 let trait_declarations =
90 static_regex!(r"(?m)^[ \t]*(?:pub(?:\([^)]*\))?\s+)?trait\s+([A-Za-z_][A-Za-z0-9_]*)\b");
91 let trait_implementations = static_regex!(
92 r"(?m)^[ \t]*impl(?:\s*<[^>\n]*>)?\s+([A-Za-z_][A-Za-z0-9_:]*)\s*(?:<[^>{}\n]*>)?\s+for\s+"
93 );
94
95 let implementations: HashMap<String, usize> = trait_implementations
96 .captures_iter(content)
97 .filter_map(|captures| {
98 captures
99 .get(1)
100 .map(|name| last_path_segment(name.as_str()).to_string())
101 })
102 .fold(HashMap::new(), |mut counts, trait_name| {
103 *counts.entry(trait_name).or_insert(0) += 1;
104 counts
105 });
106
107 trait_declarations
108 .captures_iter(content)
109 .filter_map(|captures| {
110 let trait_name = captures.get(1)?.as_str();
111 (implementations.get(trait_name) == Some(&1)).then(|| {
112 let start = captures.get(0).map_or(0, |m| m.start());
113 OptimizeFinding {
114 line: line_number_at(content, start),
115 category: "single-impl-trait".into(),
116 severity: "medium".into(),
117 current: format!("Trait `{trait_name}` has exactly one implementation."),
118 recommended: format!(
119 "Use its concrete type directly; restore `{trait_name}` when a second implementation is needed."
120 ),
121 loc_impact: 4,
122 }
123 })
124 })
125 .collect()
126}
127
128pub fn detect_stdlib_alternatives(content: &str) -> Vec<OptimizeFinding> {
130 let custom_map = static_regex!(
131 r"(?m)^[ \t]*(?:pub(?:\([^)]*\))?\s+)?struct\s+([A-Za-z_][A-Za-z0-9_]*(?:HashMap|Map|Dictionary|Lookup)[A-Za-z0-9_]*)\b"
132 );
133 let string_builder = static_regex!(r"\bString::new\s*\(\s*\)");
134 let push_str = static_regex!(r"\.[ \t]*push_str\s*\(");
135 let manual_sort =
136 static_regex!(r"(?m)^[ \t]*(?:for|while)\b[\s\S]{0,800}?(?:swap\s*\(|\.swap\s*\()");
137 let mut findings = Vec::new();
138
139 for captures in custom_map.captures_iter(content) {
140 let Some(name) = captures.get(1) else {
141 continue;
142 };
143 let Some(full_match) = captures.get(0) else {
144 continue;
145 };
146 push_unique(
147 &mut findings,
148 OptimizeFinding {
149 line: line_number_at(content, full_match.start()),
150 category: "stdlib-alternative".into(),
151 severity: "medium".into(),
152 current: format!("Custom collection `{}` resembles a map or lookup table.", name.as_str()),
153 recommended: "Prefer `std::collections::HashMap` unless this type enforces a domain invariant.".to_string(),
154 loc_impact: 8,
155 },
156 );
157 }
158
159 if string_builder.is_match(content) && push_str.find_iter(content).count() >= 2 {
160 let start = string_builder
161 .find(content)
162 .map_or(0, |matched| matched.start());
163 push_unique(
164 &mut findings,
165 OptimizeFinding {
166 line: line_number_at(content, start),
167 category: "stdlib-alternative".into(),
168 severity: "low".into(),
169 current: "A `String` is assembled with repeated `push_str` calls.".to_string(),
170 recommended: "Use `join`, `format!`, or an iterator collected into `String` when it makes the construction clearer.".to_string(),
171 loc_impact: 3,
172 },
173 );
174 }
175
176 if let Some(matched) = manual_sort.find(content) {
177 push_unique(
178 &mut findings,
179 OptimizeFinding {
180 line: line_number_at(content, matched.start()),
181 category: "stdlib-alternative".into(),
182 severity: "medium".into(),
183 current: "A loop performs a manual element swap while sorting.".to_string(),
184 recommended: "Use `slice::sort_by` or `slice::sort_unstable_by` instead of maintaining a sorting loop.".to_string(),
185 loc_impact: 6,
186 },
187 );
188 }
189
190 findings
191}
192
193pub fn detect_yagni(content: &str) -> Vec<OptimizeFinding> {
195 let empty_trait = static_regex!(
196 r"(?ms)^[ \t]*(?:pub(?:\([^)]*\))?\s+)?trait\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{\s*\}"
197 );
198 let private_abstraction =
199 static_regex!(r"(?m)^[ \t]*(?:struct|enum|trait)\s+([A-Za-z_][A-Za-z0-9_]*)\b");
200 let function_parameters = static_regex!(
201 r"(?ms)^[ \t]*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)[^\n{]*\(([^)]*)\)"
202 );
203 let mut findings = Vec::new();
204 let mut empty_trait_names = HashSet::new();
205
206 for captures in empty_trait.captures_iter(content) {
207 let (Some(name), Some(full_match)) = (captures.get(1), captures.get(0)) else {
208 continue;
209 };
210 empty_trait_names.insert(name.as_str().to_string());
211 push_unique(
212 &mut findings,
213 OptimizeFinding {
214 line: line_number_at(content, full_match.start()),
215 category: "yagni".into(),
216 severity: "low".into(),
217 current: format!(
218 "Marker trait `{}` has no behaviour or bounds.",
219 name.as_str()
220 ),
221 recommended: "Remove it until it expresses a real capability or constraint."
222 .to_string(),
223 loc_impact: 2,
224 },
225 );
226 }
227
228 for captures in private_abstraction.captures_iter(content) {
229 let (Some(name), Some(full_match)) = (captures.get(1), captures.get(0)) else {
230 continue;
231 };
232 if empty_trait_names.contains(name.as_str())
233 || count_identifier_occurrences(content, name.as_str()) > 1
234 {
235 continue;
236 }
237 push_unique(
238 &mut findings,
239 OptimizeFinding {
240 line: line_number_at(content, full_match.start()),
241 category: "yagni".into(),
242 severity: "low".into(),
243 current: format!(
244 "Private abstraction `{}` is never referenced after its declaration.",
245 name.as_str()
246 ),
247 recommended:
248 "Remove the unused abstraction, or add it only with its first concrete use."
249 .to_string(),
250 loc_impact: 2,
251 },
252 );
253 }
254
255 for captures in function_parameters.captures_iter(content) {
256 let (Some(name), Some(parameters), Some(full_match)) =
257 (captures.get(1), captures.get(2), captures.get(0))
258 else {
259 continue;
260 };
261 let parameter_count = parameters
262 .as_str()
263 .split(',')
264 .map(str::trim)
265 .filter(|parameter| !parameter.is_empty())
266 .count();
267 if parameter_count < 6 {
268 continue;
269 }
270 push_unique(
271 &mut findings,
272 OptimizeFinding {
273 line: line_number_at(content, full_match.start()),
274 category: "yagni".into(),
275 severity: "low".into(),
276 current: format!(
277 "Function `{}` accepts {parameter_count} parameters.",
278 name.as_str()
279 ),
280 recommended:
281 "Group parameters that change together into a focused options or domain type."
282 .to_string(),
283 loc_impact: 3,
284 },
285 );
286 }
287
288 findings
289}
290
291pub fn detect_oneline_candidates(content: &str) -> Vec<OptimizeFinding> {
293 let single_expression_function = static_regex!(
294 r"(?ms)^[ \t]*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)(?:<[^>{}]*>)?\s*\([^{};]*\)\s*(?:->\s*[^\n{]+)?\{\s*\n\s*([^{}\n]+?)\s*\n\s*\}"
295 );
296
297 single_expression_function
298 .captures_iter(content)
299 .filter_map(|captures| {
300 let (Some(name), Some(body), Some(full_match)) =
301 (captures.get(1), captures.get(2), captures.get(0))
302 else {
303 return None;
304 };
305 let expression = body.as_str().trim();
306 let is_expression = !expression.ends_with(';')
307 && !expression.starts_with("let ")
308 && !expression.starts_with("return ")
309 && !expression.starts_with("if ")
310 && !expression.starts_with("match ")
311 && !expression.starts_with("//");
312 is_expression.then(|| OptimizeFinding {
313 line: line_number_at(content, full_match.start()),
314 category: "oneline-candidate".into(),
315 severity: "low".into(),
316 current: format!(
317 "Function `{}` uses a multi-line single-expression body.",
318 name.as_str()
319 ),
320 recommended: format!(
321 "Collapse `{}` to a one-line expression body if that matches nearby style.",
322 name.as_str()
323 ),
324 loc_impact: 2,
325 })
326 })
327 .collect()
328}
329
330pub fn detect_reuse_candidates(
332 content: &str,
333 path: &str,
334 project_root: &Path,
335) -> Vec<OptimizeFinding> {
336 let current_windows = code_windows(content);
337 let mut findings = Vec::new();
338 let mut first_occurrence = HashMap::new();
339 let mut reported = HashSet::new();
340
341 for (line, window) in ¤t_windows {
342 if let Some(first_line) = first_occurrence.get(window) {
343 if *line >= *first_line + 3 && reported.insert(window.clone()) {
344 push_unique(
345 &mut findings,
346 OptimizeFinding {
347 line: *line,
348 category: "reuse-candidate".into(),
349 severity: "low".into(),
350 current: format!("Three-line sequence duplicates code beginning at line {first_line}."),
351 recommended: "Extract the shared sequence into a small helper with a domain-focused name.".to_string(),
352 loc_impact: 3,
353 },
354 );
355 }
356 } else {
357 first_occurrence.insert(window.clone(), *line);
358 }
359 }
360
361 if first_occurrence.is_empty() {
362 return findings;
363 }
364
365 let target_path = normalized_target_path(path, project_root);
366 for source_path in project_source_files(project_root, &target_path) {
367 let Ok(other_content) = fs::read_to_string(&source_path) else {
368 continue;
369 };
370 for (line, window) in code_windows(&other_content) {
371 let Some(current_line) = first_occurrence.get(&window) else {
372 continue;
373 };
374 if !reported.insert(window) {
375 continue;
376 }
377 let source_label = source_path
378 .strip_prefix(project_root)
379 .unwrap_or(&source_path)
380 .display();
381 push_unique(
382 &mut findings,
383 OptimizeFinding {
384 line: *current_line,
385 category: "reuse-candidate".into(),
386 severity: "low".into(),
387 current: format!(
388 "Three-line sequence is also present near line {line} in `{source_label}`."
389 ),
390 recommended: "Extract a shared helper only if both call sites have the same domain meaning.".to_string(),
391 loc_impact: 3,
392 },
393 );
394 }
395 }
396
397 findings
398}
399
400pub fn detect_single_product_factories(content: &str) -> Vec<OptimizeFinding> {
402 let factory = static_regex!(
403 r"(?m)^[ \t]*(?:pub(?:\([^)]*\))?\s+)?(?:struct|enum)\s+([A-Za-z_][A-Za-z0-9_]*(?:Factory|Builder|Creator))\b"
404 );
405 let return_type = static_regex!(
406 r"(?m)^[ \t]*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+[A-Za-z_][A-Za-z0-9_]*[^\n{]*->\s*([A-Za-z_][A-Za-z0-9_:]*)"
407 );
408
409 factory
410 .captures_iter(content)
411 .filter_map(|captures| {
412 let name = captures.get(1)?.as_str();
413 let declaration = captures.get(0)?;
414 let impl_start = content.find(&format!("impl {name}"))?;
415 let impl_end = content[impl_start + 1..]
416 .find("\nimpl ")
417 .map_or(content.len(), |offset| impl_start + 1 + offset);
418 let products: HashSet<_> = return_type
419 .captures_iter(&content[impl_start..impl_end])
420 .filter_map(|return_capture| return_capture.get(1))
421 .map(|product| product.as_str())
422 .filter(|product| !matches!(*product, "Self" | "Result" | "Option"))
423 .collect();
424
425 (products.len() == 1).then(|| {
426 let product = products.into_iter().next().unwrap_or_default();
427 OptimizeFinding {
428 line: line_number_at(content, declaration.start()),
429 category: "single-product-factory".to_string(),
430 severity: "low".to_string(),
431 current: format!("'{name}' only constructs '{product}'."),
432 recommended: format!(
433 "Construct '{product}' directly; retain '{name}' when it supports multiple products."
434 ),
435 loc_impact: 4,
436 }
437 })
438 })
439 .collect()
440}
441
442pub fn detect_native_feature_replacements(
443 content: &str,
444 project_root: &Path,
445) -> Vec<OptimizeFinding> {
446 let Ok(manifest) = fs::read_to_string(project_root.join("Cargo.toml")) else {
447 return Vec::new();
448 };
449 let replacements = [
450 (
451 "once_cell",
452 "once_cell::",
453 "std::sync::OnceLock or std::sync::LazyLock",
454 ),
455 ("lazy_static", "lazy_static!", "std::sync::LazyLock"),
456 ];
457
458 replacements
459 .iter()
460 .filter_map(|(dependency, usage, native)| {
461 let declared = manifest.lines().any(|line| {
462 let line = line.trim_start();
463 line.starts_with(dependency)
464 && matches!(
465 line.as_bytes().get(dependency.len()),
466 Some(b' ' | b'\t' | b'=')
467 )
468 });
469 let offset = content.find(usage)?;
470 declared.then(|| OptimizeFinding {
471 line: line_number_at(content, offset),
472 category: "native-feature-replacement".to_string(),
473 severity: "medium".to_string(),
474 current: format!("'{dependency}' is declared and '{usage}' is used in this file."),
475 recommended: format!(
476 "Use '{native}' when its standard-library behavior covers this use case."
477 ),
478 loc_impact: 1,
479 })
480 })
481 .collect()
482}
483
484fn finding_score(finding: &OptimizeFinding) -> i32 {
485 let severity = match finding.severity.as_str() {
486 "critical" => 400,
487 "high" => 300,
488 "medium" => 200,
489 _ => 100,
490 };
491 severity + finding.loc_impact.max(0)
492}
493
494pub fn format_report_text(report: &OptimizeReport, path: &str) -> String {
495 let mut out = format!(
496 "Solution Intelligence: {path}\n\n{} finding(s); estimated reduction: {} LOC\n",
497 report.summary.total_findings, report.summary.estimated_loc_reduction
498 );
499
500 if report.findings.is_empty() {
501 out.push_str("\nNo simplification opportunities detected.\n");
502 return out;
503 }
504
505 for finding in &report.findings {
506 out.push_str(&format!(
507 "\nLine {} [{}] {}\n Current: {}\n Recommended: {}\n Estimated impact: -{} LOC\n",
508 finding.line,
509 finding.severity,
510 finding.category,
511 finding.current,
512 finding.recommended,
513 finding.loc_impact
514 ));
515 }
516
517 let mut categories: Vec<_> = report.summary.by_category.iter().collect();
518 categories.sort_by(|left, right| left.0.cmp(right.0));
519 out.push_str("\nBy category:\n");
520 for (category, count) in categories {
521 out.push_str(&format!(" {category}: {count}\n"));
522 }
523 out
524}
525
526pub fn format_report_json(report: &OptimizeReport, path: &str) -> Value {
528 json!({
529 "path": path,
530 "findings": &report.findings,
531 "summary": &report.summary,
532 })
533}
534
535fn push_unique(findings: &mut Vec<OptimizeFinding>, candidate: OptimizeFinding) {
536 if !findings.iter().any(|finding| {
537 finding.line == candidate.line
538 && finding.category == candidate.category
539 && finding.current == candidate.current
540 }) {
541 findings.push(candidate);
542 }
543}
544
545fn line_number_at(content: &str, byte_offset: usize) -> usize {
546 content[..byte_offset]
547 .bytes()
548 .filter(|byte| *byte == b'\n')
549 .count()
550 + 1
551}
552
553fn last_path_segment(name: &str) -> &str {
554 name.rsplit("::").next().unwrap_or(name)
555}
556
557fn count_identifier_occurrences(content: &str, identifier: &str) -> usize {
558 let mut count = 0;
559 let mut offset = 0;
560 while let Some(found_at) = content[offset..].find(identifier) {
561 let start = offset + found_at;
562 let end = start + identifier.len();
563 let before_is_ident = content[..start]
564 .chars()
565 .next_back()
566 .is_some_and(is_identifier_character);
567 let after_is_ident = content[end..]
568 .chars()
569 .next()
570 .is_some_and(is_identifier_character);
571 if !before_is_ident && !after_is_ident {
572 count += 1;
573 }
574 offset = end;
575 }
576 count
577}
578
579fn is_identifier_character(character: char) -> bool {
580 character.is_ascii_alphanumeric() || character == '_'
581}
582
583fn code_windows(content: &str) -> Vec<(usize, String)> {
584 let comment_or_blank = static_regex!(r"^\s*(?://|#|/\*|\*|\*/|$)");
585 let whitespace = static_regex!(r"\s+");
586 let lines: Vec<_> = content
587 .lines()
588 .enumerate()
589 .filter(|(_, line)| !comment_or_blank.is_match(line))
590 .map(|(index, line)| {
591 (
592 index + 1,
593 whitespace.replace_all(line.trim(), " ").into_owned(),
594 )
595 })
596 .collect();
597
598 lines
599 .windows(3)
600 .filter_map(|window| {
601 let text = format!("{}\n{}\n{}", window[0].1, window[1].1, window[2].1);
602 if text.len() >= 30 {
603 Some((window[0].0, text))
604 } else {
605 None
606 }
607 })
608 .collect()
609}
610
611fn normalized_target_path(path: &str, project_root: &Path) -> PathBuf {
612 let path = Path::new(path);
613 if path.is_absolute() {
614 path.to_path_buf()
615 } else {
616 project_root.join(path)
617 }
618}
619
620fn project_source_files(project_root: &Path, target_path: &Path) -> Vec<PathBuf> {
621 const MAX_FILES: usize = 256;
622 const MAX_FILE_BYTES: u64 = 1_048_576;
623 let mut sources = Vec::new();
624 let mut directories = vec![project_root.to_path_buf()];
625
626 while let Some(directory) = directories.pop() {
627 let Ok(entries) = fs::read_dir(&directory) else {
628 continue;
629 };
630 for entry in entries.flatten() {
631 if sources.len() >= MAX_FILES {
632 return sources;
633 }
634 let path = entry.path();
635 let Ok(file_type) = entry.file_type() else {
636 continue;
637 };
638 if file_type.is_dir() {
639 if !should_skip_directory(&path) {
640 directories.push(path);
641 }
642 continue;
643 }
644 if !file_type.is_file() || path == target_path || !is_source_file(&path) {
645 continue;
646 }
647 if entry
648 .metadata()
649 .map_or(true, |metadata| metadata.len() > MAX_FILE_BYTES)
650 {
651 continue;
652 }
653 sources.push(path);
654 }
655 }
656 sources.sort();
657 sources
658}
659
660fn should_skip_directory(path: &Path) -> bool {
661 matches!(
662 path.file_name().and_then(|name| name.to_str()),
663 Some(".git" | "target" | "node_modules" | "vendor" | ".venv" | "dist" | "build")
664 )
665}
666
667fn is_source_file(path: &Path) -> bool {
668 matches!(
669 path.extension().and_then(|extension| extension.to_str()),
670 Some(
671 "rs" | "c"
672 | "cc"
673 | "cpp"
674 | "h"
675 | "hpp"
676 | "go"
677 | "java"
678 | "js"
679 | "jsx"
680 | "kt"
681 | "py"
682 | "rb"
683 | "swift"
684 | "ts"
685 | "tsx"
686 )
687 )
688}
689
690#[cfg(test)]
691mod tests {
692 use std::path::Path;
693
694 use super::{
695 analyze_file, detect_oneline_candidates, detect_single_impl_traits,
696 detect_stdlib_alternatives, detect_yagni, format_report_json, format_report_text,
697 };
698
699 #[test]
700 fn finds_trait_with_one_implementation() {
701 let content = "trait Store { fn get(&self); }\nstruct Memory;\nimpl Store for Memory { fn get(&self) {} }\n";
702 let findings = detect_single_impl_traits(content);
703
704 assert_eq!(findings.len(), 1);
705 assert_eq!(findings[0].category, "single-impl-trait");
706 assert_eq!(findings[0].line, 1);
707 }
708
709 #[test]
710 fn finds_standard_library_alternatives() {
711 let content = "struct UserMap { entries: Vec<(String, String)> }\n\nfn render() {\n let mut out = String::new();\n out.push_str(\"a\");\n out.push_str(\"b\");\n}\n";
712 let findings = detect_stdlib_alternatives(content);
713
714 assert!(
715 findings
716 .iter()
717 .any(|finding| finding.current.contains("UserMap"))
718 );
719 assert!(
720 findings
721 .iter()
722 .any(|finding| finding.current.contains("push_str"))
723 );
724 }
725
726 #[test]
727 fn finds_yagni_and_one_line_candidates() {
728 let content = "trait Marker {}\n\nfn options(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) {}\n\nfn answer() -> u8 {\n 42\n}\n";
729
730 assert_eq!(detect_yagni(content).len(), 2);
731 assert_eq!(detect_oneline_candidates(content).len(), 1);
732 }
733
734 #[test]
735 fn report_formats_text_and_json() {
736 let content = "trait Store { fn get(&self); }\nstruct Memory;\nimpl Store for Memory { fn get(&self) {} }\n";
737 let report = analyze_file(content, "src/store.rs", Path::new("."));
738
739 assert!(format_report_text(&report, "src/store.rs").contains("Solution Intelligence"));
740 let json = format_report_json(&report, "src/store.rs");
741 assert_eq!(json["path"], "src/store.rs");
742 assert_eq!(json["summary"]["total_findings"], 1);
743 }
744}