use crate::code::{fn_body, fn_names, is_called, markers, split_module};
use std::path::Path;
#[derive(Debug, PartialEq, Eq)]
pub struct Finding {
pub rule: &'static str,
pub detail: String,
}
pub const RULES: [&str; 8] = [
"unwired",
"negative-only",
"ignored-input",
"undocumented",
"duplication",
"positional-index",
"byte-scanner",
"status-unread",
];
#[must_use]
pub fn unwired(
crate_src: &str,
tests_src: &str,
new_fns: &[String],
) -> Vec<Finding> {
new_fns.iter().filter_map(|f| {
let called = is_called(crate_src, f);
let called_in_tests = tests_src.contains(&format!("{f}("));
(!called && called_in_tests).then(|| Finding {
rule: "unwired",
detail: format!("`{f}` is called only from tests -- landed but never wired in"),
})
}).collect()
}
#[must_use]
pub fn negative_only(
impl_src: &str,
tests_src: &str,
new_fns: &[String],
) -> Vec<Finding> {
new_fns
.iter()
.filter(|f| is_detector(impl_src, f))
.filter_map(|f| {
if !tests_src.contains(&format!("{f}(")) {
return None;
}
let positive = [
"!.is_empty()",
"is_empty(), false",
"assert!(!",
"len(), 1",
"len(), 2",
"len() > 0",
"> 0",
]
.iter()
.any(|p| tests_src.contains(p));
(!positive).then(|| Finding {
rule: "negative-only",
detail: format!(
"`{f}`'s test never asserts something IS found -- \
a function that always finds nothing would pass"
),
})
})
.collect()
}
fn is_detector(impl_src: &str, f: &str) -> bool {
impl_src.lines().any(|l| {
let s = l.trim();
s.starts_with("pub fn ")
&& s.contains(&format!("fn {f}("))
&& s.split("->").nth(1).is_some_and(|r| {
r.contains("Vec<")
|| r.contains("Option<")
|| r.contains("Map<")
})
})
}
#[must_use]
pub fn undocumented(impl_src: &str, new_fns: &[String]) -> Vec<Finding> {
new_fns
.iter()
.filter(|f| declared_without_doc(impl_src, f))
.map(|f| Finding {
rule: "undocumented",
detail: format!(
"`{f}` is a new `pub fn` with no doc comment -- \
`signatures` puts those lines in the next prompt"
),
})
.collect()
}
fn declared_without_doc(impl_src: &str, f: &str) -> bool {
let lines: Vec<&str> = impl_src.lines().collect();
let decl = format!("fn {f}(");
let Some(i) = lines.iter().position(|l| {
let s = l.trim();
s.starts_with("pub fn ") && s.contains(&decl)
}) else {
return false;
};
lines.get(..i).is_none_or(|before| {
!before
.iter()
.rev()
.find(|p| !p.trim().starts_with("#["))
.is_some_and(|p| p.trim().starts_with("///"))
})
}
#[must_use]
pub fn ignored_input(impl_src: &str, new_fns: &[String]) -> Vec<Finding> {
new_fns.iter().filter_map(|f| {
let sig = impl_src.lines()
.find(|l| l.contains(&format!("fn {f}(")) || l.contains(&format!("fn {f}<")))?;
let params = sig.split_once('(')?.1;
let ignored: Vec<&str> = params.split(',')
.filter_map(|p| p.trim().split(':').next())
.filter(|n| n.starts_with('_') && n.len() > 1)
.collect();
(!ignored.is_empty()).then(|| Finding {
rule: "ignored-input",
detail: format!("`{f}` ignores {} -- an `_` prefix silences the \
unused-parameter warning; a new fn that ignores an \
input is usually a stub", ignored.join(", ")),
})
}).collect()
}
pub fn node(path: &Path, added: &[String]) -> std::io::Result<Vec<Finding>> {
let src = std::fs::read_to_string(path)?;
let (_, tests_r) = split_module(&src);
let root = path
.parent()
.and_then(Path::parent)
.unwrap_or(Path::new("src"));
let crate_src: String = crate::fed::rust_files(root)
.iter()
.filter_map(|p| std::fs::read_to_string(p).ok())
.map(|s| split_module(&s).0.to_string())
.collect();
let (impl_r, _) = split_module(&src);
let mut out = unwired(&crate_src, tests_r, added);
out.extend(negative_only(impl_r, tests_r, added));
out.extend(ignored_input(impl_r, added));
out.extend(undocumented(impl_r, added));
out.extend(duplication(&crate_src, added));
out.extend(fix_shapes(&crate_src, added));
Ok(out)
}
pub type AddedFns = Vec<(std::path::PathBuf, Vec<String>)>;
fn diff_of(root: &Path, rev: &str) -> std::io::Result<String> {
let out = crate::git::at(root, &["show", "--unified=0", rev]).output()?;
if !out.status.success() {
return Err(std::io::Error::other(format!(
"cannot read revision `{rev}`: {}",
String::from_utf8_lossy(&out.stderr).trim()
)));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
fn added_pub_fn(line: &str) -> Option<&str> {
let rest = line.strip_prefix('+')?.trim().strip_prefix("pub fn ")?;
Some(rest.split(['(', '<']).next()?.trim())
}
#[must_use]
pub fn added_fns(diff: &str) -> AddedFns {
let mut per: std::collections::BTreeMap<std::path::PathBuf, Vec<String>> =
std::collections::BTreeMap::new();
let mut file = std::path::PathBuf::new();
for line in diff.lines() {
if let Some(p) = line.strip_prefix("+++ b/") {
file = std::path::PathBuf::from(p);
} else if file.file_name().is_some_and(|f| f == "mod.rs")
&& let Some(name) = added_pub_fn(line)
{
per.entry(file.clone()).or_default().push(name.to_string());
}
}
per.into_iter().collect()
}
pub fn added_in_commit(root: &Path, rev: &str) -> std::io::Result<AddedFns> {
Ok(added_fns(&diff_of(root, rev)?))
}
pub fn commit(
root: &Path,
rev: &str,
) -> std::io::Result<Vec<(std::path::PathBuf, Finding)>> {
let mut out = Vec::new();
for (file, added) in added_in_commit(root, rev)? {
for f in node(&root.join(&file), &added)? {
out.push((file.clone(), f));
}
}
Ok(out)
}
#[must_use]
pub fn duplication(crate_src: &str, new_fns: &[String]) -> Vec<Finding> {
let mut out = Vec::new();
for f in new_fns {
let Some(mine) = fn_body(crate_src, f).map(markers) else {
continue;
};
if mine.len() < 2 {
continue;
}
for other in fn_names(crate_src) {
if &other == f {
continue;
}
let shared = shared_markers(crate_src, &mine, &other);
if shared.len() < 2 || calls(crate_src, f, &other) {
continue;
}
out.push(Finding {
rule: "duplication",
detail: format!(
"`{f}` recognises {} that `{other}` already does -- \
two readings of one parse (`.:B13`)",
shared.join(", ")
),
});
}
}
out
}
fn shared_markers(src: &str, mine: &[String], other: &str) -> Vec<String> {
let Some(theirs) = fn_body(src, other).map(markers) else {
return Vec::new();
};
mine.iter()
.filter(|m| theirs.contains(m))
.map(|m| format!("`{m}`"))
.collect()
}
fn calls(src: &str, f: &str, other: &str) -> bool {
fn_body(src, f).is_some_and(|b| b.contains(&format!("{other}(")))
}
pub struct FixShape {
pub rule: &'static str,
pub shape: &'static str,
}
const SLICE_PATTERN: FixShape = FixShape {
rule: "positional-index",
shape: "let [a, b] = xs.as_slice() else { ... } -- the pattern carries \
the arity, so the length check and the indexes stop repeating \
each other",
};
const NAMED_BOUNDARY: FixShape = FixShape {
rule: "byte-scanner",
shape: "cut it into helpers that each take a slice and answer one \
question -- `get` and `saturating_*` become natural where `b[i]` \
was, and the indexing goes with the length",
};
const READ_THE_STATUS: FixShape = FixShape {
rule: "status-unread",
shape: "read `out.status.success()` before `out.stdout` -- `Ok` means \
the process RAN, not that it worked, and a failed run's empty \
output reads exactly like a clean one",
};
#[must_use]
pub fn fix_shapes(crate_src: &str, new_fns: &[String]) -> Vec<Finding> {
let mut out = Vec::new();
for f in new_fns {
let Some(body) = fn_body(crate_src, f) else {
continue;
};
if let Some(bind) = repeated_index(body) {
out.push(shape_finding(f, &SLICE_PATTERN, &format!("`{bind}`")));
}
if body.contains(".output()") && !body.contains("status") {
out.push(shape_finding(f, &READ_THE_STATUS, "a subprocess"));
}
let scans = body.matches("b[").count();
if body.lines().count() > 15 && scans >= 3 {
out.push(shape_finding(
f,
&NAMED_BOUNDARY,
&format!(
"{scans} byte indexes over {} lines",
body.lines().count()
),
));
}
}
out
}
fn shape_finding(f: &str, s: &FixShape, what: &str) -> Finding {
Finding {
rule: s.rule,
detail: format!("`{f}`: {what}. Try: {}", s.shape),
}
}
fn repeated_index(body: &str) -> Option<String> {
crate::code::literal_indexes(body)
.into_iter()
.find(|(n, c)| *c >= 2 && body.contains(&format!("{n}.len()")))
.map(|(n, _)| n)
}
#[cfg(test)]
#[path = "tests/review.rs"]
mod tests;
#[cfg(test)]
#[path = "tests/git.rs"]
mod git_tests;