use std::collections::HashMap;
use std::path::{Path, PathBuf};
use serde_json::json;
use crate::deep::{DeepContext, DeepError, FileId};
use crate::finding::{EvidenceClass, Finding, Location, OneBasedLine, Origin, Severity};
use crate::functions::walk_functions;
use crate::ingest::{SourceFile, Workspace};
use crate::reachability::{ReachabilityError, has_attr_ending_in};
use crate::rules::complexity::FunctionInfo;
use crate::rules::duplication::WorkspaceDuplication;
pub const DUPLICATIVE_REINVENTION_RULE: &str = "duplicative-reinvention";
pub const DUPLICATIVE_REINVENTION_RULE_REVISION: u32 = 1;
pub const CONNECTIVITY_DROP_RULE: &str = "connectivity-drop";
pub const CONNECTIVITY_DROP_RULE_REVISION: u32 = 1;
pub const MONOMORPHIZATION_LOAD_RULE: &str = "monomorphization-load";
pub const MONOMORPHIZATION_LOAD_RULE_REVISION: u32 = 1;
const MONOMORPHIZATION_LOAD_THRESHOLD: u32 = 20;
#[derive(Debug)]
pub enum SlopStructuralDeepError {
Deep(DeepError),
Io(PathBuf, std::io::Error),
Parse(PathBuf, syn::Error),
Reachability(ReachabilityError),
}
impl std::fmt::Display for SlopStructuralDeepError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Deep(err) => write!(f, "{err}"),
Self::Io(path, err) => write!(f, "{}: failed to read file: {err}", path.display()),
Self::Parse(path, err) => write!(f, "{}: failed to parse: {err}", path.display()),
Self::Reachability(err) => write!(f, "{err}"),
}
}
}
impl std::error::Error for SlopStructuralDeepError {}
#[derive(Debug, Default)]
pub struct DeepStructuralReport {
pub findings: Vec<Finding>,
pub errors: Vec<SlopStructuralDeepError>,
pub checked: usize,
}
struct FunctionFanIn {
qualified_name: String,
file: PathBuf,
line: usize,
cross_file_references: usize,
}
fn cross_file_reference_count(
analysis: &ra_ap_ide::Analysis,
file_id: FileId,
position: ra_ap_ide::FilePosition,
include_tests: bool,
) -> Result<usize, DeepError> {
let referencing = crate::deep::referencing_files(analysis, position, include_tests)?;
Ok(referencing
.iter()
.filter(|&&referencing_file| referencing_file != file_id)
.count())
}
fn is_reliably_checkable_for_fan_in(attrs: &[syn::Attribute], in_trait_impl: bool) -> bool {
!in_trait_impl && !has_attr_ending_in(attrs, "test") && !has_attr_ending_in(attrs, "bench")
}
fn collect_function_fan_in(
workspace: &Workspace,
ctx: &DeepContext,
analysis: &ra_ap_ide::Analysis,
include_tests: bool,
) -> (Vec<FunctionFanIn>, Vec<SlopStructuralDeepError>) {
let mut records = Vec::new();
let mut errors = Vec::new();
for krate in &workspace.crates {
for file in &krate.source_files {
if !file.kind.is_locally_reportable() {
continue;
}
collect_file_fan_in(
ctx,
analysis,
file,
include_tests,
&mut records,
&mut errors,
);
}
}
(records, errors)
}
fn collect_file_fan_in(
ctx: &DeepContext,
analysis: &ra_ap_ide::Analysis,
file: &SourceFile,
include_tests: bool,
records: &mut Vec<FunctionFanIn>,
errors: &mut Vec<SlopStructuralDeepError>,
) {
let file_id = match ctx.file_id(&file.path) {
Ok(Some(file_id)) => file_id,
Ok(None) => return,
Err(err) => {
errors.push(SlopStructuralDeepError::Deep(err));
return;
}
};
let ast = match crate::functions::read_and_parse_source(
&file.path,
|err| SlopStructuralDeepError::Io(file.path.clone(), err),
|err| SlopStructuralDeepError::Parse(file.path.clone(), err),
) {
Ok((_, ast)) => ast,
Err(err) => {
errors.push(err);
return;
}
};
walk_functions(&ast, |site| {
if !is_reliably_checkable_for_fan_in(site.attrs, site.in_trait_impl) {
return;
}
let offset = site.ident_span.byte_range().start as u32;
let position = ra_ap_ide::FilePosition {
file_id,
offset: offset.into(),
};
match cross_file_reference_count(analysis, file_id, position, include_tests) {
Ok(cross_file_references) => records.push(FunctionFanIn {
qualified_name: site.qualified_name,
file: file.path.clone(),
line: site.ident_span.start().line,
cross_file_references,
}),
Err(err) => errors.push(SlopStructuralDeepError::Deep(err)),
}
});
}
fn connectivity_drop_findings(records: &[FunctionFanIn]) -> Vec<Finding> {
records
.iter()
.filter(|record| record.cross_file_references == 0)
.map(|record| {
Finding::new(
format!(
"{CONNECTIVITY_DROP_RULE}:{}:{}",
record.file.display(),
record.qualified_name
),
CONNECTIVITY_DROP_RULE,
Severity::Info,
Location {
file: record.file.clone(),
line: OneBasedLine::new(record.line)
.expect("proc-macro2 span lines are 1-based"),
item_path: record.qualified_name.clone(),
},
EvidenceClass::Heuristic,
Origin::Code,
Some(json!({
"tier": "deep",
"cross_file_references": 0,
})),
)
})
.collect()
}
fn duplicative_reinvention_findings(
duplication: &WorkspaceDuplication,
records: &[FunctionFanIn],
) -> Vec<Finding> {
let fan_in: HashMap<(&Path, &str), usize> = records
.iter()
.map(|record| {
(
(record.file.as_path(), record.qualified_name.as_str()),
record.cross_file_references,
)
})
.collect();
let mut findings = Vec::new();
for family in &duplication.families {
let all_isolated = family.members.iter().all(|member| {
fan_in
.get(&(member.file.as_path(), member.qualified_name.as_str()))
.is_some_and(|&cross_file_references| cross_file_references == 0)
});
if !all_isolated {
continue;
}
let anchor = &family.members[0];
findings.push(Finding::new(
format!(
"{DUPLICATIVE_REINVENTION_RULE}:{}:{}",
anchor.file.display(),
anchor.qualified_name
),
DUPLICATIVE_REINVENTION_RULE,
Severity::Info,
Location {
file: anchor.file.clone(),
line: OneBasedLine::new(anchor.start_line)
.expect("proc-macro2 span lines are 1-based"),
item_path: anchor.qualified_name.clone(),
},
EvidenceClass::Heuristic,
Origin::Code,
Some(json!({
"tier": "deep",
"member_count": family.members.len(),
"files": family.members.iter()
.map(|member| member.file.display().to_string())
.collect::<Vec<_>>(),
})),
));
}
findings
}
fn monomorphization_load_findings(
production_records: &[FunctionFanIn],
complexity_functions: &[FunctionInfo],
) -> Vec<Finding> {
let generic_param_counts: HashMap<(&Path, &str), u32> = complexity_functions
.iter()
.map(|function| {
(
(function.file.as_path(), function.qualified_name.as_str()),
function.generic_param_count,
)
})
.collect();
production_records
.iter()
.filter_map(|record| {
let generic_param_count = *generic_param_counts
.get(&(record.file.as_path(), record.qualified_name.as_str()))?;
if generic_param_count == 0 {
return None;
}
let cross_file_call_sites = record.cross_file_references as u32;
let monomorphization_load_score = generic_param_count * cross_file_call_sites;
if monomorphization_load_score <= MONOMORPHIZATION_LOAD_THRESHOLD {
return None;
}
Some(Finding::new(
format!(
"{MONOMORPHIZATION_LOAD_RULE}:{}:{}",
record.file.display(),
record.qualified_name
),
MONOMORPHIZATION_LOAD_RULE,
Severity::Info,
Location {
file: record.file.clone(),
line: OneBasedLine::new(record.line)
.expect("proc-macro2 span lines are 1-based"),
item_path: record.qualified_name.clone(),
},
EvidenceClass::Heuristic,
Origin::Code,
Some(json!({
"tier": "deep",
"file": record.file.display().to_string(),
"function": record.qualified_name,
"line": record.line,
"generic_param_count": generic_param_count,
"cross_file_call_sites": cross_file_call_sites,
"monomorphization_load_score": monomorphization_load_score,
})),
))
})
.collect()
}
pub fn analyze_workspace(
workspace: &Workspace,
duplication: &WorkspaceDuplication,
include_tests: bool,
complexity_functions: &[FunctionInfo],
) -> Result<DeepStructuralReport, SlopStructuralDeepError> {
let ctx = DeepContext::load(&workspace.root).map_err(SlopStructuralDeepError::Deep)?;
let analysis = ctx.analysis();
let (records, mut errors) = collect_function_fan_in(workspace, &ctx, &analysis, include_tests);
let checked = records.len();
let mut findings = connectivity_drop_findings(&records);
findings.extend(duplicative_reinvention_findings(duplication, &records));
if include_tests {
let (production_records, production_errors) =
collect_function_fan_in(workspace, &ctx, &analysis, false);
errors.extend(production_errors);
findings.extend(monomorphization_load_findings(
&production_records,
complexity_functions,
));
} else {
findings.extend(monomorphization_load_findings(
&records,
complexity_functions,
));
}
Ok(DeepStructuralReport {
findings,
errors,
checked,
})
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
use crate::rules::duplication::{CloneFamily, CloneMember, DupeMode};
use crate::test_util::TempDir;
fn write_crate(dir: &TempDir, name: &str, deps: &[(&str, &str)], lib_source: &str) {
std::fs::create_dir_all(dir.join(name).join("src")).unwrap();
let mut manifest =
format!("[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n");
if !deps.is_empty() {
manifest.push_str("\n[dependencies]\n");
for (dep_name, rel_path) in deps {
manifest.push_str(&format!("{dep_name} = {{ path = \"{rel_path}\" }}\n"));
}
}
std::fs::write(dir.join(name).join("Cargo.toml"), manifest).unwrap();
std::fs::write(dir.join(name).join("src/lib.rs"), lib_source).unwrap();
}
fn write_workspace_manifest(dir: &TempDir, members: &[&str]) {
let members_toml = members
.iter()
.map(|m| format!("\"{m}\""))
.collect::<Vec<_>>()
.join(", ");
std::fs::write(
dir.join("Cargo.toml"),
format!("[workspace]\nmembers = [{members_toml}]\nresolver = \"2\"\n"),
)
.unwrap();
}
#[test]
fn connectivity_drop_flags_a_function_with_no_cross_file_callers() {
let dir = TempDir::new("connectivity-drop-isolated");
write_crate(
&dir,
"core",
&[],
r#"pub fn called_from_elsewhere() -> i32 {
1
}
fn isolated_helper() -> i32 {
2
}
"#,
);
write_crate(
&dir,
"consumer",
&[("core", "../core")],
r#"pub fn run() -> i32 {
core::called_from_elsewhere()
}
"#,
);
write_workspace_manifest(&dir, &["core", "consumer"]);
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let duplication = WorkspaceDuplication::default();
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
let names: HashSet<&str> = report
.findings
.iter()
.filter(|f| f.rule == CONNECTIVITY_DROP_RULE)
.map(|f| f.location.item_path.as_str())
.collect();
assert!(
!names.contains("called_from_elsewhere"),
"called from `consumer` — must not be flagged"
);
assert!(
names.contains("isolated_helper"),
"never referenced from another file — must be flagged"
);
}
#[test]
fn connectivity_drop_does_not_flag_a_test_function() {
let dir = TempDir::new("connectivity-drop-test-fn");
write_crate(
&dir,
"core",
&[],
r#"pub fn called_from_elsewhere() -> i32 {
1
}
#[test]
fn some_test() {
assert_eq!(1, 1);
}
"#,
);
write_crate(
&dir,
"consumer",
&[("core", "../core")],
r#"pub fn run() -> i32 {
core::called_from_elsewhere()
}
"#,
);
write_workspace_manifest(&dir, &["core", "consumer"]);
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let duplication = WorkspaceDuplication::default();
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
let names: HashSet<&str> = report
.findings
.iter()
.filter(|f| f.rule == CONNECTIVITY_DROP_RULE)
.map(|f| f.location.item_path.as_str())
.collect();
assert!(
!names.contains("some_test"),
"test functions are entry points by design — zero cross-file callers is expected, not a slop signal"
);
}
#[test]
fn connectivity_drop_does_not_flag_a_trait_impl_method() {
let dir = TempDir::new("connectivity-drop-trait-impl");
write_crate(
&dir,
"core",
&[],
r#"pub struct Foo;
impl std::fmt::Display for Foo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "foo")
}
}
"#,
);
std::fs::write(
dir.join("Cargo.toml"),
r#"[workspace]
members = ["core"]
resolver = "2"
"#,
)
.unwrap();
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let duplication = WorkspaceDuplication::default();
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
let names: HashSet<&str> = report
.findings
.iter()
.filter(|f| f.rule == CONNECTIVITY_DROP_RULE)
.map(|f| f.location.item_path.as_str())
.collect();
assert!(
!names.contains("Foo::fmt"),
"trait-impl methods are invoked via implicit dispatch (`{{}}` calls `Display::fmt`) \
a literal-reference search can't see — must not be flagged"
);
}
#[test]
fn connectivity_drop_finding_shape_matches_the_documented_contract() {
let dir = TempDir::new("connectivity-drop-shape");
write_crate(&dir, "core", &[], "fn isolated() -> i32 {\n 1\n}\n");
std::fs::write(
dir.join("Cargo.toml"),
r#"[workspace]
members = ["core"]
resolver = "2"
"#,
)
.unwrap();
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let duplication = WorkspaceDuplication::default();
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
let finding = report
.findings
.iter()
.find(|f| f.rule == CONNECTIVITY_DROP_RULE)
.expect("isolated() must be flagged");
assert_eq!(finding.severity, Severity::Info);
assert_eq!(finding.evidence_class, EvidenceClass::Heuristic);
assert_eq!(finding.origin, Origin::Code);
assert_eq!(
finding.evidence,
Some(json!({"tier": "deep", "cross_file_references": 0}))
);
}
#[test]
fn duplicative_reinvention_flags_a_family_with_no_fan_in_on_any_member() {
let dir = TempDir::new("duplicative-reinvention-isolated");
write_crate(
&dir,
"core",
&[],
"fn clone_one() -> i32 {\n 1\n}\n\nfn clone_two() -> i32 {\n 1\n}\n",
);
std::fs::write(
dir.join("Cargo.toml"),
r#"[workspace]
members = ["core"]
resolver = "2"
"#,
)
.unwrap();
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let core_lib = dir.join("core/src/lib.rs");
let member_a = CloneMember {
qualified_name: "clone_one".to_string(),
file: core_lib.clone(),
start_line: 1,
end_line: 1,
start_token: 0,
end_token: 0,
token_count: 1,
mode: DupeMode::Strict,
identifier_mapping: Vec::new(),
normalized_literal_kinds: Vec::new(),
};
let member_b = CloneMember {
qualified_name: "clone_two".to_string(),
file: core_lib.clone(),
start_line: 5,
end_line: 5,
start_token: 0,
end_token: 0,
token_count: 1,
mode: DupeMode::Strict,
identifier_mapping: Vec::new(),
normalized_literal_kinds: Vec::new(),
};
let duplication = WorkspaceDuplication {
families: vec![CloneFamily {
members: vec![member_a, member_b],
}],
errors: Vec::new(),
excluded_generated: 0,
};
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
let hit = report
.findings
.iter()
.find(|f| f.rule == DUPLICATIVE_REINVENTION_RULE)
.expect("a family whose members are never referenced in `records` must be flagged");
assert_eq!(hit.severity, Severity::Info);
assert_eq!(hit.evidence_class, EvidenceClass::Heuristic);
assert_eq!(hit.location.item_path, "clone_one");
assert_eq!(hit.evidence.as_ref().unwrap()["member_count"], 2);
}
#[test]
fn duplicative_reinvention_does_not_flag_a_family_with_a_referenced_member() {
let dir = TempDir::new("duplicative-reinvention-referenced");
write_crate(
&dir,
"core",
&[],
r#"pub fn clone_one() -> i32 {
1
}
fn clone_two() -> i32 {
1
}
"#,
);
write_crate(
&dir,
"consumer",
&[("core", "../core")],
r#"pub fn run() -> i32 {
core::clone_one()
}
"#,
);
write_workspace_manifest(&dir, &["core", "consumer"]);
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let core_lib = dir.join("core/src/lib.rs");
let member_a = CloneMember {
qualified_name: "clone_one".to_string(),
file: core_lib.clone(),
start_line: 1,
end_line: 1,
start_token: 0,
end_token: 0,
token_count: 1,
mode: DupeMode::Strict,
identifier_mapping: Vec::new(),
normalized_literal_kinds: Vec::new(),
};
let member_b = CloneMember {
qualified_name: "clone_two".to_string(),
file: core_lib.clone(),
start_line: 5,
end_line: 5,
start_token: 0,
end_token: 0,
token_count: 1,
mode: DupeMode::Strict,
identifier_mapping: Vec::new(),
normalized_literal_kinds: Vec::new(),
};
let duplication = WorkspaceDuplication {
families: vec![CloneFamily {
members: vec![member_a, member_b],
}],
errors: Vec::new(),
excluded_generated: 0,
};
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
assert!(
!report
.findings
.iter()
.any(|f| f.rule == DUPLICATIVE_REINVENTION_RULE),
"clone_one is referenced from `consumer` — the family must not be flagged"
);
}
#[test]
fn duplicative_reinvention_does_not_flag_a_family_of_test_functions() {
let dir = TempDir::new("duplicative-reinvention-test-family");
write_crate(
&dir,
"core",
&[],
r#"#[test]
fn clone_test_one() {
assert_eq!(1, 1);
}
#[test]
fn clone_test_two() {
assert_eq!(1, 1);
}
"#,
);
std::fs::write(
dir.join("Cargo.toml"),
r#"[workspace]
members = ["core"]
resolver = "2"
"#,
)
.unwrap();
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let core_lib = dir.join("core/src/lib.rs");
let member_a = CloneMember {
qualified_name: "clone_test_one".to_string(),
file: core_lib.clone(),
start_line: 1,
end_line: 1,
start_token: 0,
end_token: 0,
token_count: 1,
mode: DupeMode::Strict,
identifier_mapping: Vec::new(),
normalized_literal_kinds: Vec::new(),
};
let member_b = CloneMember {
qualified_name: "clone_test_two".to_string(),
file: core_lib.clone(),
start_line: 5,
end_line: 5,
start_token: 0,
end_token: 0,
token_count: 1,
mode: DupeMode::Strict,
identifier_mapping: Vec::new(),
normalized_literal_kinds: Vec::new(),
};
let duplication = WorkspaceDuplication {
families: vec![CloneFamily {
members: vec![member_a, member_b],
}],
errors: Vec::new(),
excluded_generated: 0,
};
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
assert!(
!report
.findings
.iter()
.any(|f| f.rule == DUPLICATIVE_REINVENTION_RULE),
"a family made entirely of #[test] functions must not be flagged — fan-in isn't a \
reliable signal for test functions"
);
}
#[test]
fn connectivity_drop_counts_a_test_only_cross_file_caller_when_include_tests_is_true() {
let dir = TempDir::new("connectivity-drop-test-only-caller-included");
write_crate(
&dir,
"core",
&[],
r#"pub fn used_only_in_test() -> i32 {
1
}
"#,
);
write_crate(
&dir,
"consumer",
&[("core", "../core")],
r#"#[test]
fn calls_it() {
assert_eq!(core::used_only_in_test(), 1);
}
"#,
);
write_workspace_manifest(&dir, &["core", "consumer"]);
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let duplication = WorkspaceDuplication::default();
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
let names: HashSet<&str> = report
.findings
.iter()
.filter(|f| f.rule == CONNECTIVITY_DROP_RULE)
.map(|f| f.location.item_path.as_str())
.collect();
assert!(
!names.contains("used_only_in_test"),
"called from a #[test] fn in another file — with include_tests: true this counts as \
a cross-file reference, the same as production usage, so it must not be flagged"
);
}
#[test]
fn connectivity_drop_does_not_count_a_test_only_cross_file_caller_when_include_tests_is_false()
{
let dir = TempDir::new("connectivity-drop-test-only-caller-excluded");
write_crate(
&dir,
"core",
&[],
r#"pub fn used_only_in_test() -> i32 {
1
}
"#,
);
write_crate(
&dir,
"consumer",
&[("core", "../core")],
r#"#[test]
fn calls_it() {
assert_eq!(core::used_only_in_test(), 1);
}
"#,
);
write_workspace_manifest(&dir, &["core", "consumer"]);
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let duplication = WorkspaceDuplication::default();
let report = analyze_workspace(&workspace, &duplication, false, &Vec::new()).unwrap();
let names: HashSet<&str> = report
.findings
.iter()
.filter(|f| f.rule == CONNECTIVITY_DROP_RULE)
.map(|f| f.location.item_path.as_str())
.collect();
assert!(
names.contains("used_only_in_test"),
"its only cross-file caller lives inside a #[test] fn — with include_tests: false \
that reference is filtered out same as any other test-only usage, so the function \
looks structurally unwired even though a real (test-only) caller exists"
);
}
#[test]
fn duplicative_reinvention_does_not_flag_a_family_with_a_generated_file_member() {
let dir = TempDir::new("duplicative-reinvention-generated-member");
std::fs::create_dir_all(dir.join("core/src")).unwrap();
std::fs::write(
dir.join("core/Cargo.toml"),
"[package]\nname = \"core\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
std::fs::write(
dir.join("core/src/lib.rs"),
"mod authored;\nmod generated;\n",
)
.unwrap();
std::fs::write(
dir.join("core/src/authored.rs"),
"fn clone_authored() -> i32 {\n 42\n}\n",
)
.unwrap();
std::fs::write(
dir.join("core/src/generated.rs"),
"// @generated by codegen. DO NOT EDIT.\nfn clone_generated() -> i32 {\n 42\n}\n",
)
.unwrap();
std::fs::write(
dir.join("Cargo.toml"),
"[workspace]\nmembers = [\"core\"]\nresolver = \"2\"\n",
)
.unwrap();
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let source_files = workspace
.crates
.iter()
.flat_map(|krate| krate.source_files.iter());
let duplication =
crate::rules::duplication::analyze_workspace(source_files, DupeMode::Strict, 1, true);
assert_eq!(
duplication.families.len(),
1,
"clone_authored and clone_generated must form one real clone family: {:?}",
duplication.families
);
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
assert!(
!report
.findings
.iter()
.any(|f| f.rule == DUPLICATIVE_REINVENTION_RULE),
"clone_generated's file is skipped by the fan-in scan (generated code, \
unconditionally excluded there), so it never enters `records` — the family must be \
treated as not-all-isolated rather than flagged on an incomplete signal"
);
}
#[test]
fn duplicative_reinvention_flags_a_family_whose_only_caller_is_invisible_proc_macro_generated_code()
{
let dir = TempDir::new("duplicative-reinvention-proc-macro-blind-spot");
std::fs::create_dir_all(dir.join("macros/src")).unwrap();
std::fs::write(
dir.join("macros/Cargo.toml"),
r#"[package]
name = "macros"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
"#,
)
.unwrap();
std::fs::write(
dir.join("macros/src/lib.rs"),
r#"use proc_macro::TokenStream;
/// Would-be expansion (never actually run — the Deep Tier loads with no
/// proc-macro server): a call to `clone_two()` the analysis never sees.
#[proc_macro_derive(CallsCloneTwo)]
pub fn calls_clone_two(_input: TokenStream) -> TokenStream {
"fn __generated_caller() { crate::clone_two(); }".parse().unwrap()
}
"#,
)
.unwrap();
std::fs::create_dir_all(dir.join("core/src")).unwrap();
std::fs::write(
dir.join("core/Cargo.toml"),
r#"[package]
name = "core"
version = "0.1.0"
edition = "2021"
[dependencies]
macros = { path = "../macros" }
"#,
)
.unwrap();
std::fs::write(dir.join("core/src/lib.rs"), "mod a;\nmod b;\nmod widget;\n").unwrap();
std::fs::write(
dir.join("core/src/a.rs"),
"pub fn clone_one() -> i32 {\n 7\n}\n",
)
.unwrap();
std::fs::write(
dir.join("core/src/b.rs"),
"pub fn clone_two() -> i32 {\n 7\n}\n",
)
.unwrap();
std::fs::write(
dir.join("core/src/widget.rs"),
"#[derive(macros::CallsCloneTwo)]\npub struct Widget;\n",
)
.unwrap();
write_workspace_manifest(&dir, &["macros", "core"]);
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let source_files = workspace
.crates
.iter()
.flat_map(|krate| krate.source_files.iter());
let duplication =
crate::rules::duplication::analyze_workspace(source_files, DupeMode::Strict, 1, false);
assert_eq!(
duplication.families.len(),
1,
"clone_one and clone_two must form one real clone family: {:?}",
duplication.families
);
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
assert!(
report
.findings
.iter()
.any(|f| f.rule == DUPLICATIVE_REINVENTION_RULE),
"documents today's actual (policy-violating) behavior: clone_two's only real caller \
is invisible generated code, so it looks just as isolated as the genuinely-unused \
clone_one and the family is flagged — see this test's doc comment"
);
}
#[cfg(feature = "deep")]
#[test]
fn connectivity_drop_registry_example_still_triggers_the_rule() {
let example = crate::rule_registry::lookup(CONNECTIVITY_DROP_RULE)
.expect("connectivity-drop has a registry entry")
.example
.expect("connectivity-drop has a curated example")
.before;
let dir = TempDir::new("connectivity-drop-registry-example");
write_crate(&dir, "core", &[], example);
write_workspace_manifest(&dir, &["core"]);
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let duplication = WorkspaceDuplication::default();
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == CONNECTIVITY_DROP_RULE)
.count(),
1,
"{:?}",
report.findings
);
}
#[cfg(feature = "deep")]
#[test]
fn duplicative_reinvention_registry_example_still_triggers_the_rule() {
let example = crate::rule_registry::lookup(DUPLICATIVE_REINVENTION_RULE)
.expect("duplicative-reinvention has a registry entry")
.example
.expect("duplicative-reinvention has a curated example")
.before;
let dir = TempDir::new("duplicative-reinvention-registry-example");
write_crate(&dir, "core", &[], example);
write_workspace_manifest(&dir, &["core"]);
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let core_lib = dir.join("core/src/lib.rs");
let member_a = CloneMember {
qualified_name: "calculate_discount_v1".to_string(),
file: core_lib.clone(),
start_line: 1,
end_line: 3,
start_token: 0,
end_token: 0,
token_count: 1,
mode: DupeMode::Strict,
identifier_mapping: Vec::new(),
normalized_literal_kinds: Vec::new(),
};
let member_b = CloneMember {
qualified_name: "calculate_discount_v2".to_string(),
file: core_lib.clone(),
start_line: 5,
end_line: 7,
start_token: 0,
end_token: 0,
token_count: 1,
mode: DupeMode::Strict,
identifier_mapping: Vec::new(),
normalized_literal_kinds: Vec::new(),
};
let duplication = WorkspaceDuplication {
families: vec![CloneFamily {
members: vec![member_a, member_b],
}],
errors: Vec::new(),
excluded_generated: 0,
};
let report = analyze_workspace(&workspace, &duplication, true, &Vec::new()).unwrap();
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == DUPLICATIVE_REINVENTION_RULE)
.count(),
1,
"{:?}",
report.findings
);
}
fn write_monomorphization_fixture(
dir: &TempDir,
generic_fn_source: &str,
caller_body: &str,
caller_count: usize,
) {
std::fs::create_dir_all(dir.join("core/src")).unwrap();
std::fs::write(
dir.join("core/Cargo.toml"),
"[package]\nname = \"core\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
let mut lib_source = String::from("mod generic;\n");
for i in 0..caller_count {
lib_source.push_str(&format!("mod caller_{i};\n"));
}
std::fs::write(dir.join("core/src/lib.rs"), lib_source).unwrap();
std::fs::write(dir.join("core/src/generic.rs"), generic_fn_source).unwrap();
for i in 0..caller_count {
std::fs::write(dir.join(format!("core/src/caller_{i}.rs")), caller_body).unwrap();
}
write_workspace_manifest(dir, &["core"]);
}
fn run_monomorphization_fixture(dir: &TempDir) -> DeepStructuralReport {
let workspace = crate::ingest::load(Some(&dir.join("Cargo.toml"))).unwrap();
let duplication = WorkspaceDuplication::default();
let source_files = workspace
.crates
.iter()
.flat_map(|krate| krate.source_files.iter());
let complexity = crate::rules::complexity::analyze_workspace(source_files, false);
analyze_workspace(&workspace, &duplication, true, &complexity.functions).unwrap()
}
#[test]
fn monomorphization_load_fires_for_a_generic_function_with_many_cross_file_callers() {
let dir = TempDir::new("monomorphization-load-fires");
write_monomorphization_fixture(
&dir,
"pub fn wrap_triple<T, U, E>(first: T, second: U, _tag: E) -> (T, U) {\n (first, second)\n}\n",
"pub fn run() -> (i32, i32) {\n crate::generic::wrap_triple(1, 2, \"tag\")\n}\n",
7,
);
let report = run_monomorphization_fixture(&dir);
let finding = report.findings.iter().find(|f| {
f.rule == MONOMORPHIZATION_LOAD_RULE && f.location.item_path == "wrap_triple"
});
assert!(finding.is_some(), "{:?}", report.findings);
let evidence = finding.unwrap().evidence.as_ref().unwrap();
assert_eq!(evidence["generic_param_count"], 3);
assert_eq!(evidence["cross_file_call_sites"], 7);
assert_eq!(evidence["monomorphization_load_score"], 21);
}
#[test]
fn monomorphization_load_does_not_fire_for_a_generic_function_with_few_callers() {
let dir = TempDir::new("monomorphization-load-few-callers");
write_monomorphization_fixture(
&dir,
"pub fn wrap_triple<T, U, E>(first: T, second: U, _tag: E) -> (T, U) {\n (first, second)\n}\n",
"pub fn run() -> (i32, i32) {\n crate::generic::wrap_triple(1, 2, \"tag\")\n}\n",
1,
);
let report = run_monomorphization_fixture(&dir);
assert!(
!report
.findings
.iter()
.any(|f| f.rule == MONOMORPHIZATION_LOAD_RULE),
"generic_param_count 3 * cross_file_call_sites 1 = 3, well under the threshold — \
must not fire: {:?}",
report.findings
);
}
#[test]
fn monomorphization_load_does_not_fire_for_a_non_generic_function_with_many_callers() {
let dir = TempDir::new("monomorphization-load-non-generic");
write_monomorphization_fixture(
&dir,
"pub fn wrap_triple(first: i32, second: i32, _tag: &str) -> (i32, i32) {\n (first, second)\n}\n",
"pub fn run() -> (i32, i32) {\n crate::generic::wrap_triple(1, 2, \"tag\")\n}\n",
7,
);
let report = run_monomorphization_fixture(&dir);
assert!(
!report
.findings
.iter()
.any(|f| f.rule == MONOMORPHIZATION_LOAD_RULE),
"zero generic params means zero monomorphization load regardless of fan-in — must \
not fire: {:?}",
report.findings
);
}
fn split_marked_files(source: &str) -> Vec<(&str, String)> {
let mut result: Vec<(&str, String)> = Vec::new();
for line in source.lines() {
if let Some(name) = line.strip_prefix("// file: ") {
result.push((name, String::new()));
} else if let Some(entry) = result.last_mut() {
entry.1.push_str(line);
entry.1.push('\n');
}
}
result
}
#[cfg(feature = "deep")]
#[test]
fn monomorphization_load_registry_example_still_triggers_the_rule() {
let example = crate::rule_registry::lookup(MONOMORPHIZATION_LOAD_RULE)
.expect("monomorphization-load has a registry entry")
.example
.expect("monomorphization-load has a curated example")
.before;
let files = split_marked_files(example);
assert_eq!(files.len(), 8, "expected 8 marked files: {files:?}");
let dir = TempDir::new("monomorphization-load-registry-example");
std::fs::create_dir_all(dir.join("core/src")).unwrap();
std::fs::write(
dir.join("core/Cargo.toml"),
"[package]\nname = \"core\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
let mod_declarations: String = files
.iter()
.map(|(name, _)| {
let mod_name = name.strip_suffix(".rs").expect("marked file ends in .rs");
format!("mod {mod_name};\n")
})
.collect();
std::fs::write(dir.join("core/src/lib.rs"), mod_declarations).unwrap();
for (name, source) in &files {
std::fs::write(dir.join("core/src").join(name), source).unwrap();
}
write_workspace_manifest(&dir, &["core"]);
let report = run_monomorphization_fixture(&dir);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == MONOMORPHIZATION_LOAD_RULE)
.count(),
1,
"{:?}",
report.findings
);
}
}