use super::*; use crate::analysis::classify::{ CallTarget, call_text_may_call_free_function, free_helper_call_resolves, impl_self_type_name, inherent_owner_call_resolves, method_call_resolves_to_impl, module_stem, owner_dispatch_trait, owner_impl_identity_shadowed, requires_inherent_receiver_identity, test_calls_free_function, }; use crate::analysis::facts::{FunctionImplContext, ModulePathTarget}; use std::sync::Arc; pub(super) mod context; mod visibility; pub(crate) use context::CompactGripContext; pub(super) use context::{CompactTest, call_text_contains_named_call}; /// Walk `index.tests()` and return tests that plausibly relate to `seam`, /// each tagged with the single highest-priority `RelationReason` it /// satisfies. The two-step "match then rank" replaces the old binary /// `calls_owner || same_file_or_named` check from earlier campaigns. /// /// Detection per reason — strict ordering: the first reason that fires /// wins, so e.g. a test that both `calls owner` and `is in same file` /// carries `direct_owner_call`, never `same_test_file`. pub(super) fn find_related_tests_with_context<'context, 'index>( seam: &RepoSeam, context: &'context CompactGripContext<'index>, ) -> Vec<(&'context CompactTest<'index>, RelationReason)> { find_related_tests_in(seam, context, None) } /// True when `seam` relates to some test whose context position is in /// `pool`, by a reason `counts` accepts (#12940). Same rules as /// [`find_related_tests_with_context`]: other candidates are dropped after /// matching and before the per-test checks, and every later step only /// removes a test on its own facts and keeps its reason, so a pool test is /// related here, with that reason, exactly when it is related there. pub(super) fn relates_to_pool_test( seam: &RepoSeam, context: &CompactGripContext<'_>, pool: &BTreeSet, counts: fn(RelationReason) -> bool, ) -> bool { !find_related_tests_in(seam, context, Some((pool, counts))).is_empty() } type RelationPool<'p> = (&'p BTreeSet, fn(RelationReason) -> bool); fn find_related_tests_in<'context, 'index>( seam: &RepoSeam, context: &'context CompactGripContext<'index>, pool: Option>, ) -> Vec<(&'context CompactTest<'index>, RelationReason)> { let owner = OwnerContext::resolve(seam, context); let target_tokens = assertion_target_tokens(seam); let prefix = owner.prefix.as_deref(); let mut candidates: BTreeMap = BTreeMap::new(); match_direct_owner_call(&mut candidates, context, prefix, &owner); let inaccessible_direct: BTreeSet = context .owner_function(seam.file(), seam.display_line()) .map(|function| { candidates .keys() .copied() .filter(|test_index| { context.tests.get(*test_index).is_some_and(|indexed| { context.private_visibility.proven_inaccessible( context, function, indexed.test, ) }) }) .collect() }) .unwrap_or_default(); candidates.retain(|test_index, _| !inaccessible_direct.contains(test_index)); match_helper_owner_call(&mut candidates, context, prefix, &owner); match_target_affinity_owner_call( &mut candidates, seam, context, prefix, &owner, &target_tokens, ); match_assertion_target_affinity(&mut candidates, context, prefix, &target_tokens); match_same_test_file(&mut candidates, context, prefix, &owner); match_same_module(&mut candidates, context, prefix, &owner); match_owner_named_test(&mut candidates, context, prefix, &owner); match_import_path_affinity(&mut candidates, context, prefix, &owner); match_fixture_owner_affinity(&mut candidates, context, prefix, &owner); if let Some((pool, counts)) = pool { candidates.retain(|test_index, reason| pool.contains(test_index) && counts(*reason)); if candidates.is_empty() { return Vec::new(); } } // An inaccessible direct call cannot regain oracle credit through a // proximity or import fallback. An independently matched helper can // still reach a private owner from inside its own module. candidates.retain(|test_index, reason| { !inaccessible_direct.contains(test_index) || *reason == RelationReason::HelperOwnerCall }); // #6292: a test whose every call of the owner's name settles on a // same-named module-level rival relates through no signal of its own: // the same rule diff-mode related tests apply. if let Some(identity) = owner.identity.as_ref() { candidates.retain(|test_index, reason| { *reason == RelationReason::HelperOwnerCall || context.tests.get(*test_index).is_none_or(|indexed| { identity.resolve_test(indexed.test, context.index) != CallTarget::Other }) }); } else if owner.free_function && owner.same_name_count > 1 && let Some(owner_fn) = context.owner_function(seam.file(), seam.display_line()) { // #10855: no identity exists when the only rival sits in another // crate class (an integration test's own module). A test whose every // call goes through a module its own file declares and defines the // same-named function in names that local rival, not the owner. candidates.retain(|test_index, reason| { *reason == RelationReason::HelperOwnerCall || context.tests.get(*test_index).is_none_or(|indexed| { !crate::analysis::classify::test_calls_only_through_local_rival_module( context.index, owner_fn, indexed.test, ) }) }); } // Newly registered property facts carry assertion interpretation, not // authority to call any owner with the same spelling. Bind them before // every evidence stage, including value-insensitive direct-call credit. // A policy-modified fact must not become ordinary when its exact receipt // no longer matches; registration provenance and authority are distinct. // Ordinary relation rows retain their existing rules. let owner_fn = context.owner_function(seam.file(), seam.display_line()); candidates.retain(|test_index, _| { context.tests.get(*test_index).is_some_and(|indexed| { !context.index.is_registered_proptest(indexed.test) || (context.index.proptest_source(indexed.test).is_some() && owner_fn.is_some_and(|owner| { crate::analysis::classify::bound_free_owner_calls( context.index, owner, indexed.test, &indexed.test.body, context.pin_syntax(), ) })) }) }); dedupe_related_candidates(candidates, context) } /// Cached facts about a seam's owning function that every relationship /// strategy reads from. Resolved once per seam to avoid re-walking the /// index and re-deriving file stems / module paths per strategy. pub(super) struct OwnerContext<'index> { name: String, name_lower: String, file_stem: String, /// Set only when the owner file has no module stem (a crate root), so /// its inline tests still relate by exact path (#5395). crate_root_file: Option, module_path: Option, prefix: Option, fixture_names: Arc>, impl_type: Option, /// The owner is a module-level `fn` (parser-established), so a /// receiver or type-path call of its name reaches something else. free_function: bool, inherent_receiver: bool, inherent_owner: Option<&'index FunctionSummary>, /// The seam's owning function, for the shadowed-impl-identity refusal. function: Option<&'index FunctionSummary>, /// The owner's file, for the compilation-unit identity check (#14508 /// review). file: Option<&'index Path>, impl_trait: Option, same_name_count: usize, identity: Option>, } impl<'index> OwnerContext<'index> { fn resolve(seam: &RepoSeam, context: &CompactGripContext<'index>) -> Self { let owner_fn = context.owner_function(seam.file(), seam.display_line()); let name = owner_fn.map(|f| f.name.as_str()).unwrap_or("").to_string(); let name_lower = name.to_ascii_lowercase(); let owner_file = owner_fn.map(|f| f.file.as_path()); // Module identity, as in the finding-level relation (#5395): // `serialize/mod.rs` is `serialize`, and a crate root has none. let file_stem = owner_file.and_then(module_stem).unwrap_or_default(); let crate_root_file = if file_stem.is_empty() { owner_file.and_then(context::crate_root_file_key) } else { None }; let module_path = owner_file.and_then(|file| module_path_for_index(context.index, file)); let prefix = owner_fn.and_then(|f| package_prefix(&f.file)); let fixture_names = owner_file .map(|file| context.fixture_names_for_owner_file(file)) .unwrap_or_default(); let impl_type = owner_fn.and_then(|owner| impl_self_type_name(&owner.id.0)); let free_function = owner_fn.is_some_and(|owner| owner.impl_context == FunctionImplContext::Free); let inherent_receiver = owner_fn.is_some_and(requires_inherent_receiver_identity); let impl_trait = owner_fn.and_then(owner_dispatch_trait); let same_name_count = context.function_name_count(&name); // Shared per analysis run with the finding-level relation (#7716): // the same (owner, index) answer, so the per-test parses serve every // seam instead of dying with each construction. let identity = owner_fn.filter(|_| same_name_count > 1).and_then(|owner| { crate::analysis::classify::shared_owner_call_identity(context.index, owner) }); Self { name, name_lower, file_stem, crate_root_file, module_path, prefix, fixture_names, impl_type, free_function, inherent_receiver, inherent_owner: owner_fn.filter(|owner| requires_inherent_receiver_identity(owner)), function: owner_fn, file: owner_file, impl_trait, same_name_count, identity, } } } /// Tokens from `RequiredDiscriminator` and `ExpectedSink` that an /// `assertion_target_affinity` match must mention. Already filtered /// through `extract_identifier_tokens`, so stop-words and short tokens /// are excluded. pub(super) fn assertion_target_tokens(seam: &RepoSeam) -> BTreeSet { let discriminator_tokens = match seam.required_discriminator() { crate::analysis::seams::RequiredDiscriminator::MatchArmTaken { arm } => { match_arm_assertion_target_tokens(arm) } _ if seam.kind() == SeamKind::CallPresence => { call_presence_callee_target_tokens(required_discriminator_text(seam)) } _ => required_discriminator_tokens(seam), }; let sink_tokens = if seam.kind() == SeamKind::MatchArm { Vec::new() } else { extract_identifier_tokens(seam.expected_sink().as_str()) }; let filters_generic_call_tokens = seam.kind() == SeamKind::CallPresence; discriminator_tokens .into_iter() .chain(sink_tokens) .filter(|token| { !filters_generic_call_tokens || call_presence_assertion_affinity_token_is_specific_enough(token) }) .collect() } pub(super) fn match_arm_assertion_target_tokens(arm: &str) -> Vec { extract_identifier_tokens(arm) .into_iter() .filter(|token| match_arm_assertion_target_token_is_specific_enough(token)) .collect() } pub(super) fn match_arm_assertion_target_token_is_specific_enough(token: &str) -> bool { token.chars().next().is_some_and(|ch| ch.is_uppercase()) } pub(super) fn call_presence_callee_target_tokens(expression: &str) -> Vec { let mut tokens = extract_call_facts(expression, 0) .into_iter() .flat_map(|call| extract_identifier_tokens(&call.name)) .collect::>(); tokens.sort(); tokens.dedup(); tokens } pub(super) fn call_presence_assertion_affinity_token_is_specific_enough(token: &str) -> bool { if matches!( token, "arg" | "args" | "arm" | "class" | "clone" | "context" | "count" | "counts" | "data" | "dedup" | "description" | "entry" | "evidence" | "field" | "file" | "files" | "from" | "input" | "is_empty" | "iter" | "item" | "items" | "kind" | "line" | "lines" | "missing" | "model" | "name" | "owner" | "output" | "path" | "paths" | "probe" | "result" | "results" | "side_effect" | "sink" | "sort" | "summary" | "target" | "test" | "tests" | "text" | "u64" | "value" | "values" | "variant" | "byte" | "bytes" ) { return false; } true } pub(super) fn match_direct_owner_call( candidates: &mut BTreeMap, context: &CompactGripContext<'_>, prefix: Option<&str>, owner: &OwnerContext<'_>, ) { if owner.name.is_empty() { return; } if let Some(indices) = context.tests_by_call_name.get(&owner.name) { for test_index in indices { let Some(indexed) = context.tests.get(*test_index) else { continue; }; if owner.inherent_receiver { // Every inherent entry borrows the complete shared owner refusal, // independently of the legacy impl-name ambiguity shortcut. if !owner.inherent_owner.is_some_and(|function| { inherent_owner_call_resolves(indexed.test, function, context.index) }) { continue; } } else if owner.same_name_count > 1 && let Some(impl_type) = owner.impl_type.as_deref() && !method_call_resolves_to_impl( indexed.test, &owner.name, impl_type, owner.impl_trait.as_deref(), ) { continue; } // `ByteSize::kb(1)` or `size.kb()` never calls a free `kb` (#6713). if owner.free_function && !context .tests .get(*test_index) .is_some_and(|indexed| test_calls_free_function(indexed.test, &owner.name)) { continue; } // A call spelled like a direct-owner import alias of another // function binds to that import, not to a same-named local // function in a sibling module (#14508 review). if context.alias_spelling_binds_other_owner(indexed.test, &owner.name, &owner.name) { continue; } // #11382: a test whose own scope rebinds the owner's impl type or // trait calls the test-local item, not the production owner; the // finding-level relation refuses the same call. Refusal only removes // the direct-call credit, so this can only lower a relation. if owner.function.is_some_and(|function| { owner_impl_identity_shadowed(indexed.test, function, context.index) }) { continue; } insert_related_candidate( candidates, context, prefix, *test_index, RelationReason::DirectOwnerCall, ); } } // #14508: a test that imports the owner under an alias and calls the // alias reaches the owner directly. The import's module path must name // the owner's module: crate-relative for `crate::` imports, or the // package-qualified path for an integration test's external import. if owner.impl_type.is_none() && !owner.inherent_receiver && let Some(aliased) = context.tests_by_direct_owner_alias.get(&owner.name) { let owner_module = owner.module_path.as_deref().unwrap_or(""); let owner_is_crate_root = owner.crate_root_file.is_some(); for entry in aliased { let Some(indexed) = context.tests.get(entry.test_index) else { continue; }; let matches = direct_owner_alias_module_matches( &entry.module_path, entry.crate_relative, owner_module, owner_is_crate_root, owner.crate_root_file.as_deref(), indexed.test.file.as_path(), owner.file, owner.prefix.as_deref(), context.index, ); if !matches { continue; } // A local inline module of the alias's path shadows the import, so // the call binds to that module, not to the owner (#14508 review). if context.local_module_shadows_alias(indexed, &entry.module_path, &owner.name) { continue; } // A local function of the alias's name shadows the import, so the // call binds to it, not to the owner (#14508 review). if context.local_function_shadows_call(indexed, &entry.alias, entry.module_depth) { continue; } // A `let`/closure/parameter binding of the alias at the call line // binds the call to that local value, not to the owner. if context.alias_binding_shadows_call(indexed, &entry.alias, entry.call_line) { continue; } if owner.function.is_some_and(|function| { owner_impl_identity_shadowed(indexed.test, function, context.index) }) { continue; } insert_related_candidate( candidates, context, prefix, entry.test_index, RelationReason::DirectOwnerCall, ); } } } #[allow( clippy::too_many_arguments, reason = "the alias spelling, the owner's module identity and the test crate unit are separate inputs; a struct would only rename them" )] fn direct_owner_alias_module_matches( alias_module: &str, alias_crate_relative: bool, owner_module: &str, owner_is_crate_root: bool, owner_crate_root: Option<&str>, test_file: &Path, owner_file: Option<&Path>, owner_prefix: Option<&str>, index: &RustIndex, ) -> bool { // `src/pricing/mod.rs` names `pricing`, but `module_path_for_index` keeps // the file stem (`pricing/mod`); fold the leaf so the owner matches its // `crate::pricing` import (#14508 review). let owner_module = owner_module.strip_suffix("/mod").unwrap_or(owner_module); if alias_crate_relative { // `crate::` resolves against the crate that compiles the test file, so // compilation-unit identity must hold before the equality check. if rust_index::is_test_file(test_file) { return false; } let owner_package = owner_prefix.unwrap_or(""); let Some(test_package) = package_scope(test_file) else { return false; }; if test_package != owner_package { return false; } // A package can hold both a library and a binary, and `crate::` in the // binary names the binary's own modules. if !crate_relative_alias_shares_compilation_unit( test_file, alias_module, owner_file, owner_is_crate_root, owner_crate_root, index, ) { return false; } if alias_module.is_empty() { return owner_is_crate_root; } // The chain above already compared files; the index's binary-target // module path (`bin/pricing`) is not the crate-relative spelling. return true; } // An external import names a package first: `subject::pricing`. Only the // identifiers the test's crate uses for the owner's own library count; a // sibling package's name must not credit this owner (#14508 review). let owner_root = match owner_crate_root { Some(root) => root.to_string(), None => match owner_prefix { Some(prefix) => format!("{prefix}src/lib.rs"), None => "src/lib.rs".to_string(), }, }; let import_names = index .member_crates .import_names(test_file, Path::new(&owner_root)); let (package, rest) = match alias_module.split_once('/') { Some((package, rest)) => (package, Some(rest)), None => (alias_module, None), }; if !import_names.iter().any(|name| name == package) { return false; } match rest { None => owner_is_crate_root, Some(rest) => { rest.strip_suffix("/mod").unwrap_or(rest) == owner_module && owner_file.is_some_and(|owner_file| { resolve_module_chain(index, Path::new(&owner_root), rest) .is_some_and(|resolved| { normalize_path(&resolved) == normalize_path(owner_file) }) }) } } } /// Whether a `crate::`-relative alias in `test_file` can name `owner_file` /// (#14508 review). `crate::` resolves against the crate that compiles the /// test file, so package identity alone is not enough: a binary target is a /// separate compilation unit from the library beside it. /// /// Two shapes are definite negatives: the test file is an established binary /// target root, so `crate::` names that binary and never another crate root; /// or it belongs to a `src/bin/` target, whose module tree is confined /// to its own directory, so `crate::` never names a library module. /// /// A binary root that reaches a *different* file for the same module name /// through `#[path]` stays unresolved here; the inline-module shadow guard /// covers the inline spelling. fn crate_relative_alias_shares_compilation_unit( test_file: &Path, alias_module: &str, owner_file: Option<&Path>, owner_is_crate_root: bool, owner_crate_root: Option<&str>, index: &RustIndex, ) -> bool { if index.member_crates.is_binary_target_root(test_file) { let test_root = context::crate_root_file_key(test_file); if owner_is_crate_root && owner_crate_root != test_root.as_deref() { return false; } } if alias_module.is_empty() { // `crate::owner` names the crate root of the compilation unit that // compiles the test, so an empty alias module credits only when that // root is the owner's crate root (#14508 review). let Some(owner_root) = owner_crate_root else { return false; }; let Some(test_root) = crate_root_file_for_test(index, test_file) else { return false; }; return normalize_path(&test_root) == normalize_path(Path::new(owner_root)); } let Some(owner_file) = owner_file else { return false; }; let Some(root_file) = crate_root_file_for_test(index, test_file) else { return false; }; resolve_module_chain(index, &root_file, alias_module) .is_some_and(|resolved| normalize_path(&resolved) == normalize_path(owner_file)) } /// The crate root file that compiles `test_file` (#14508 review). A binary /// target root is the file itself; a module inside a `src/bin/` target /// resolves from that target's `main.rs` or flat `.rs`; a library or /// binary module under `src/` resolves from `src/lib.rs` or `src/main.rs`. fn crate_root_file_for_test(index: &RustIndex, test_file: &Path) -> Option { if index.member_crates.is_binary_target_root(test_file) { return Some(test_file.to_path_buf()); } if let Some(bin_dir) = binary_target_module_dir(test_file) { let normalized = normalize_path(test_file); if normalized == format!("{bin_dir}.rs") || normalized == format!("{bin_dir}/main.rs") { return Some(test_file.to_path_buf()); } let main = PathBuf::from(format!("{bin_dir}/main.rs")); if index_has_file(index, &main) { return Some(main); } let flat = PathBuf::from(format!("{bin_dir}.rs")); if index_has_file(index, &flat) { return Some(flat); } return None; } let prefix = package_prefix(test_file).unwrap_or_default(); let lib = PathBuf::from(format!("{prefix}src/lib.rs")); let main = PathBuf::from(format!("{prefix}src/main.rs")); let (lib_exists, main_exists) = (index_has_file(index, &lib), index_has_file(index, &main)); if lib_exists != main_exists { return Some(if lib_exists { lib } else { main }); } if !lib_exists { return None; } // A package can hold a library and a default binary, and a `src/` module // belongs to whichever root declares it; preferring `src/lib.rs` would // credit the library for a binary-only child module (#14508 review). let normalized = normalize_path(test_file); if normalized == normalize_path(&lib) { return Some(lib); } if normalized == normalize_path(&main) { return Some(main); } let module_path = module_path_for_index(index, test_file)?; let module_path = module_path.strip_suffix("/mod").unwrap_or(&module_path); let declares = |root: &Path| { resolve_module_chain(index, root, module_path) .is_some_and(|resolved| normalize_path(&resolved) == normalized) }; match (declares(&lib), declares(&main)) { (true, false) => Some(lib), (false, true) => Some(main), _ => None, } } /// Resolve a slash-separated `crate::` chain from `root_file` the way rustc /// does, following each declaration's `#[path]` target. A missing declaration /// or a non-literal `#[path]` fails closed (#14508 review). fn resolve_module_chain(index: &RustIndex, root_file: &Path, module_path: &str) -> Option { let mut current = root_file.to_path_buf(); for segment in module_path.split('/') { let facts = index.files().get(¤t)?; let mut matching = facts .module_declarations .iter() .filter(|declaration| declaration.name == segment); let declaration = matching.next()?; // Two `#[cfg]`-gated declarations of one module with different // `#[path]` targets compile different files per configuration; no // static single target exists, so fail closed (#14508 review). if matching.any(|other| other.path_target != declaration.path_target) { return None; } let dir = current.parent()?; current = match &declaration.path_target { ModulePathTarget::Default => { // `pricing.rs` declaring `mod x;` resolves under `pricing/`; // only the compilation-unit root keeps the declaring directory. let root_like = current == root_file || current.ends_with("mod.rs") || index.member_crates.is_binary_target_root(¤t); let base = if root_like { dir.to_path_buf() } else { dir.join(current.file_stem()?) }; let file = base.join(format!("{segment}.rs")); let mod_file = base.join(segment).join("mod.rs"); let file_exists = index_has_file(index, &file); let mod_exists = index_has_file(index, &mod_file); match (file_exists, mod_exists) { (true, false) => file, (false, true) => mod_file, _ => return None, } } ModulePathTarget::Literal(path) => { let resolved = dir.join(path); if index_has_file(index, &resolved) { resolved } else { return None; } } ModulePathTarget::Unknown => return None, }; } Some(current) } fn index_has_file(index: &RustIndex, path: &Path) -> bool { let normalized = normalize_path(path); index .files() .iter() .any(|(key, _)| normalize_path(key) == normalized) } /// The `src/bin/` directory a test file belongs to, when it sits in a /// binary target's module tree (#14508 review). `src/bin/.rs`, /// `src/bin//main.rs` and `src/bin//.rs` all name /// `src/bin/`. fn binary_target_module_dir(test_file: &Path) -> Option { let normalized = normalize_path(test_file); let at = normalized.find("src/bin/")?; if at > 0 && !normalized[..at].ends_with('/') { return None; } let after = &normalized[at + "src/bin/".len()..]; let first = after.split('/').next()?; let name = first.strip_suffix(".rs").unwrap_or(first); (!name.is_empty()).then(|| format!("{}src/bin/{name}", &normalized[..at])) } /// The module path a test file's own items sit under, for comparing an inline /// module chain with an absolute `crate::` path (#14508 review). A crate root /// names no module: `lib.rs`, `main.rs`, and a `src/bin` target root. fn test_file_module_path(index: &RustIndex, file: &Path) -> String { if module_stem(file).is_none() { return String::new(); } if let Some(bin_dir) = binary_target_module_dir(file) { let normalized = normalize_path(file); if normalized == format!("{bin_dir}.rs") || normalized == format!("{bin_dir}/main.rs") { return String::new(); } } let path = module_path_for_index(index, file).unwrap_or_default(); path.strip_suffix("/mod").unwrap_or(&path).to_string() } pub(super) fn match_helper_owner_call( candidates: &mut BTreeMap, context: &CompactGripContext<'_>, prefix: Option<&str>, owner: &OwnerContext<'_>, ) { if owner.name.is_empty() { return; } // A free owner is reached through a helper only when the helper body // spells a bare or module-qualified call of it; a helper calling only // `Type::name(..)` never credits the free `name` beside it (#6713). let indices = if owner.free_function { context .tests_by_free_helper_owner_call_name .get(&owner.name) } else { context.tests_by_helper_owner_call_name.get(&owner.name) }; let Some(indices) = indices else { return; }; for test_index in indices { if owner.inherent_receiver && !owner.inherent_owner.is_some_and(|function| { context.inherent_helper_reaches_owner(*test_index, function) }) { continue; } insert_related_candidate( candidates, context, prefix, *test_index, RelationReason::HelperOwnerCall, ); } } pub(super) fn match_target_affinity_owner_call( candidates: &mut BTreeMap, seam: &RepoSeam, context: &CompactGripContext<'_>, prefix: Option<&str>, owner: &OwnerContext<'_>, target_tokens: &BTreeSet, ) { if requires_concrete_activation_values(seam) || owner.name.is_empty() || target_tokens.is_empty() { return; } let Some(indices) = (if owner.free_function { context .tests_by_free_target_affinity_owner_call_name .get(&owner.name) } else { context .tests_by_target_affinity_owner_call_name .get(&owner.name) }) else { return; }; for test_index in indices { let Some(test) = context.tests.get(*test_index) else { continue; }; if !test_assertion_mentions_any_target_token(test, target_tokens) || (owner.inherent_receiver && !owner.inherent_owner.is_some_and(|function| { context.inherent_helper_reaches_owner(*test_index, function) })) { continue; } insert_related_candidate( candidates, context, prefix, *test_index, RelationReason::HelperOwnerCall, ); } } pub(super) fn test_assertion_mentions_any_target_token( test: &CompactTest<'_>, target_tokens: &BTreeSet, ) -> bool { target_tokens .iter() .any(|token| test.assertion_tokens.contains(token)) } pub(super) fn match_assertion_target_affinity( candidates: &mut BTreeMap, context: &CompactGripContext<'_>, prefix: Option<&str>, target_tokens: &BTreeSet, ) { let limit = crowded_relation_limit(context.tests.len()); let mut matched_tokens: BTreeMap = BTreeMap::new(); for token in target_tokens { if let Some(indices) = context.tests_by_assertion_token.get(token) { // A token asserted across much of the suite (`status`, `path`) // says nothing about which tests read this seam (#4434). Only // tests in the seam's package count, so another crate's common // token cannot silence the local tests that assert it. if indices.len() > limit && indices .iter() .filter(|&&test_index| { context.tests.get(test_index).is_some_and(|indexed| { prefix.is_none_or(|prefix| indexed.path_normalized.starts_with(prefix)) }) }) .nth(limit) .is_some() { continue; } for &test_index in indices { // Rank only tests this reason could still admit, so an // out-of-package or already-related test takes no slot. let admissible = !candidates.contains_key(&test_index) && context.tests.get(test_index).is_some_and(|indexed| { prefix.is_none_or(|prefix| indexed.path_normalized.starts_with(prefix)) }); if admissible { *matched_tokens.entry(test_index).or_default() += 1; } } } } // Several mid-frequency tokens from one long discriminator can still // name thousands of tests together. Past the limit, keep the tests that // assert the most target tokens, earliest index first on ties. The tie // order only keeps output deterministic; index position carries no // relevance. let mut ranked = matched_tokens.into_iter().collect::>(); if ranked.len() > limit { ranked.sort_by(|(left_index, left), (right_index, right)| { right.cmp(left).then(left_index.cmp(right_index)) }); ranked.truncate(limit); } for (test_index, _) in ranked { insert_related_candidate( candidates, context, prefix, test_index, RelationReason::AssertionTargetAffinity, ); } } pub(super) fn match_same_test_file( candidates: &mut BTreeMap, context: &CompactGripContext<'_>, prefix: Option<&str>, owner: &OwnerContext<'_>, ) { if owner.file_stem.is_empty() { let indices = owner .crate_root_file .as_ref() .and_then(|path| context.tests_by_crate_root_file.get(path)); for test_index in indices.into_iter().flatten() { insert_related_candidate( candidates, context, prefix, *test_index, RelationReason::SameTestFile, ); } return; } let stems = [ owner.file_stem.clone(), format!("{}_test", owner.file_stem), format!("{}_tests", owner.file_stem), ]; for stem in stems { if let Some(indices) = context.tests_by_file_stem.get(&stem) { for test_index in indices { // #7527: a shared leaf name is not module identity; the // finding-level relation applies the same scope. if !owner_file_admits_companion(owner, context, *test_index) { continue; } insert_related_candidate( candidates, context, prefix, *test_index, RelationReason::SameTestFile, ); } } } } fn owner_file_admits_companion( owner: &OwnerContext<'_>, context: &CompactGripContext<'_>, test_index: usize, ) -> bool { let (Some(owner_file), Some(indexed)) = ( owner.function.and_then(|function| function.file.to_str()), context.tests.get(test_index), ) else { return true; }; crate::analysis::classify::companion_scope_admits(owner_file, &indexed.path_normalized) } pub(super) fn match_same_module( candidates: &mut BTreeMap, context: &CompactGripContext<'_>, prefix: Option<&str>, owner: &OwnerContext<'_>, ) { let Some(module_path) = owner.module_path.as_deref() else { return; }; for test_index in context.same_module_indices(module_path) { insert_related_candidate( candidates, context, prefix, test_index, RelationReason::SameModule, ); } } pub(super) fn match_owner_named_test( candidates: &mut BTreeMap, context: &CompactGripContext<'_>, prefix: Option<&str>, owner: &OwnerContext<'_>, ) { for test_index in context.owner_named_indices(&owner.name_lower) { insert_related_candidate( candidates, context, prefix, test_index, RelationReason::OwnerNamedTest, ); } } pub(super) fn match_import_path_affinity( candidates: &mut BTreeMap, context: &CompactGripContext<'_>, prefix: Option<&str>, owner: &OwnerContext<'_>, ) { if owner.name.is_empty() { return; } let Some(indices) = context.tests_by_import_token.get(&owner.name) else { return; }; for test_index in indices { if !context .tests .get(*test_index) .is_some_and(|indexed| test_imports_owner_compact(indexed, &owner.name)) { continue; } insert_related_candidate( candidates, context, prefix, *test_index, RelationReason::ImportPathAffinity, ); } } pub(super) fn match_fixture_owner_affinity( candidates: &mut BTreeMap, context: &CompactGripContext<'_>, prefix: Option<&str>, owner: &OwnerContext<'_>, ) { for fixture_name in owner.fixture_names.iter() { if let Some(indices) = context.tests_by_call_name.get(fixture_name) { for test_index in indices { insert_related_candidate( candidates, context, prefix, *test_index, RelationReason::FixtureOwnerAffinity, ); } } } } pub(super) fn dedupe_related_candidates<'context, 'index>( candidates: BTreeMap, context: &'context CompactGripContext<'index>, ) -> Vec<(&'context CompactTest<'index>, RelationReason)> { let mut related: Vec<(&'context CompactTest<'index>, RelationReason)> = Vec::new(); let mut seen: std::collections::HashSet<(String, PathBuf, usize)> = std::collections::HashSet::new(); for (test_index, reason) in candidates { let Some(indexed) = context.tests.get(test_index) else { continue; }; let key = ( indexed.test.name.clone(), indexed.test.file.clone(), indexed.test.start_line, ); if seen.insert(key) { related.push((indexed, reason)); } } related } pub(super) fn insert_related_candidate( candidate_reasons: &mut BTreeMap, context: &CompactGripContext<'_>, prefix: Option<&str>, test_index: usize, reason: RelationReason, ) { if candidate_reasons.contains_key(&test_index) { return; } let Some(indexed) = context.tests.get(test_index) else { return; }; if let Some(prefix) = prefix && !indexed.path_normalized.starts_with(prefix) { return; } candidate_reasons.insert(test_index, reason); } #[cfg(test)] pub(super) fn find_related_tests_compact<'a>( seam: &RepoSeam, context: &'a CompactGripContext<'_>, ) -> Vec<&'a CompactTest<'a>> { find_related_tests_ranked(seam, context) .into_iter() .take(COMPACT_RELATED_TEST_LIMIT) .map(|(indexed, _reason)| indexed) .collect() } /// Every related test for `seam` with its relation, in rank order. Compact /// evidence caps the tests it scores but decides reach over this full list, /// so a reach-bearing relation ranked below the cap still counts. pub(super) fn find_related_tests_ranked<'a>( seam: &RepoSeam, context: &'a CompactGripContext<'_>, ) -> Vec<(&'a CompactTest<'a>, RelationReason)> { let mut related = find_related_tests_with_context(seam, context); let owner_fn = context.owner_function(seam.file(), seam.display_line()); let _best_oracles = sort_related_tests_for_seam(seam, context, owner_fn, &mut related); related } #[derive(Clone, Eq, PartialEq, Ord, PartialOrd)] pub(super) struct RelatedTestRankKey { relation_confidence: u8, relation_reason: u8, oracle_strength: Reverse, activation_overlap: Reverse, file: PathBuf, test_name: String, line: usize, } /// The strongest-oracle answer for one related test of one seam. pub(super) type BestOracle = (OracleKind, OracleStrength, Option); /// Sort `related` into rank order and return each test's best oracle, in /// the sorted order. The rank key already needs the best oracle of every /// related test, so the caller reuses it instead of asking again (#5361). pub(super) fn sort_related_tests_for_seam<'a>( seam: &RepoSeam, context: &CompactGripContext<'_>, owner_fn: Option<&FunctionSummary>, related: &mut [(&'a CompactTest<'a>, RelationReason)], ) -> Vec { let owner = seam_owner_activation(seam, context); let boolean_pin = BooleanBoundaryPin::establish(seam, owner_fn, context.index); // The gate reads the complete relation set of this seam (#12434); asking // per test would see a lone proximity relation and disagree with the // stage views. let refuse = super::refuses_other_function_oracle( seam, related.iter().map(|(_, reason)| *reason), owner_fn.is_some(), ); let claims_pin = super::claims_payload_pin::ClaimsPayloadPin::establish( seam, owner_fn, context.index, related.iter().map(|(indexed, _)| indexed.test), ); // #12478: one reverse owner-reach walk for the whole related set. A // one-element slice per test rebuilt the walk (and its unbounded // OnceLock closure) on every related test of the seam. let credited_views = ((refuse || claims_pin.is_some()) && !related.is_empty()).then(|| { let related_pairs: Vec<_> = related .iter() .map(|&(indexed, reason)| (indexed.test, reason)) .collect(); super::credited_related_tests( context, owner_fn, &related_pairs, refuse, claims_pin.as_ref(), ) }); debug_assert!( credited_views .as_ref() .is_none_or(|views| views.len() == related.len()) ); let mut ranked: Vec<_> = related .iter() .enumerate() .map(|(i, &entry)| { let (indexed, reason) = entry; // #12060: rank and publish the oracle the stages credit. A // proximity test whose assertion pins another function keeps its // identity but offers no oracle for this match arm or predicate // boundary (#12434). let credited_test = credited_views .as_ref() .and_then(|views| views.get(i)) .map_or(indexed.test, AsRef::as_ref); let oracle = best_oracle( credited_test, seam, owner_fn, context.index, // #8282: the run's shared instance, like every other walk // stage; a per-key fresh instance re-paid the whole-index // lazily computed facts once per (seam, related test) rank. context.pin_syntax(), boolean_pin.as_ref(), ); let key = related_test_rank_key(seam, context, indexed, reason, owner.as_ref(), &oracle); (key, entry, oracle) }) .collect(); // Stable, like the `sort_by_cached_key` this replaces. ranked.sort_by(|a, b| a.0.cmp(&b.0)); let mut oracles = Vec::with_capacity(ranked.len()); for (slot, (_key, entry, oracle)) in related.iter_mut().zip(ranked) { *slot = entry; oracles.push(oracle); } oracles } pub(super) fn related_test_rank_key( seam: &RepoSeam, context: &CompactGripContext<'_>, indexed: &CompactTest<'_>, reason: RelationReason, owner: Option<&SeamOwnerActivation<'_>>, best_oracle: &BestOracle, ) -> RelatedTestRankKey { let oracle_strength = &best_oracle.1; RelatedTestRankKey { relation_confidence: reason.confidence().rank(), relation_reason: reason.priority(), oracle_strength: Reverse(oracle_strength.rank()), activation_overlap: Reverse(activation_overlap_score(seam, context, indexed, owner)), file: indexed.test.file.clone(), test_name: indexed.test.name.clone(), line: indexed.test.start_line, } } pub(super) fn fixture_names_for_owner_file( facts: rust_index::FileFactsView<'_>, ) -> BTreeSet { facts .functions .iter() .filter(|f| { !f.source_role.is_evidence_role() && (is_fixture_named(&f.name) || f.body.contains("#[fixture]")) }) .map(|f| f.name.clone()) .collect() } /// Tokens drawn from a `RepoSeam`'s `RequiredDiscriminator`. Filtered /// through `extract_identifier_tokens` so common short words and /// stop-tokens are already excluded. pub(super) fn required_discriminator_tokens(seam: &RepoSeam) -> Vec { extract_identifier_tokens(required_discriminator_text(seam)) } pub(super) fn required_discriminator_text(seam: &RepoSeam) -> &str { use crate::analysis::seams::RequiredDiscriminator; match seam.required_discriminator() { RequiredDiscriminator::BoundaryValue { description } | RequiredDiscriminator::ReturnValue { description } => description.as_str(), RequiredDiscriminator::ErrorVariant { variant } => variant.as_str(), RequiredDiscriminator::FieldValue { field } => field.as_str(), RequiredDiscriminator::Effect { sink } => sink.as_str(), RequiredDiscriminator::MatchArmTaken { arm } => arm.as_str(), RequiredDiscriminator::CallSite { target } => target.as_str(), } } /// Token-aware: does any assertion text in `test` contain at least one /// of `tokens` as a whole identifier? Substring match would let /// `discount` accidentally match `discount_threshold`; we want exact /// identifier hits. #[cfg(test)] pub(super) fn assertion_targets_seam(test: &TestSummary, tokens: &[String]) -> bool { if tokens.is_empty() { return false; } for assertion in &test.assertions { let assertion_tokens = extract_identifier_tokens(&assertion.text); if assertion_tokens .iter() .any(|at| tokens.iter().any(|t| at == t)) { return true; } } false } #[cfg(test)] pub(super) fn same_test_file(test_file: &Path, owner_stem: &str) -> bool { let Some(stem) = module_stem(test_file) else { return false; }; if stem == owner_stem { return true; } // Suffix check avoids the allocation that `stem == format!("{owner_stem}_test")` // would do per call. Two suffix variants cover the common naming // conventions: `*_test.rs` and `*_tests.rs`. if let Some(prefix) = stem.strip_suffix("_test") && prefix == owner_stem { return true; } if let Some(prefix) = stem.strip_suffix("_tests") && prefix == owner_stem { return true; } false } /// Module path slug for a Rust source file: the path components below /// `src/` or `tests/`, joined by `/`, dropping the file extension. /// Returns `None` for files that do not sit under one of those roots. /// Examples (Unix-style after normalize): /// - `crates/ripr/src/auth/login.rs` → `auth/login` /// - `tests/cli_smoke.rs` → `cli_smoke` pub(super) fn module_path_for(file: &Path) -> Option { let normalized = normalize_path(file); let body = normalized .rfind("/src/") .map(|idx| &normalized[idx + "/src/".len()..]) .or_else(|| { normalized .rfind("/tests/") .map(|idx| &normalized[idx + "/tests/".len()..]) }) .or_else(|| normalized.strip_prefix("src/")) .or_else(|| normalized.strip_prefix("tests/"))?; let trimmed = body.strip_suffix(".rs").unwrap_or(body); if trimmed.is_empty() { None } else { Some(trimmed.to_string()) } } pub(super) fn module_path_for_index(index: &RustIndex, file: &Path) -> Option { module_path_for(&rust_index::compilation_unit_path(index, file)) } /// Above this many tests, one relation key (an assertion token, a parent /// module) covers much of the suite rather than the changed code. The floor /// keeps small workspaces on the plain rules. pub(super) fn crowded_relation_limit(test_count: usize) -> usize { (test_count / 100).max(64) } /// In a crowded parent module, keep only the tests that sit close to the /// owner: the parent itself, the owner's own module and its children, and a /// test-named sibling (`tests`, `*_tests`, `test_*`). Distant siblings such as /// `analysis/classify` for an `analysis/cancellation` owner stay unrelated. pub(super) fn close_module(owner_module: &str, test_module: &str) -> bool { let Some((parent, leaf)) = owner_module.rsplit_once('/') else { return false; }; if test_module == parent { return true; } let flattened = parent.replace('/', "_"); let Some(rest) = test_module .strip_prefix(parent) .and_then(|rest| rest.strip_prefix('/')) .or_else(|| { test_module .strip_prefix(flattened.as_str()) .and_then(|rest| rest.strip_prefix('/')) }) else { return false; }; let segment = rest.split('/').next().unwrap_or(rest); segment == leaf || segment == "test" || segment == "tests" || segment.ends_with("_test") || segment.ends_with("_tests") || segment.starts_with("test_") } /// Two files share a module if any non-leaf segment of the owner's /// module path appears as a prefix of the test's module path. The leaf /// stem is excluded so this does not duplicate `same_test_file`. pub(super) fn same_module(owner_module: &str, test_module: &str) -> bool { let parent = match owner_module.rsplit_once('/') { Some((parent, _leaf)) => parent, None => return false, }; if parent.is_empty() { return false; } test_module == parent || test_module.starts_with(&format!("{parent}/")) || test_module.starts_with(&format!("{}/", parent.replace('/', "_"))) } /// Body mentions the owner via an explicit qualified-path or `use` /// shape — without calling it. The direct-call check has already /// excluded callers, so this fires for tests that import the symbol /// (or qualify it via a path) but route through some wrapper (common /// in integration tests). /// /// Tightened per #310 review: pure token co-occurrence /// (owner_name appearing as a bare identifier somewhere in the body) /// was too easy to satisfy with local bindings, comments, or /// unrelated identifiers. The detector now requires either: /// /// 1. a `module::owner_name` qualified path anywhere in the body /// (catches `crate::pricing::discounted_total`, /// `super::pricing::discounted_total`, `pricing::discounted_total` /// — they all contain `::owner_name`); or /// 2. an inline `use ... owner_name` line in the test body. File- /// scope `use` lines are not in `test.body` so this only covers /// in-function imports. pub(super) fn test_imports_owner_compact(test: &CompactTest<'_>, owner_name: &str) -> bool { if owner_name.is_empty() { return false; } let qualified = format!("::{owner_name}"); // Both branches below imply `is_import_relevant_line`, which is the // retention filter for `code_lines`; keep them inside that predicate. for code in &test.code_lines { if code.contains(&qualified) { return true; } if code.trim_start().starts_with("use ") && extract_identifier_tokens(code) .iter() .any(|token| token == owner_name) { return true; } } false } /// The one eligibility rule shared by the import readers below and by /// `CompactTest::code_lines` retention. A stripped line that fails it can /// affect neither `import_affinity_tokens` nor `test_imports_owner_compact` /// (whose `::owner` branch implies `::` and whose `use` branch is this /// prefix), so the compact context keeps only lines that pass it. Widening /// either reader requires widening this predicate, never a private copy. pub(super) fn is_import_relevant_line(code: &str) -> bool { code.contains("::") || code.trim_start().starts_with("use ") } pub(super) fn import_affinity_tokens(code_lines: &[String]) -> BTreeSet { let mut tokens = BTreeSet::new(); for code in code_lines { if is_import_relevant_line(code) { tokens.extend(extract_identifier_tokens(code)); } } tokens } /// Drop everything after a `//` line comment and replace string-literal /// contents with empty strings. v1 best-effort: handles `"..."` with /// `\\` and `\"` escapes; raw strings (`r#"..."#`), char literals /// (`'a'`), and block comments (`/* ... */`) are out of scope — those /// shapes are rare inside test bodies and treating them as code is a /// safe over-match (the previous helper accepted them all). pub(super) fn strip_comments_and_strings(line: &str) -> String { // Strip `//` line comments first; everything after is non-code. let without_comment = match line.find("//") { Some(idx) => &line[..idx], None => line, }; let mut out = String::with_capacity(without_comment.len()); let mut in_string = false; let mut in_char = false; let mut escaped = false; let mut chars = without_comment.chars().peekable(); while let Some(ch) = chars.next() { if in_string || in_char { if escaped { escaped = false; continue; } match ch { '\\' => escaped = true, '"' if in_string => in_string = false, '\'' if in_char => in_char = false, _ => {} } continue; } match ch { '"' => in_string = true, '\'' => { let mut lookahead = chars.clone(); let is_char_literal = match lookahead.next() { Some('\\') => { if lookahead.next() == Some('u') { if lookahead.next() == Some('{') { for next in lookahead.by_ref() { if next == '}' { break; } } } } else { lookahead.next(); } lookahead.next() == Some('\'') } Some(_) => lookahead.next() == Some('\''), None => false, }; if is_char_literal { in_char = true; } else { out.push(ch); } } _ => out.push(ch), } } out } pub(super) fn is_fixture_named(name: &str) -> bool { let prefixes = ["fixture_", "setup_", "make_", "build_", "new_", "mock_"]; let suffixes = ["_fixture", "_factory"]; prefixes.iter().any(|p| name.starts_with(p)) || suffixes.iter().any(|s| name.ends_with(s)) } pub(super) fn normalize_path(path: &Path) -> String { path.to_string_lossy() .replace('\\', "/") .trim_start_matches("./") .to_string() } /// Extract a source-file stem after normalizing separators from either /// host. Grip inputs can carry paths produced on a different platform /// than the host resolving the association (#3469); a foreign separator /// makes [`std::path::Path::file_stem`] treat an entire relative path as /// one file name, so same-test-file lookups miss on exactly one host. /// Non-UTF-8 paths fail closed: lossy replacement characters could /// collapse distinct file names into one stem and fabricate a /// same-test-file relation (the #3545 `cross_host_stem` guard). /// Production association keys on [`module_stem`] (#5395); this raw stem /// stays for the cross-host and non-UTF-8 regression tests. #[cfg(test)] pub(super) fn normalized_file_stem(path: &Path) -> String { let Some(text) = path.to_str() else { return String::new(); }; let unified = text.replace('\\', "/"); let file = unified.rsplit('/').next().unwrap_or_default(); Path::new(file) .file_stem() .and_then(|stem| stem.to_str()) .unwrap_or_default() .to_string() } pub(super) fn package_prefix(path: &Path) -> Option { let normalized = normalize_path(path); if let Some(rest) = normalized.strip_prefix("crates/") && let Some((crate_name, crate_relative)) = rest.split_once('/') && (crate_relative.starts_with("src/") || crate_relative.starts_with("tests/")) { return Some(format!("crates/{crate_name}/")); } for marker in ["/src/", "/tests/"] { if let Some(idx) = normalized.rfind(marker) { let prefix = &normalized[..idx]; if prefix.is_empty() { return None; } return Some(format!("{prefix}/")); } } None } pub(super) fn package_scope(path: &Path) -> Option { let normalized = normalize_path(path); if let Some(prefix) = package_prefix(path) { return Some(prefix); } if normalized.starts_with("src/") || normalized.starts_with("tests/") { return Some(String::new()); } None }