diff --git a/.ripr/traceability.d/RIPR-SPEC-0442.toml b/.ripr/traceability.d/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..b2b99df4ade --- /dev/null +++ b/.ripr/traceability.d/RIPR-SPEC-0442.toml @@ -0,0 +1,55 @@ +# Aliased direct import of the owner credits the owner only when the import +# names its module in the same compilation unit (#14508). +[[behavior]] +id = "RIPR-SPEC-0442" +name = "Aliased owner import credit" +spec = "docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md" +tests = [ + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_an_integration_test_module_shadows_the_library_module_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_nested_module_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_mod_rs_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_sibling_module_declares_the_alias_name_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_test_module_declares_the_alias_name_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_local_function_shadows_it_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_inline_module_shadows_the_library_module_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_root_imports_the_library_root_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_scoped_binding_shadows_it_then_owner_takes_no_value_from_it", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_table_covers_each_scanned_form", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_ignores_a_genuine_call_in_the_last_match_arm", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_keeps_a_real_match_arm_binding", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_flat_tuple_pattern_binding", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_nested_tuple_pattern_binding", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_slice_pattern_binding", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_binding_in_a_later_loop", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_library_child_module_imports_the_crate_root_owner_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_child_module_imports_its_crate_root_owner_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_child_module_imports_the_binary_root_then_library_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_nearer_unsupported_import_shadows_it_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_closure_in_a_macro_token_tree_shadows_it_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_test_function_parameter_shadows_it_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_cfg_gated_module_has_two_paths_then_owner_gets_no_related_test", +] +fixtures = [ + "fixtures/evidence-promotion-honesty-corpus/corpus.json", +] +code = [ + "crates/ripr/src/analysis/test_grip_evidence/related_tests.rs", + "crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs", + "crates/ripr/src/analysis/classify/const_flow.rs", + "crates/ripr/src/analysis/extract/shadow.rs", + "crates/ripr/src/analysis/syntax/ra.rs", +] +outputs = [ + "docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md", +] +metrics = [ + "unit_test_pass_rate", + "corpus_case_pass_rate", +] diff --git a/changelog.d/14508-aliased-owner-import.md b/changelog.d/14508-aliased-owner-import.md new file mode 100644 index 00000000000..0bbea5ee967 --- /dev/null +++ b/changelog.d/14508-aliased-owner-import.md @@ -0,0 +1,7 @@ + +- `ripr pilot` and the repo-exposure grip path credit a test that imports the + changed owner under an alias as a direct owner call when the import names the + owner's module in the same compilation unit (crate root, nested file module, + `mod.rs`, or an integration test's package-qualified import). A `crate::` + import in an integration test or a binary target names that unit's own + module, so it does not credit the library owner (#14508). diff --git a/crates/ripr/src/analysis/classifier/evidence.rs b/crates/ripr/src/analysis/classifier/evidence.rs index d52dbccc2a7..c6587f92956 100644 --- a/crates/ripr/src/analysis/classifier/evidence.rs +++ b/crates/ripr/src/analysis/classifier/evidence.rs @@ -3970,6 +3970,7 @@ mod tests { fn owner_local_bindings_exclude_names_the_signature_binds() { let binding = |name: &str| LetBindingFact { line: 1, + scope_end: None, name: name.to_string(), }; let owner = FunctionSummary { diff --git a/crates/ripr/src/analysis/classify/const_flow.rs b/crates/ripr/src/analysis/classify/const_flow.rs index 9e7c6b1249a..5d1d14be406 100644 --- a/crates/ripr/src/analysis/classify/const_flow.rs +++ b/crates/ripr/src/analysis/classify/const_flow.rs @@ -211,6 +211,53 @@ impl ModuleScopes { .iter() .all(|line| self.0.get(line) == Some(declared)) } + + /// The chain of inline `mod` names in force at `line`, outermost first, + /// ignoring non-module blocks. `None` when the line is outside the + /// scanned source (#14508 review). + pub(in crate::analysis) fn module_chain_at(&self, line: usize) -> Option> { + let chain = self.0.get(&line)?; + Some(chain.iter().filter_map(|name| name.as_deref()).collect()) + } + + /// Whether the chain of `mod` items in force at `declaration_line` is at + /// least as deep as `use_module_depth` and is a prefix of the chain at + /// `call_line`. That is a declaration in the import's module or a nested + /// module, and in the call's module or an enclosing one. A declaration in + /// an enclosing module than the import is shadowed by the import, so it + /// does not withhold the call (#14508 review). + pub(in crate::analysis) fn declaration_shadows_import( + &self, + declaration_line: usize, + use_module_depth: usize, + call_line: usize, + ) -> bool { + let (Some(declared), Some(used)) = (self.0.get(&declaration_line), self.0.get(&call_line)) + else { + return false; + }; + // A non-module block (`impl`, `fn`, or a bare block) around the + // declaration is not a module scope. Dropping that marker would make + // an associated or block-local function look like a root declaration + // and falsely shadow a genuine import (#14508 review). + if declared.iter().any(Option::is_none) { + return false; + } + let declared = declared + .iter() + .filter_map(|name| name.as_deref()) + .collect::>(); + let used = used + .iter() + .filter_map(|name| name.as_deref()) + .collect::>(); + declared.len() >= use_module_depth + && declared.len() <= used.len() + && declared + .iter() + .zip(used.iter()) + .all(|(declared, used)| declared == used) + } } /// What evaluating the related tests under the old and new value showed. diff --git a/crates/ripr/src/analysis/classify/const_flow/tests.rs b/crates/ripr/src/analysis/classify/const_flow/tests.rs index 57d2925f5d5..1a14625d0b0 100644 --- a/crates/ripr/src/analysis/classify/const_flow/tests.rs +++ b/crates/ripr/src/analysis/classify/const_flow/tests.rs @@ -431,6 +431,20 @@ fn modules_with_the_same_chain_share_a_scope() { assert!(super::shares_module_scope(source, 2, &[3])); } +#[test] +fn an_associated_function_does_not_shadow_a_module_level_import() { + let source = "use crate::owner as dt;\n\ + impl Rival {\n\ + fn dt() {}\n\ + }\n\ + #[test]\n\ + fn genuine() { dt(); }\n"; + assert!( + !super::module_scopes(source).declaration_shadows_import(3, 0, 6), + "an associated function cannot rebind the module-level `dt` import" + ); +} + /// Run the whole decision on a one-file crate: its production functions that /// name `LIMIT` are the readers and its `#[test]`s the related tests. fn decide(tests: &str, old: &str, new: &str) -> Result, String> { diff --git a/crates/ripr/src/analysis/classify/mod.rs b/crates/ripr/src/analysis/classify/mod.rs index 979d0a87478..8e5673ec1b9 100644 --- a/crates/ripr/src/analysis/classify/mod.rs +++ b/crates/ripr/src/analysis/classify/mod.rs @@ -101,7 +101,7 @@ pub(in crate::analysis) use caller_loop_selector::withhold_caller_loop_selector_ pub(in crate::analysis) use compile_time_guard::constrained_by_compile_time_assertion; pub(in crate::analysis) use const_flow::{ ChangedConsts, ConstFlow, associated_const_binding, const_value_changes, evaluate_const_flow, - shares_module_scope, + module_scopes, shares_module_scope, }; pub(in crate::analysis) use const_readers::{const_reader_returns, same_file_const_readers}; pub(in crate::analysis) use context::ProbeContext; @@ -211,14 +211,14 @@ pub(in crate::analysis) use refusal_miss::{ }; pub(in crate::analysis) use related_tests::{ DependencyEdgeContext, RelatedTestCandidateIndex, assertion_pins_display_string, - body_contains_owner_call, call_text_may_call_free_function, changes_only_string_literals, - companion_scope_admits, declared_dependent_package_calls_owner, - find_related_tests_with_candidate_index, free_helper_call_resolves, impl_self_type_name, - inherent_owner_call_resolves, is_display_fmt_owner, is_drop_destructor, is_partial_eq_method, - manifests_with_unindexed_files, method_call_resolves_to_impl, module_stem, - owner_call_is_direct, owner_call_text, owner_dispatch_trait, owner_impl_identity_shadowed, - owner_trait_name, package_prefix, requires_inherent_receiver_identity, - resolves_method_in_prefix, test_calls_free_function, + body_contains_owner_call, call_text_may_call_free_function, call_text_spells_bare_free_call, + changes_only_string_literals, companion_scope_admits, declared_dependent_package_calls_owner, + find_related_tests_with_candidate_index, free_function_call_text, free_helper_call_resolves, + impl_self_type_name, inherent_owner_call_resolves, is_display_fmt_owner, is_drop_destructor, + is_partial_eq_method, manifests_with_unindexed_files, method_call_resolves_to_impl, + module_stem, owner_call_is_direct, owner_call_text, owner_dispatch_trait, + owner_impl_identity_shadowed, owner_trait_name, package_prefix, + requires_inherent_receiver_identity, resolves_method_in_prefix, test_calls_free_function, }; #[cfg(feature = "lang-rust")] pub(in crate::analysis) use reveal::RELATED_TESTS_RENDER_CAP; diff --git a/crates/ripr/src/analysis/classify/related_tests.rs b/crates/ripr/src/analysis/classify/related_tests.rs index 94a6513e76e..3e0ad5e4c28 100644 --- a/crates/ripr/src/analysis/classify/related_tests.rs +++ b/crates/ripr/src/analysis/classify/related_tests.rs @@ -8683,6 +8683,28 @@ pub(in crate::analysis) fn free_function_call_text<'text>( text.get(at..) } +/// Whether one captured call's raw source text spells the bare free-function +/// call `name(` — the only spelling an imported alias can bind to. A +/// module-qualified path (`rival::name(`) names that module's function, not +/// the alias, even when the module name is lowercase (#14508 review). +pub(in crate::analysis) fn call_text_spells_bare_free_call(text: &str, name: &str) -> bool { + if name.is_empty() { + return false; + } + let masked = mask_comments_and_strings(text); + let mut calls = masked + .match_indices(name) + .map(|(at, _)| at) + .filter(|&at| is_free_function_call_at(&masked, at, name)) + .peekable(); + calls.peek().is_some() + && calls.all(|at| { + let qualifier = masked[..at].trim_end(); + let qualifier = qualifier.strip_suffix("r#").unwrap_or(qualifier); + !qualifier.trim_end().ends_with("::") + }) +} + /// The text a captured call named like `owner` contributes as an owner /// call: the whole line for an owner that may be reached through a path or /// receiver, the free-call suffix for a module-level `fn`, `None` when the diff --git a/crates/ripr/src/analysis/extract/shadow.rs b/crates/ripr/src/analysis/extract/shadow.rs index 71b90eb8f5b..f2ee5884ae3 100644 --- a/crates/ripr/src/analysis/extract/shadow.rs +++ b/crates/ripr/src/analysis/extract/shadow.rs @@ -10,15 +10,17 @@ //! the original text, and shadow-shaped text inside comments, strings, or //! char literals never defeats a real call (#3728 rounds 3-5). //! -//! #3727 Slice A adds a parser-backed decision path with the SAME rules at -//! line granularity: on files whose `FileFacts.used_lexical_fallback` is -//! false, [`ShadowAuthority::ParserBodyFacts`] derives the decision from -//! the parser-produced `nested_fn_names` / `let_bindings` fact fields; on -//! fallback files (or files absent from the index) -//! [`ShadowAuthority::LexicalMaskedBody`] runs the byte-level scanners -//! byte-identically. THE FLAG — not set emptiness — is the discriminator: -//! a parser-backed file can legitimately contain zero bindings, and empty -//! fact sets on parser-backed files are real "no shadow" results. +//! The two authorities share the same binding vocabulary and the same +//! whole-body `let`/nested-`fn` rules, but they diverge deliberately for the +//! scoped binding forms added in #14508: the parser path carries each +//! binding's `scope_end` and defeats only uses inside that body/arm, while +//! the lexical fallback detects the same forms and withholds the whole body. +//! The fallback is deliberately conservative (it may drop credit for a +//! genuine call after the scope on a file the parser could not read; it +//! never grants credit to a scoped binding). THE FLAG — not set emptiness — +//! is the discriminator: a parser-backed file can legitimately contain zero +//! bindings, and empty fact sets on parser-backed files are real "no shadow" +//! results. use crate::analysis::facts::LetBindingFact; @@ -90,12 +92,18 @@ pub(crate) fn fact_body_let_shadow_line( } let_bindings .iter() + .filter(|binding| binding.scope_end.is_none()) .filter(|binding| binding.name == callee) .map(|binding| binding.line) .min() } /// Parser-fact twin of [`body_shadows_callee_at_line`] (#3727 Slice A). +/// +/// A `let` binding keeps the shipped end-of-function over-approximation +/// (`scope_end == None`); a closure, `for`, match-arm, `if let`/`while let` +/// or nested-fn parameter carries its body/arm end and defeats only uses +/// inside that scope (#14508 review). pub(crate) fn fact_body_shadows_callee_at_line( nested_fn_names: &[String], let_bindings: &[LetBindingFact], @@ -103,7 +111,25 @@ pub(crate) fn fact_body_shadows_callee_at_line( body_line: usize, ) -> bool { fact_body_defines_callee_fn(nested_fn_names, callee) - || fact_body_let_shadow_line(let_bindings, callee).is_some_and(|shadow| shadow <= body_line) + || fact_body_binding_shadows_at_line(let_bindings, callee, body_line) +} + +/// Whether a binding of `callee` is in scope at `body_line`: the binding +/// starts at its own line and ends at `scope_end` (inclusive), or at the end +/// of the function when `scope_end` is `None` (a `let`). +pub(crate) fn fact_body_binding_shadows_at_line( + let_bindings: &[LetBindingFact], + callee: &str, + body_line: usize, +) -> bool { + if callee.is_empty() { + return false; + } + let_bindings.iter().any(|binding| { + binding.name == callee + && binding.line <= body_line + && binding.scope_end.is_none_or(|end| body_line <= end) + }) } /// Whole-word identifier extraction over one binding pattern's text @@ -278,6 +304,148 @@ pub(crate) fn test_body_defines_callee_fn(body: &str, callee: &str) -> bool { pub(crate) fn body_shadows_callee_at_line(body: &str, callee: &str, body_line: usize) -> bool { test_body_defines_callee_fn(body, callee) || test_body_let_shadow_line(body, callee).is_some_and(|shadow| shadow <= body_line) + || test_body_scoped_shadow_at_line(body, callee) +} + +/// The current match arm's pattern: the text after the last top-level `,`, +/// `;` or `{` in the pre-`=>` text. Depth tracking keeps a tuple or struct +/// pattern's bindings, which a plain `rsplit` on `,` would drop (#14508 +/// review). +fn arm_pattern_before_arrow(text: &str) -> &str { + let mut depth = 0i32; + let mut cut = 0usize; + for (index, byte) in text.bytes().enumerate() { + match byte { + b')' | b']' | b'}' => depth -= 1, + b'(' | b'[' => depth += 1, + b'{' => { + if depth == 0 { + cut = index + 1; + } + depth += 1; + } + b',' | b';' if depth == 0 => cut = index + 1, + _ => {} + } + } + &text[cut..] +} + +/// Lexical fallback for the scoped binding forms the parser facts cover +/// (#14508 review): a closure, `for`, match-arm, `if let`/`while let` or +/// nested-fn parameter that names `callee`. The lexical path is a +/// whole-body approximation like [`test_body_let_shadow_line`]: it withholds +/// credit for the whole body rather than computing the binding's exact +/// extent. That is the fail-closed direction (a genuine call after the scope +/// may lose credit on a file the parser could not read), and it keeps the +/// fallback from crediting a scoped binding as the owner. +pub(crate) fn test_body_scoped_shadow_at_line(body: &str, callee: &str) -> bool { + if callee.is_empty() { + return false; + } + // `for in ..` + if any_between_keywords(body, "for ", " in ", callee) { + return true; + } + // `if let = ..` and `while let = ..` + for keyword in ["if let ", "while let "] { + if any_between_keywords(body, keyword, " = ", callee) { + return true; + } + } + // `match .. { => .. }` + let mut search = 0usize; + while let Some(offset) = body[search..].find("match ") { + let open = search + offset; + let Some(brace) = body[open..].find('{') else { + break; + }; + let arms = &body[open + brace + 1..]; + // Only text before a `=>` is a pattern; the final segment is the + // last arm's body and must not be scanned as a pattern (#14508 + // review). + let mut rest = arms; + while let Some((pattern, after)) = rest.split_once("=>") { + let pattern = arm_pattern_before_arrow(pattern); + if pattern_contains_word(pattern, callee) { + return true; + } + rest = after; + } + search = open + brace + 1; + } + // `|| ..` + let mut search = 0usize; + while let Some(offset) = body[search..].find('|') { + let start = search + offset; + if body.as_bytes().get(start + 1) == Some(&b'|') { + search = start + 2; + continue; + } + let Some(end) = body[start + 1..].find('|') else { + break; + }; + let params = &body[start + 1..start + 1 + end]; + if pattern_contains_word(params, callee) { + return true; + } + search = start + 1 + end + 1; + } + // `fn (: T) ..` + let mut search = 0usize; + while let Some(offset) = body[search..].find("fn ") { + let start = search + offset; + search = start + 3; + let Some(open) = body[start..].find('(') else { + continue; + }; + let parameter_list = &body[start + open..]; + let mut depth = 0usize; + let mut close = None; + for (offset, byte) in parameter_list.bytes().enumerate() { + match byte { + b'(' => depth += 1, + b')' => { + depth = depth.saturating_sub(1); + if depth == 0 { + close = Some(offset); + break; + } + } + _ => {} + } + } + let Some(close) = close else { + continue; + }; + let params = ¶meter_list[1..close]; + if pattern_contains_word(params, callee) { + return true; + } + } + false +} + +/// Whether any `` occurrence names `callee`, so a later +/// loop or `if let` binding is not invisible (#14508 review). +fn any_between_keywords(body: &str, start: &str, end: &str, callee: &str) -> bool { + // Rust tokens may be separated by newlines as well as spaces. Only this + // boolean lexical query needs the normalized text; callers retain the + // original body and its offsets (#14508 review). + let normalized = body.split_whitespace().collect::>().join(" "); + let body = normalized.as_str(); + let mut search = 0usize; + while let Some(offset) = body[search..].find(start) { + let pattern_start = search + offset + start.len(); + let Some(end_offset) = body[pattern_start..].find(end) else { + return false; + }; + if pattern_contains_word(&body[pattern_start..pattern_start + end_offset], callee) { + return true; + } + search = pattern_start + end_offset + end.len(); + } + false } /// Whole-word containment: `word` delimited by non-identifier characters on @@ -308,6 +476,7 @@ mod fact_authority_tests { fn binding(line: usize, name: &str) -> LetBindingFact { LetBindingFact { line, + scope_end: None, name: name.to_string(), } } @@ -442,4 +611,154 @@ mod fact_authority_tests { ); } } + + #[test] + fn scoped_shadow_ignores_a_genuine_call_in_the_last_match_arm() { + let body = "match v {\n Some(x) => helper(x),\n _ => owner(1)\n}\n"; + assert!( + !test_body_scoped_shadow_at_line(body, "owner"), + "the last arm's body is not a pattern; a genuine owner(..) call must not shadow" + ); + } + + #[test] + fn scoped_shadow_keeps_a_real_match_arm_binding() { + let body = "match v {\n Some(owner) => helper(x),\n _ => other(1)\n}\n"; + assert!( + test_body_scoped_shadow_at_line(body, "owner"), + "a real arm binding of owner must still shadow" + ); + } + + #[test] + fn scoped_shadow_table_covers_each_scanned_form() { + let cases = [ + ("for pattern", "for owner in items { use_it(); }", true), + ("for other", "for item in items { use_it(); }", false), + ( + "if let pattern", + "if let Some(owner) = value { use_it(); }", + true, + ), + ( + "if let other", + "if let Some(item) = value { use_it(); }", + false, + ), + ( + "while let pattern", + "while let Some(owner) = value { use_it(); }", + true, + ), + ( + "while let other", + "while let Some(item) = value { use_it(); }", + false, + ), + ("closure parameter", "let f = |owner| owner;", true), + ("closure other", "let f = |item| item;", false), + ("nested fn parameter", "fn helper(owner: i32) { }", true), + ("nested fn other", "fn helper(item: i32) { }", false), + ( + "match arm binding", + "match v { Some(owner) => helper(x), _ => other(1) }", + true, + ), + ( + "match arm other", + "match v { Some(item) => helper(x), _ => other(1) }", + false, + ), + ( + "last arm bare call", + "match v { Some(x) => helper(x), _ => owner(1) }", + false, + ), + ( + "last arm block call", + "match v { Some(x) => helper(x), _ => { owner(1) } }", + false, + ), + ( + "last arm binding", + "match v { Some(x) => helper(x), owner => owner(1) }", + true, + ), + ( + "tuple pattern binding", + "match pair { (owner, _) => owner(100, 100), _ => 0 }", + true, + ), + ( + "struct pattern binding", + "match pair { Foo { owner, .. } => owner(100, 100), _ => 0 }", + true, + ), + ( + "nested tuple pattern binding", + "match pair { Some((owner, _)) => owner(100, 100), _ => 0 }", + true, + ), + ( + "slice pattern binding", + "match pair { [owner, _] => owner(100, 100), _ => 0 }", + true, + ), + ]; + for (label, body, expected) in cases { + assert_eq!( + test_body_scoped_shadow_at_line(body, "owner"), + expected, + "{label}: {body}" + ); + } + } + + #[test] + fn scoped_shadow_sees_a_loop_binding_with_newline_before_in() { + assert!(test_body_scoped_shadow_at_line( + "for owner\nin items { owner(1); }", + "owner" + )); + } + + #[test] + fn scoped_shadow_sees_a_parameter_after_nested_parentheses() { + assert!(test_body_scoped_shadow_at_line( + "fn helper(pair: (u8, u8), owner: fn(i32, i32) -> i32) { owner(1, 2); }", + "owner" + )); + } + + #[test] + fn scoped_shadow_sees_a_flat_tuple_pattern_binding() { + assert!(test_body_scoped_shadow_at_line( + "match pair { (owner, _) => owner(100, 100), _ => 0 }", + "owner" + )); + } + + #[test] + fn scoped_shadow_sees_a_nested_tuple_pattern_binding() { + assert!(test_body_scoped_shadow_at_line( + "match pair { Some((owner, _)) => owner(100, 100), _ => 0 }", + "owner" + )); + } + + #[test] + fn scoped_shadow_sees_a_slice_pattern_binding() { + assert!(test_body_scoped_shadow_at_line( + "match pair { [owner, _] => owner(100, 100), _ => 0 }", + "owner" + )); + } + + #[test] + fn scoped_shadow_sees_a_binding_in_a_later_loop() { + assert!(test_body_scoped_shadow_at_line( + "for item in first { consume(item); } for owner in callbacks { owner(100, 100); }", + "owner" + )); + } } diff --git a/crates/ripr/src/analysis/facts/model.rs b/crates/ripr/src/analysis/facts/model.rs index 7cbf814ab1b..2cc06f4dbf6 100644 --- a/crates/ripr/src/analysis/facts/model.rs +++ b/crates/ripr/src/analysis/facts/model.rs @@ -1081,10 +1081,17 @@ impl FunctionSourceRole { /// columns: a binding defeats uses at and after its own body-relative line. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct LetBindingFact { - /// 0-based line of the `let` token relative to the enclosing function's + /// 0-based line of the binding token relative to the enclosing function's /// body start (the same body-relative line math the lexical shadow /// scanners use). pub line: usize, + /// Last body-relative line where the binding is in scope (inclusive). + /// `None` for a `let` binding, which keeps the shipped end-of-function + /// over-approximation; `Some(end)` for a closure, `for`, match-arm, + /// `if let`/`while let` or nested-fn parameter, whose scope ends at its + /// body or arm (#14508 review). + #[serde(default)] + pub scope_end: Option, /// One whole-word identifier from the binding's pattern (`x` for /// `let mut x = ..`, `a` and `b` for `let (a, b) = ..`). Extracted with /// the lexical authority's whole-word semantics so the fact-derived and diff --git a/crates/ripr/src/analysis/syntax/ra.rs b/crates/ripr/src/analysis/syntax/ra.rs index 34ad70b2f9d..102edcd605c 100644 --- a/crates/ripr/src/analysis/syntax/ra.rs +++ b/crates/ripr/src/analysis/syntax/ra.rs @@ -3,7 +3,7 @@ use crate::domain::{OracleKind, OracleStrength, SymbolId}; use ra_ap_syntax::Edition; use ra_ap_syntax::{ AstNode, SourceFile, SyntaxKind, SyntaxNode, TextSize, - ast::{self, HasAttrs, HasGenericArgs, HasGenericParams, HasModuleItem, HasName}, + ast::{self, HasAttrs, HasGenericArgs, HasGenericParams, HasLoopBody, HasModuleItem, HasName}, }; mod closure_callbacks; #[cfg(test)] @@ -1144,18 +1144,26 @@ fn simple_cfg_guard(attributes: &[String]) -> Option<(String, bool)> { /// Collects the parser-backed test-body shadow facts for one function /// (#3727 Slice A): the names of `fn` items nested inside the function's -/// body, and one [`LetBindingFact`] per whole-word name in every -/// initialized `let` binding's pattern, line-relative to the function's -/// `fn` keyword line. +/// body, and one [`LetBindingFact`] per whole-word name in a `let` pattern, +/// a nested `fn` name, and each closure, `for`, match-arm, +/// `if let`/`while let` or nested-`fn` parameter, line-relative to the +/// function's `fn` keyword line. /// -/// The semantics are deliberately scanner-equivalent at line granularity -/// (see `analysis::extract::shadow`): a nested `fn ` item is -/// hoisted and defeats the whole body, and a binding defeats uses at and -/// after its own body-relative line. No scope extents, no columns. The -/// pattern names are extracted with the shared lexical authority's -/// whole-word vocabulary (`extract_pattern_words`), so the fact-derived -/// decisions equal the lexical scanners' decisions on the same masked body -/// for realistic Rust — the equivalence battery in this module pins it. +/// A nested `fn ` item is hoisted and defeats the whole body. A +/// `let` binding carries `scope_end: None` and keeps the shipped +/// end-of-function over-approximation. A closure, `for`, match-arm, +/// `if let`/`while let` or nested-`fn` parameter carries `scope_end` with +/// the inclusive end line of its body or arm, so it defeats only uses inside +/// that scope. The pattern names are extracted with the shared lexical +/// authority's whole-word vocabulary (`extract_pattern_words`). +/// +/// The lexical fallback in `analysis::extract::shadow` deliberately diverges +/// for the scoped forms: it withholds the whole body rather than computing +/// the exact extent, which is fail-closed (it may drop credit for a genuine +/// call after the scope on a file the parser could not read, and never +/// grants credit to a scoped binding). The equivalence battery in this +/// module pins only the shared families (`let` bindings and nested `fn` +/// names), not the scoped forms. /// /// `line_of` maps a tree offset to a 1-based line, and `fn_line` is the /// 1-based line of the function's `fn` keyword — the two inputs that make @@ -1206,6 +1214,7 @@ fn collect_body_shadow_facts( for name in extract_pattern_words(&pattern.syntax().text().to_string()) { let_bindings.push(LetBindingFact { line: body_relative_line, + scope_end: None, name, }); } @@ -1268,16 +1277,223 @@ fn collect_body_shadow_facts( for name in extract_pattern_words(&pattern) { let_bindings.push(LetBindingFact { line: body_relative_line, + scope_end: None, name, }); } } } + // #14508 review: a closure, `for`, match-arm, `if let`/`while let` or + // nested-fn parameter binds the alias only inside its own body/arm. The + // fact carries that scope end so a genuine call after the scope keeps its + // credit. + for closure in function + .syntax() + .descendants() + .filter_map(ast::ClosureExpr::cast) + { + let Some(body) = closure.body() else { + continue; + }; + let scope_end = body.syntax().text_range().end(); + if let Some(params) = closure.param_list() { + for param in params.params() { + push_scoped_binding_facts( + &mut let_bindings, + param.pat(), + scope_end, + line_of, + fn_line, + ); + } + } + } + for for_expr in function + .syntax() + .descendants() + .filter_map(ast::ForExpr::cast) + { + let Some(body) = for_expr.loop_body() else { + continue; + }; + push_scoped_binding_facts( + &mut let_bindings, + for_expr.pat(), + body.syntax().text_range().end(), + line_of, + fn_line, + ); + } + for arm in function + .syntax() + .descendants() + .filter_map(ast::MatchArm::cast) + { + let Some(expr) = arm.expr() else { + continue; + }; + push_scoped_binding_facts( + &mut let_bindings, + arm.pat(), + expr.syntax().text_range().end(), + line_of, + fn_line, + ); + } + for if_expr in function + .syntax() + .descendants() + .filter_map(ast::IfExpr::cast) + { + let Some(condition) = if_expr.condition() else { + continue; + }; + let Some(then_branch) = if_expr.then_branch() else { + continue; + }; + // A let-chain condition (`if let Some(dt) = .. && cond`) is a + // BinExpr, so walk every LetExpr under it, not only a direct + // condition (#14508 review). + for let_expr in condition + .syntax() + .descendants() + .filter_map(ast::LetExpr::cast) + { + push_scoped_binding_facts( + &mut let_bindings, + let_expr.pat(), + then_branch.syntax().text_range().end(), + line_of, + fn_line, + ); + } + } + for while_expr in function + .syntax() + .descendants() + .filter_map(ast::WhileExpr::cast) + { + let Some(condition) = while_expr.condition() else { + continue; + }; + let Some(body) = while_expr.loop_body() else { + continue; + }; + for let_expr in condition + .syntax() + .descendants() + .filter_map(ast::LetExpr::cast) + { + push_scoped_binding_facts( + &mut let_bindings, + let_expr.pat(), + body.syntax().text_range().end(), + line_of, + fn_line, + ); + } + } + for nested_fn in function.syntax().descendants().filter_map(ast::Fn::cast) { + if nested_fn.syntax().text_range() == function.syntax().text_range() { + continue; + } + let Some(body) = nested_fn.body() else { + continue; + }; + if let Some(params) = nested_fn.param_list() { + for param in params.params() { + push_scoped_binding_facts( + &mut let_bindings, + param.pat(), + body.syntax().text_range().end(), + line_of, + fn_line, + ); + } + } + } + // The enclosing function's own parameters shadow the alias for its whole + // body; a `#[rstest]` fixture parameter named like the alias is the + // compiling case (#14508 review). + if let (Some(body), Some(params)) = (function.body(), function.param_list()) { + for param in params.params() { + push_scoped_binding_facts( + &mut let_bindings, + param.pat(), + body.syntax().text_range().end(), + line_of, + fn_line, + ); + } + } + // A closure inside a macro token tree is not a `ClosureExpr` node, so the + // AST walk above cannot see its parameters. Read each token tree's masked + // text for `|params|` pairs and bind each name for the rest of the tree + // (fail closed, #14508 review). + for tree in function + .syntax() + .descendants() + .filter(|node| node.kind() == SyntaxKind::TOKEN_TREE) + { + let text = crate::analysis::extract::mask_comments_and_strings(&tree.text().to_string()); + let last = TextSize::from(u32::from(tree.text_range().end()).saturating_sub(1)); + let (Some(line), Some(end_line)) = ( + line_of(tree.text_range().start()).checked_sub(fn_line), + line_of(last).checked_sub(fn_line), + ) else { + continue; + }; + let mut rest = text.as_str(); + while let Some(open) = rest.find('|') { + let after = &rest[open + 1..]; + let Some(close) = after.find('|') else { break }; + for segment in after[..close].split(',') { + let name_part = segment.split(':').next().unwrap_or(segment); + for name in extract_pattern_words(name_part) { + let_bindings.push(LetBindingFact { + line, + scope_end: Some(end_line), + name, + }); + } + } + rest = &after[close + 1..]; + } + } let_bindings.sort_by(|left, right| left.line.cmp(&right.line).then(left.name.cmp(&right.name))); let_bindings.dedup(); (nested_fn_names, let_bindings) } +/// Record one scoped binding fact per whole-word name in `pattern`, with the +/// binding's body-relative start line and the inclusive end line of the +/// body/arm that scopes it (#14508 review). +fn push_scoped_binding_facts( + let_bindings: &mut Vec, + pattern: Option, + scope_end: TextSize, + line_of: &impl Fn(TextSize) -> usize, + fn_line: usize, +) { + let Some(pattern) = pattern else { + return; + }; + let Some(start) = line_of(pattern.syntax().text_range().start()).checked_sub(fn_line) else { + return; + }; + let last = TextSize::from(u32::from(scope_end).saturating_sub(1)); + let Some(end) = line_of(last).checked_sub(fn_line) else { + return; + }; + for name in extract_pattern_words(&pattern.syntax().text().to_string()) { + let_bindings.push(LetBindingFact { + line: start, + scope_end: Some(end), + name, + }); + } +} + /// Parser-backed shadow facts (#3727 Slice A) for a bare body text that is /// not necessarily a `fn` item — harness-subject invocation spans and /// merged evidence bodies. The text is wrapped in a synthetic `fn` item @@ -5450,11 +5666,16 @@ mod nested { include!("nested.rs"); } #[cfg(test)] mod shadow_fact_equivalence_tests { - //! #3727 Slice A: the parser-produced body facts must decide the shared - //! shadow authority EXACTLY like the lexical scanners decide the same - //! masked body, so switching consumers between the two authorities - //! cannot move a verdict. The battery pins scanner equivalence over the - //! #3722/#3728 pin families plus the positional and same-line rules. + //! #3727 Slice A: the parser-produced body facts and the lexical + //! scanners must agree on the shared families — `let` bindings and + //! nested `fn` names — so switching consumers between the two + //! authorities cannot move a verdict for those forms. The battery pins + //! that shared-family equivalence over the #3722/#3728 pin families plus + //! the positional and same-line rules. It does not cover the scoped + //! forms (closure, `for`, match-arm, `if let`/`while let` and nested-`fn` + //! parameters): the parser carries their `scope_end` and credits a + //! genuine call after the scope, while the lexical fallback withholds the + //! whole body by design (see `analysis::extract::shadow`). use super::*; use crate::analysis::extract::{ diff --git a/crates/ripr/src/analysis/test_grip_evidence.rs b/crates/ripr/src/analysis/test_grip_evidence.rs index 9fe41972dda..69be69adc14 100644 --- a/crates/ripr/src/analysis/test_grip_evidence.rs +++ b/crates/ripr/src/analysis/test_grip_evidence.rs @@ -48,7 +48,7 @@ use related_tests::{ use super::classify::{ assertion_observes_collection_argument, assertion_observes_direct_collection_for_probe, assertion_pins_pushed_collection_count, call_text_may_call_free_function, - direct_collection_mutation_receiver, is_ignored, owner_call_text, + direct_collection_mutation_receiver, free_function_call_text, is_ignored, owner_call_text, predicate_line_arms_all_agree, reach_evidence as classify_reach_evidence, related_tests_reach_owner_indirectly, relation_establishes_reach, test_calls_free_function, test_count_pins_pushed_collection, test_counts_pushed_collection_argument, @@ -3486,12 +3486,30 @@ fn observed_value_facts_for_test( let value_facts = indexed.value_facts(index); let env = super::value_resolution::ValueEnv::new(seam, value_facts); for call in indexed.test.body_calls() { - if call.name != owner_name { + let is_alias = call.name != owner_name; + // The alias names a free function. An associated owner resolves its + // own calls through its type; a free alias of the same name must not + // lend it arguments (#14508 review). + if is_alias && owner_fn.impl_context != FunctionImplContext::Free { continue; } - let Some(args) = - owner_call_text(&call.text, owner_fn).and_then(|text| call_arguments(text, owner_name)) - else { + if is_alias && !context.is_direct_owner_alias(indexed, owner_name, &owner_fn.file, call) { + continue; + } + let call_name = if is_alias { + call.name.as_str() + } else { + owner_name + }; + let Some(args) = (if is_alias { + // The alias names a free function, so only a free-call spelling + // reaches it; `Rival::dt(..)` calls an associated function on + // another type and must not lend its arguments (#14508 review). + free_function_call_text(&call.text, call_name) + .and_then(|text| call_arguments(text, call_name)) + } else { + owner_call_text(&call.text, owner_fn).and_then(|text| call_arguments(text, call_name)) + }) else { continue; }; for (arg_index, arg) in args.into_iter().enumerate() { @@ -4045,12 +4063,30 @@ fn boundary_equality_overlap_score( let mut score = 0; for call in indexed.test.body_calls() { - if call.name != owner_fn.name { + let is_alias = call.name != owner_fn.name; + // The alias names a free function; an associated owner's boundary + // can only be closed by its own calls (#14508 review). + if is_alias && owner_fn.impl_context != FunctionImplContext::Free { continue; } - let Some(args) = owner_call_text(&call.text, owner_fn) - .and_then(|text| call_arguments(text, &owner_fn.name)) - else { + if is_alias && !context.is_direct_owner_alias(indexed, &owner_fn.name, &owner_fn.file, call) + { + continue; + } + let call_name = if is_alias { + call.name.as_str() + } else { + owner_fn.name.as_str() + }; + let Some(args) = (if is_alias { + // Same free-call authority as the observed-value loop: a + // qualified `Rival::dt(..)` is not the aliased free function + // (#14508 review). + free_function_call_text(&call.text, call_name) + .and_then(|text| call_arguments(text, call_name)) + } else { + owner_call_text(&call.text, owner_fn).and_then(|text| call_arguments(text, call_name)) + }) else { continue; }; let Some(left_arg) = args.get(left_operand.index) else { diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index 14055e1dd72..a1ca878f7ce 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -4,7 +4,7 @@ use crate::analysis::classify::{ 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; +use crate::analysis::facts::{FunctionImplContext, ModulePathTarget}; use std::sync::Arc; pub(super) mod context; @@ -181,6 +181,9 @@ pub(super) struct OwnerContext<'index> { 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>, @@ -230,6 +233,7 @@ impl<'index> OwnerContext<'index> { 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, @@ -355,58 +359,406 @@ pub(super) fn match_direct_owner_call( if owner.name.is_empty() { return; } - let Some(indices) = context.tests_by_call_name.get(&owner.name) else { - return; - }; - 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) + 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; } - } 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; + insert_related_candidate( + candidates, + context, + prefix, + *test_index, + RelationReason::DirectOwnerCall, + ); } - // `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; + } + // #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, + ); } - // #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; + } +} + +#[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(); } - insert_related_candidate( - candidates, - context, - prefix, - *test_index, - RelationReason::DirectOwnerCall, - ); } + 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( diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs index 6d5f306d50f..e9e255e1bd7 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs @@ -12,6 +12,18 @@ pub(crate) struct CompactGripContext<'a> { pub(in crate::analysis::test_grip_evidence) index: &'a RustIndex, pub(in crate::analysis::test_grip_evidence) tests: Vec>, pub(in crate::analysis::test_grip_evidence) tests_by_call_name: BTreeMap>, + /// Tests whose call is spelled through a direct import alias of a + /// production function: imported name -> the test, the import's module + /// path (slash-separated), whether that path is `crate::`-relative, the + /// alias spelling and the call line. A relative path resolves against + /// the test's own crate; a package-qualified one names the owner's + /// package (#14508). + pub(in crate::analysis::test_grip_evidence) tests_by_direct_owner_alias: + BTreeMap>, + /// Per test file: start lines of every indexed non-test function, keyed by + /// name, so the alias shadow guard can tell a same-module declaration + /// from a sibling module's (#14508 review). + local_function_starts_by_file: BTreeMap>>, pub(in crate::analysis::test_grip_evidence) tests_by_helper_owner_call_name: BTreeMap>, /// Tests whose helper chain reaches the owner name through a @@ -110,6 +122,22 @@ pub(crate) struct CompactGripContext<'a> { pin_syntax: crate::analysis::classify::OwnerPinSyntax, } +/// One alias-spelled call of a directly imported owner (#14508). +#[derive(Clone, Debug, Eq, PartialEq)] +pub(in crate::analysis::test_grip_evidence) struct DirectOwnerAliasEntry { + pub(in crate::analysis::test_grip_evidence) test_index: usize, + /// Slash-separated module segments of the import. + pub(in crate::analysis::test_grip_evidence) module_path: String, + /// The import was written `crate::`-relative. + pub(in crate::analysis::test_grip_evidence) crate_relative: bool, + pub(in crate::analysis::test_grip_evidence) alias: String, + pub(in crate::analysis::test_grip_evidence) call_line: usize, + /// Number of enclosing `mod` scopes at the import, so the local-function + /// shadow guard can tell an enclosing declaration from a nearer one + /// (#14508 review). + pub(in crate::analysis::test_grip_evidence) module_depth: usize, +} + /// Candidate generation only: the existing `contains` and `same_module` /// predicates remain the authority for admitting relations. #[derive(Default)] @@ -283,6 +311,228 @@ impl<'a> CompactGripContext<'a> { &self.pin_syntax } + /// Whether `test` reaches `owner_name` through the alias spelling + /// `call.name` at `call.line` (#14508). The table lookup is + /// allocation-free; on a lexical-fallback file the binding check masks + /// the body per alias call, so this is not a constant-time query there. + /// + /// The table stores one row per resolved call line, so the row's own + /// identity is the authority: the row must name this exact call line and + /// its import module must name the owner's module. A nested + /// `use rival::different_function as dt` binds a later `dt(..)` to another + /// function, and a same-named import of another module must not borrow an + /// outer owner row's credit (#14508 review). + pub(in crate::analysis::test_grip_evidence) fn is_direct_owner_alias( + &self, + test: &CompactTest<'_>, + owner_name: &str, + owner_file: &Path, + call: &CallFact, + ) -> bool { + let Some(entries) = self.tests_by_direct_owner_alias.get(owner_name) else { + return false; + }; + // An imported alias is a local name, so only a bare `alias(..)` + // spelling binds to it. A same-line `rival::alias(..)` names that + // module's function and must not borrow the row (#14508 review). + if !crate::analysis::classify::call_text_spells_bare_free_call(&call.text, &call.name) { + return false; + } + // The shadow guards are expensive and only decide a call that is + // already spelled like one of this owner's aliases at this line, so + // find the matching entry first and run them once for that call + // (#14508 review). + let Some(matched) = entries.iter().find(|entry| { + entry.alias == call.name + && entry.call_line == call.line + && self + .tests + .get(entry.test_index) + .is_some_and(|indexed| std::ptr::eq(indexed.test, test.test)) + }) else { + return false; + }; + if self.alias_binding_shadows_call(test, &call.name, call.line) + || self.local_function_shadows_call(test, &call.name, matched.module_depth) + { + return false; + } + let owner_module = super::module_path_for_index(self.index, owner_file); + let owner_module = owner_module.as_deref().unwrap_or(""); + let file_stem = module_stem(owner_file).unwrap_or_default(); + let owner_crate_root = if file_stem.is_empty() { + crate_root_file_key(owner_file) + } else { + None + }; + let owner_is_crate_root = owner_crate_root.is_some(); + let owner_prefix = super::package_prefix(owner_file); + entries.iter().any(|entry| { + entry.alias == call.name + && entry.call_line == call.line + && self + .tests + .get(entry.test_index) + .is_some_and(|indexed| std::ptr::eq(indexed.test, test.test)) + && !self.local_module_shadows_alias(test, &entry.module_path, owner_name) + && super::direct_owner_alias_module_matches( + &entry.module_path, + entry.crate_relative, + owner_module, + owner_is_crate_root, + owner_crate_root.as_deref(), + test.test.file.as_path(), + Some(owner_file), + owner_prefix.as_deref(), + self.index, + ) + }) + } + + /// Whether a `let`, nested `fn` name, closure parameter, `for`/match-arm/ + /// `if let`/`while let` pattern, or nested-fn parameter named `call_name` + /// encloses the call at `call_line`, so the alias-spelled call binds to + /// that local value rather than to the imported owner (#14508 review). A + /// `let` keeps the end-of-function over-approximation; the other forms are + /// bounded by their body or arm. + pub(in crate::analysis::test_grip_evidence) fn alias_binding_shadows_call( + &self, + test: &CompactTest<'_>, + call_name: &str, + call_line: usize, + ) -> bool { + let body_line = call_line.saturating_sub(test.test.start_line); + let lexical = self + .index + .files() + .get(&test.test.file) + .is_some_and(|facts| facts.used_lexical_fallback); + if lexical { + let masked = crate::analysis::extract::mask_comments_and_strings(&test.test.body); + crate::analysis::extract::ShadowAuthority::LexicalMaskedBody + .body_shadows_callee_at_line(&masked, call_name, body_line) + } else { + crate::analysis::extract::ShadowAuthority::ParserBodyFacts { + nested_fn_names: &test.test.nested_fn_names, + let_bindings: &test.test.let_bindings, + } + .body_shadows_callee_at_line("", call_name, body_line) + } + } + + /// Whether `test`'s own module or a nearer module than the import + /// declares a non-test function named `call_name`, so an alias-spelled + /// call in that scope binds to the local function rather than to the + /// directly imported owner (#14508 review). A declaration in an enclosing + /// module than the import is shadowed by the import, and a sibling inline + /// module's same-named function is a different name scope. + pub(in crate::analysis::test_grip_evidence) fn local_function_shadows_call( + &self, + test: &CompactTest<'_>, + call_name: &str, + use_module_depth: usize, + ) -> bool { + let Some(starts) = self.local_function_starts_by_file.get(&test.test.file) else { + return false; + }; + let Some(lines) = starts.get(call_name) else { + return false; + }; + let Some(facts) = self.index.files().get(&test.test.file) else { + // Without the source the module scopes cannot be read; fall back + // to the file-wide answer (fail closed toward withholding). + return true; + }; + let scopes = crate::analysis::classify::module_scopes(&facts.source); + lines.iter().any(|line| { + scopes.declaration_shadows_import(*line, use_module_depth, test.test.start_line) + }) + } + + /// Whether the test file declares an inline module chain that matches the + /// alias's module path and defines the imported name, so the `crate::` + /// path names that local module rather than the owner file (#14508 + /// review). A binary target's inline `mod pricing { fn owner }` is a + /// different compilation unit from the library's `src/pricing.rs`, and + /// the import binds to the local module. + pub(in crate::analysis::test_grip_evidence) fn local_module_shadows_alias( + &self, + test: &CompactTest<'_>, + alias_module: &str, + imported_name: &str, + ) -> bool { + let Some(starts) = self.local_function_starts_by_file.get(&test.test.file) else { + return false; + }; + let Some(lines) = starts.get(imported_name) else { + return false; + }; + let Some(facts) = self.index.files().get(&test.test.file) else { + return false; + }; + // The alias path is absolute from the crate root, so the local + // module's absolute path is the test file's own module path plus the + // inline chain. + let file_module = super::test_file_module_path(self.index, &test.test.file); + let mut wanted: Vec<&str> = file_module + .split('/') + .filter(|segment| !segment.is_empty()) + .collect(); + wanted.extend( + alias_module + .split('/') + .filter(|segment| !segment.is_empty()), + ); + if wanted.is_empty() { + return false; + } + let scopes = crate::analysis::classify::module_scopes(&facts.source); + lines.iter().any(|line| { + scopes + .module_chain_at(*line) + .is_some_and(|chain| chain == wanted) + }) + } + + /// Whether every call of `call_name` in `test` is bound to a direct-owner + /// import alias of a *different* function, so a same-named local function + /// is not the callee (#14508 review). A test that also spells a genuine + /// local call of the name keeps the generic direct-call credit. + pub(in crate::analysis::test_grip_evidence) fn alias_spelling_binds_other_owner( + &self, + test: &TestSummary, + call_name: &str, + owner_name: &str, + ) -> bool { + let mut alias_lines = BTreeSet::new(); + for (imported_name, entries) in &self.tests_by_direct_owner_alias { + if imported_name == owner_name { + continue; + } + for entry in entries { + if entry.alias == call_name + && self + .tests + .get(entry.test_index) + .is_some_and(|indexed| std::ptr::eq(indexed.test, test)) + { + alias_lines.insert(entry.call_line); + } + } + } + if alias_lines.is_empty() { + return false; + } + let mut saw_call = false; + for call in test.calls.iter().filter(|call| call.name == call_name) { + saw_call = true; + if !alias_lines.contains(&call.line) { + return false; + } + } + saw_call + } + /// Pay the whole-index macro-site scan once, before the seam workers /// start, so it fans out over the pool instead of running in line on /// the first worker that needs it while the others wait (#9211). @@ -325,6 +575,8 @@ impl<'a> CompactGripContext<'a> { ) -> Result { checkpoint()?; let mut tests_by_call_name: BTreeMap> = BTreeMap::new(); + let mut tests_by_direct_owner_alias: BTreeMap> = + BTreeMap::new(); let mut tests_by_helper_owner_call_name: BTreeMap> = BTreeMap::new(); let mut tests_by_free_helper_owner_call_name: BTreeMap> = BTreeMap::new(); @@ -378,6 +630,10 @@ impl<'a> CompactGripContext<'a> { context_build_phase("direct_helper_import_aliases_by_file", || { direct_helper_import_aliases_by_file(index, &helper_owner_calls_by_module_path) }); + let direct_owner_import_aliases_by_file = + context_build_phase("direct_owner_import_aliases_by_file", || { + direct_owner_import_aliases_by_file(index) + }); checkpoint()?; let production_helper_owner_calls_by_package = context_build_phase("production_helper_owner_calls_by_package", || { @@ -403,6 +659,7 @@ impl<'a> CompactGripContext<'a> { checkpoint()?; let SharedIndexTables { function_names_by_file, + local_function_starts_by_file, module_import_aliases_by_file, unambiguous_production_owner_names_by_package, .. @@ -463,6 +720,35 @@ impl<'a> CompactGripContext<'a> { .iter() .map(|call| call.name.clone()) .collect::>(); + if let Some(owner_aliases) = direct_owner_import_aliases_by_file.get(&test.file) { + for call in &test.calls { + // The alias names a free function and only the bare + // `alias(..)` spelling binds to the import. A qualified + // `rival::dt(..)` names that module's function even + // when the module name is lowercase (#14508 review). + if !crate::analysis::classify::call_text_spells_bare_free_call( + &call.text, &call.name, + ) { + continue; + } + if let Some(binding) = owner_aliases + .get(&call.name) + .and_then(|alias| alias.binding_at(call.line)) + { + tests_by_direct_owner_alias + .entry(binding.name.clone()) + .or_default() + .push(DirectOwnerAliasEntry { + test_index, + module_path: binding.module_path.clone(), + crate_relative: binding.crate_relative, + alias: call.name.clone(), + call_line: call.line, + module_depth: binding.module_depth, + }); + } + } + } let mut assertion_tokens = BTreeSet::new(); for assertion in &test.assertions { for token in extract_identifier_tokens(&assertion.text) { @@ -639,6 +925,8 @@ impl<'a> CompactGripContext<'a> { index, tests, tests_by_call_name, + tests_by_direct_owner_alias, + local_function_starts_by_file, tests_by_helper_owner_call_name, tests_by_free_helper_owner_call_name, tests_by_target_affinity_owner_call_name, @@ -1404,10 +1692,17 @@ impl ScopedModuleImportAlias { #[derive(Clone, Debug, Eq, PartialEq)] pub(in crate::analysis::test_grip_evidence) struct ScopedImportedFunctionBinding { + /// Slash-separated module segments (`pricing/inner`), never `::`. pub(in crate::analysis::test_grip_evidence) module_path: String, + /// The import was written `crate::`-relative, so it resolves against the + /// crate that compiles the test file, not the owner's package (#14508 + /// review). + pub(in crate::analysis::test_grip_evidence) crate_relative: bool, pub(in crate::analysis::test_grip_evidence) name: String, start_line: usize, end_line: usize, + /// Number of enclosing `mod` scopes at the import (#14508 review). + module_depth: usize, /// Lines inside nested module bodies are not covered by this import. nested_module_lines: Vec<(usize, usize)>, /// The owning scope closes part-way through `end_line`, with code after @@ -1595,6 +1890,7 @@ pub(in crate::analysis::test_grip_evidence) fn free_spelling_target_affinity_own /// four rescans of every source's `use` statements per context. pub(in crate::analysis::test_grip_evidence) struct SharedIndexTables { function_names_by_file: BTreeMap>, + local_function_starts_by_file: BTreeMap>>, module_import_aliases_by_file: ModuleImportAliasesByFile, direct_function_import_aliases_by_file: ScopedDirectFunctionImportAliasesByFile, unambiguous_production_owner_names_by_package: ProductionOwnerNamesByPackage, @@ -1616,6 +1912,7 @@ impl SharedIndexTables { || { ( local_function_names_by_file(index), + local_function_starts_by_file(index), unambiguous_production_owner_names_by_package(index), production_owner_names_by_module_path(index), production_owner_names_by_package_and_module_path(index), @@ -1625,6 +1922,7 @@ impl SharedIndexTables { ); let ( function_names_by_file, + local_function_starts_by_file, unambiguous_production_owner_names_by_package, owner_names_by_module_path, owner_names_by_package_and_module_path, @@ -1632,6 +1930,7 @@ impl SharedIndexTables { ) = rest; Self { function_names_by_file, + local_function_starts_by_file, module_import_aliases_by_file, direct_function_import_aliases_by_file, unambiguous_production_owner_names_by_package, @@ -2738,9 +3037,11 @@ pub(in crate::analysis::test_grip_evidence) fn direct_function_import_aliases( .bindings .push(ScopedImportedFunctionBinding { module_path: imported.module_path, + crate_relative: true, name: imported.name, start_line: statement.start_line, end_line, + module_depth: statement.module_depth, nested_module_lines: nested_module_lines.clone(), end_is_partial: scan.end_is_partial(end_line), }); @@ -2935,6 +3236,212 @@ pub(in crate::analysis::test_grip_evidence) fn normalize_module_import_path( Some(path.to_string()) } +/// Normalize the module path of a direct function import for the owner-alias +/// table (#14508). Unlike [`normalize_module_import_path`], this accepts an +/// external package path (`subject::pricing`) as well as a crate-relative one +/// (`crate::pricing`), because an integration test imports the library by its +/// package name. `crate` alone is the crate root (empty path). +/// +/// Segments are normalized to `/` on both sides of the comparison: the +/// owner's module path comes from `module_path_for_index`, which joins with +/// `/`, while the import is written with `::`. Without one representation a +/// nested owner (`pricing/inner`) never matched its `crate::pricing::inner` +/// import (#14508 review). +fn normalize_direct_owner_module_path(path: &str) -> Option { + let path = path.trim(); + if path == "crate" { + return Some(OwnerModulePath { + module_path: String::new(), + crate_relative: true, + }); + } + if let Some(rest) = path.strip_prefix("crate::") { + let rest = rest.trim(); + return (!rest.is_empty()).then(|| OwnerModulePath { + module_path: rest.replace("::", "/"), + crate_relative: true, + }); + } + if path.is_empty() + || path.starts_with("self::") + || path.starts_with("super::") + || path.starts_with("::") + { + return None; + } + Some(OwnerModulePath { + module_path: path.replace("::", "/"), + crate_relative: false, + }) +} + +/// A direct-owner import's module path, normalized to `/` segments, plus +/// whether it was written `crate::`-relative (#14508 review). +#[derive(Clone, Debug, Eq, PartialEq)] +struct OwnerModulePath { + module_path: String, + crate_relative: bool, +} + +/// An imported owner function alias before it is scoped to a call line. +#[derive(Clone, Debug, Eq, PartialEq)] +struct OwnerImportedFunctionAlias { + module_path: String, + crate_relative: bool, + name: String, +} + +fn collect_direct_owner_import_aliases_from_use( + import: &str, +) -> Option> { + let import = import.trim_end_matches(';').trim(); + let mut aliases = BTreeMap::new(); + if let Some((base, rest)) = import.split_once("::{") { + let module = normalize_direct_owner_module_path(base)?; + let body = rest.strip_suffix('}')?; + for item in body.split(',').map(str::trim) { + if item.contains("::") || item.contains('{') || item.contains('}') { + continue; + } + collect_owner_function_alias(item, &module, &mut aliases); + } + return Some(aliases); + } + let (module_path, item) = import.rsplit_once("::")?; + let module = normalize_direct_owner_module_path(module_path)?; + collect_owner_function_alias(item.trim(), &module, &mut aliases); + Some(aliases) +} + +fn collect_owner_function_alias( + item: &str, + module: &OwnerModulePath, + aliases: &mut BTreeMap, +) { + let mut parsed = BTreeMap::new(); + collect_direct_function_import_alias(item, &module.module_path, &mut parsed); + for (alias, imported) in parsed { + aliases.insert( + alias, + OwnerImportedFunctionAlias { + module_path: imported.module_path, + crate_relative: module.crate_relative, + name: imported.name, + }, + ); + } +} + +/// Scoped direct-import aliases for the owner-call relation (#14508). This is +/// the same shape as [`direct_function_import_aliases`] but accepts external +/// package paths, so `use subject::owner as alias;` resolves as well as +/// `use crate::owner as alias;`. +pub(in crate::analysis::test_grip_evidence) fn direct_owner_import_aliases( + source: &str, +) -> BTreeMap { + let scan = scan_lexical_use_statements(source); + let mut aliases: BTreeMap = BTreeMap::new(); + for statement in &scan.statements { + let end_line = scan.end_line(statement); + let mut nested_module_lines = nested_module_line_ranges( + &scan.line_module_depths, + statement.start_line, + end_line, + statement.module_depth, + ); + for line in &scan.module_open_lines { + if statement.start_line <= *line && *line <= end_line { + nested_module_lines.push((*line, *line)); + } + } + let Some(parsed) = collect_direct_owner_import_aliases_from_use(&statement.text) else { + // A nearer import that binds the same spelling but names an + // unsupported module path (`self::`, `super::`, `::`) still + // shadows an outer owner alias. Record a binding that can never + // match an owner module, so the call fails closed (#14508 review). + for alias in use_statement_alias_names(&statement.text) { + aliases + .entry(alias) + .or_insert_with(|| ScopedImportedFunctionAlias { + bindings: Vec::new(), + }) + .bindings + .push(ScopedImportedFunctionBinding { + module_path: String::new(), + crate_relative: false, + name: String::new(), + start_line: statement.start_line, + end_line, + module_depth: statement.module_depth, + nested_module_lines: nested_module_lines.clone(), + end_is_partial: scan.end_is_partial(end_line), + }); + } + continue; + }; + if parsed.is_empty() { + continue; + } + for (alias, imported) in parsed { + aliases + .entry(alias) + .or_insert_with(|| ScopedImportedFunctionAlias { + bindings: Vec::new(), + }) + .bindings + .push(ScopedImportedFunctionBinding { + module_path: imported.module_path, + crate_relative: imported.crate_relative, + name: imported.name, + start_line: statement.start_line, + end_line, + module_depth: statement.module_depth, + nested_module_lines: nested_module_lines.clone(), + end_is_partial: scan.end_is_partial(end_line), + }); + } + } + aliases +} + +/// The `as` aliases a `use` statement binds, even when its module path is not +/// a supported owner path. A nearer unsupported import still shadows an outer +/// owner alias (#14508 review). A non-aliased import binds the imported name +/// itself, which the bare-call reading already handles. +fn use_statement_alias_names(import: &str) -> Vec { + let import = import.trim_end_matches(';').trim(); + let items: Vec<&str> = match import.split_once("::{") { + Some((_, rest)) => rest + .strip_suffix('}') + .map(|body| body.split(',').map(str::trim).collect()) + .unwrap_or_default(), + None => import + .rsplit_once("::") + .map(|(_, item)| vec![item.trim()]) + .unwrap_or_default(), + }; + items + .into_iter() + .filter(|item| !item.contains("::") && !item.contains('{') && !item.contains('}')) + .filter_map(|item| item.split_once(" as ").map(|(_, alias)| alias.trim())) + .filter(|alias| !alias.is_empty()) + .map(str::to_string) + .collect() +} + +pub(in crate::analysis::test_grip_evidence) fn direct_owner_import_aliases_by_file( + index: &RustIndex, +) -> ScopedDirectFunctionImportAliasesByFile { + index + .files() + .iter() + .filter_map(|(file, facts)| { + let aliases = direct_owner_import_aliases(&facts.source); + (!aliases.is_empty()).then_some((file.clone(), aliases)) + }) + .collect() +} + pub(in crate::analysis::test_grip_evidence) fn unambiguous_production_owner_names_by_package( index: &RustIndex, ) -> ProductionOwnerNamesByPackage { @@ -2986,6 +3493,32 @@ pub(in crate::analysis::test_grip_evidence) fn local_function_names_by_file( names_by_file } +/// Per test file: the start lines of every indexed non-test function, keyed +/// by name. The alias shadow guard needs the declaration's line to tell a +/// same-module (or enclosing-module) function from a sibling module's +/// same-named one (#14508 review). +pub(in crate::analysis::test_grip_evidence) fn local_function_starts_by_file( + index: &RustIndex, +) -> BTreeMap>> { + let mut starts_by_file: BTreeMap>> = BTreeMap::new(); + let actual_tests = actual_test_keys(index); + for function in index.functions().iter().filter(|function| { + !actual_tests.contains(&ActualTestKey { + file: &function.file, + name: &function.name, + start_line: function.start_line, + }) + }) { + starts_by_file + .entry(function.file.clone()) + .or_default() + .entry(function.name.clone()) + .or_default() + .push(function.start_line); + } + starts_by_file +} + /// Borrowed (file, name, start_line) identity of a function that is an /// actual executable test (`TestFact` member), so graph-admission lookups /// need no per-function key clones. #3273 widened the function diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 4242495dde0..b52cc7675df 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -23084,6 +23084,1310 @@ fn given_integration_test_when_bare_import_names_other_module_then_owner_keeps_r Ok(()) } +#[test] +fn given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508: both the crate-relative and the external package spelling of a + // direct import alias must resolve to the owner. The external case needs a + // real manifest so the owner's own package is the only import name that + // counts (#14508 review). + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let crate_src = format!( + "{prod_src}\n#[cfg(test)]\nmod tests {{\n use crate::discounted_total as dt;\n\n #[test]\n fn aliased() {{\n assert_eq!(dt(100, 100), 90);\n }}\n}}\n" + ); + let crate_root = alias_workspace_root("lib_proptest")?; + fs::write(crate_root.join("src/lib.rs"), crate_src).map_err(|error| error.to_string())?; + let crate_files = [PathBuf::from("src/lib.rs")]; + let crate_index = build_index(&crate_root, &crate_files)?; + let crate_seams = inventory_seams_from_index(&crate_files, &crate_index); + let crate_seam = crate_seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let crate_related: Vec = evidence_for_seam(crate_seam, &crate_index) + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert_eq!( + crate_related, + vec!["aliased".to_string()], + "use crate::discounted_total as dt;" + ); + + let external_root = alias_workspace_root("lib_proptest")?; + fs::write(external_root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write( + external_root.join("tests/boundary.rs"), + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn aliased() {\n assert_eq!(dt(100, 100), 90);\n}\n", + ) + .map_err(|error| error.to_string())?; + let external_files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let external_index = build_index(&external_root, &external_files)?; + let external_seams = + inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &external_index); + let external_seam = external_seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let external_related: Vec = evidence_for_seam(external_seam, &external_index) + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert_eq!( + external_related, + vec!["aliased".to_string()], + "use lib_proptest::discounted_total as dt;" + ); + Ok(()) +} + +fn alias_workspace_root(package: &str) -> Result { + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_nanos(); + let root = claim_index_fixture_root(stamp)?; + fs::create_dir_all(root.join("src")).map_err(|error| error.to_string())?; + fs::create_dir_all(root.join("tests")).map_err(|error| error.to_string())?; + fs::write( + root.join("Cargo.toml"), + format!("[package]\nname = \"{package}\"\nversion = \"0.1.0\"\n"), + ) + .map_err(|error| error.to_string())?; + Ok(root) +} + +#[test] +fn given_direct_owner_alias_when_a_local_function_shadows_it_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: the test file declares its own `dt`, so the alias-spelled + // call binds to this local function; the owner must not be credited. + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn shadowed() {\n fn dt(_amount: i32, _threshold: i32) -> i32 { 777 }\n assert_eq!(dt(100, 100), 777);\n}\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + let related: Vec = evidence + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert!( + related.is_empty(), + "a local function shadowing the import alias must not credit the owner: {related:?}" + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value() +-> Result<(), String> { + // #14508 review: the alias names the free owner. A free `dt(7, 7)` must + // not lend its arguments to a same-named associated owner. + let lib_src = "pub struct Rival;\n\nimpl Rival {\n pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { 777 } else { 7 } }\n}\n\npub fn discounted_total(amount: i32, _threshold: i32) -> i32 { amount + 1 }\n\n#[cfg(test)]\nmod tests {\n use crate::discounted_total as dt;\n use crate::Rival;\n\n #[test]\n fn mixed() {\n assert_eq!(Rival::discounted_total(100, 100), 777);\n assert_eq!(dt(7, 7), 8);\n }\n}\n"; + let root = alias_workspace_with_files("lib_proptest", &[("src/lib.rs", lib_src)])?; + let evidence = evidence_for_alias_seam(&root, &[PathBuf::from("src/lib.rs")], "src/lib.rs")?; + let values: Vec<&str> = evidence + .observed_values + .iter() + .map(|fact| fact.value.as_str()) + .collect(); + assert!( + !values.contains(&"7"), + "the free alias call must not lend its argument to the associated owner: {values:?}" + ); + assert!( + values.contains(&"100"), + "the associated call's argument is the associated owner's activation value: {values:?}" + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it() +-> Result<(), String> { + // #14508 review: a test may call the owner through the alias and also + // spell `rival::dt(..)` on a lowercase module, which the free-call reader + // otherwise accepts. The relation still credits the owner through the bare + // alias, but the qualified call's arguments must not become its values. + let prod_src = "pub mod rival;\n\npub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let rival_src = "pub fn dt(_amount: i32, _threshold: i32) -> i32 { 777 }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\nuse lib_proptest::rival;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n assert_eq!(rival::dt(7, 7), 777);\n}\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("src/rival.rs"), rival_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/rival.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence + .related_tests + .iter() + .any(|test| test.test_name == "mixed"), + "the free alias call still credits the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a qualified `Rival::dt(..)` must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the free alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_raw_escaped_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it() +-> Result<(), String> { + // The raw identifier is still module-qualified, so its arguments belong + // to the rival and not to the genuine bare alias call beside it. + let prod_src = "pub mod rival;\n\npub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let rival_src = "pub fn r#dt(_amount: i32, _threshold: i32) -> i32 { 777 }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\nuse lib_proptest::rival;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n assert_eq!(rival::r#dt(7, 7), 777);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", prod_src), + ("src/rival.rs", rival_src), + ("tests/boundary.rs", tests_src), + ], + )?; + let files = [ + "src/lib.rs", + "src/rival.rs", + "tests/boundary.rs", + ] + .map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["mixed"]); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a qualified `rival::r#dt(..)` must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the bare alias call still supplies the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_external_import_crate_root_redirects_with_path_then_original_owner_gets_no_related_test() +-> Result<(), String> { + // `lib_proptest::pricing` resolves to the redirected file as rustc does, + // not to the original physical `src/pricing.rs` owner. + let owner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ( + "src/lib.rs", + "#[path = \"redirected_pricing.rs\"]\npub mod pricing;\n", + ), + ("src/pricing.rs", owner), + ( + "src/redirected_pricing.rs", + "pub fn owner(amount: i32) -> i32 { amount }\n", + ), + ( + "tests/boundary.rs", + "use lib_proptest::pricing::owner as dt;\n\n#[test]\nfn redirected() {\n assert_eq!(dt(7), 7);\n}\n", + ), + ], + )?; + let files = [ + "src/lib.rs", + "src/pricing.rs", + "src/redirected_pricing.rs", + "tests/boundary.rs", + ] + .map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty() + && evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "the redirected import must not credit the original physical owner: {:?} / {:?}", + evidence.related_tests, + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a test in package A that imports package B's function + // under an alias must not credit package A's own same-named owner, even + // when both packages are indexed. + let negative = two_package_workspace("pkg_b")?; + let negative_files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("pkg_a/src/lib.rs"), + PathBuf::from("pkg_a/tests/control.rs"), + ]; + let negative_index = build_index(&negative, &negative_files)?; + let negative_seams = + inventory_seams_from_index(&[PathBuf::from("pkg_a/src/lib.rs")], &negative_index); + let negative_seam = negative_seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let negative_related: Vec = evidence_for_seam(negative_seam, &negative_index) + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert!( + negative_related.is_empty(), + "a sibling package's alias must not credit pkg_a's owner: {negative_related:?}" + ); + + let positive = two_package_workspace("pkg_a")?; + let positive_files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("pkg_a/src/lib.rs"), + PathBuf::from("pkg_a/tests/control.rs"), + ]; + let positive_index = build_index(&positive, &positive_files)?; + let positive_seams = + inventory_seams_from_index(&[PathBuf::from("pkg_a/src/lib.rs")], &positive_index); + let positive_seam = positive_seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let positive_related: Vec = evidence_for_seam(positive_seam, &positive_index) + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert_eq!( + positive_related, + vec!["aliased".to_string()], + "the owner's own package alias must still credit it" + ); + Ok(()) +} + +fn two_package_workspace(alias_package: &str) -> Result { + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_nanos(); + let root = claim_index_fixture_root(stamp)?; + for dir in ["src", "pkg_a/src", "pkg_a/tests"] { + fs::create_dir_all(root.join(dir)).map_err(|error| error.to_string())?; + } + // The root package is `pkg_b`, so `index.package_names` names the sibling + // package; the old all-packages check credited `pkg_a`'s owner for it. + fs::write( + root.join("Cargo.toml"), + "[package]\nname = \"pkg_b\"\nversion = \"0.1.0\"\n\n[workspace]\nmembers = [\"pkg_a\"]\nresolver = \"2\"\n", + ) + .map_err(|error| error.to_string())?; + fs::write( + root.join("pkg_a/Cargo.toml"), + "[package]\nname = \"pkg_a\"\nversion = \"0.1.0\"\n\n[dependencies]\npkg_b = { path = \"..\" }\n", + ) + .map_err(|error| error.to_string())?; + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("pkg_a/src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write( + root.join("pkg_a/tests/control.rs"), + format!( + "use {alias_package}::discounted_total as dt;\n\n#[test]\nfn aliased() {{\n assert_eq!(dt(100, 100), 90);\n}}\n" + ), + ) + .map_err(|error| error.to_string())?; + Ok(root) +} + +#[test] +fn given_direct_owner_alias_when_a_block_binding_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + // #14508 review: a block-scoped `let dt = |..| 999;` beside a genuine + // `dt(100, 100)` must not lend the owner the closure's argument. + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n {\n let dt = |a: i32, b: i32| { let _ = (a, b); 999 };\n assert_eq!(dt(7, 7), 999);\n }\n}\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence + .related_tests + .iter() + .any(|test| test.test_name == "mixed"), + "the genuine alias call still credits the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a block-scoped closure binding must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the genuine alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_scoped_binding_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + // One table over every scanned shadowing form keeps each form and its + // expected value covered without five near-identical functions. + let cases = [ + ( + "closure parameter", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n let f = |dt: fn(i32, i32) -> i32| dt(7, 7);\n assert_eq!(f(|a, b| a + b), 14);\n}\n", + ), + ( + "for pattern", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n for dt in [|a: i32, b: i32| a + b] {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + ), + ( + "match arm", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n let x = |a: i32, b: i32| a + b;\n match x {\n dt => assert_eq!(dt(7, 7), 14),\n };\n}\n", + ), + ( + "if let pattern", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n if let Some(dt) = Some(|a: i32, b: i32| a + b) {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + ), + ( + "nested fn parameter", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n fn helper(dt: fn(i32, i32) -> i32) -> i32 {\n dt(7, 7)\n }\n assert_eq!(helper(|a, b| a + b), 14);\n}\n", + ), + ]; + for (label, tests_src) in cases { + assert_scoped_alias_shadow(tests_src, label)?; + } + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_closure_parameter_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n let f = |dt: fn(i32, i32) -> i32| dt(7, 7);\n assert_eq!(f(|a, b| a + b), 14);\n assert_eq!(dt(100, 100), 90);\n}\n", + "closure parameter after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_for_pattern_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n for dt in [|a: i32, b: i32| a + b] {\n assert_eq!(dt(7, 7), 14);\n }\n assert_eq!(dt(100, 100), 90);\n}\n", + "for pattern after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_match_arm_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n let x = |a: i32, b: i32| a + b;\n match x {\n dt => assert_eq!(dt(7, 7), 14),\n };\n assert_eq!(dt(100, 100), 90);\n}\n", + "match arm after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_an_if_let_pattern_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n if let Some(dt) = Some(|a: i32, b: i32| a + b) {\n assert_eq!(dt(7, 7), 14);\n }\n assert_eq!(dt(100, 100), 90);\n}\n", + "if let pattern after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_nested_fn_parameter_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n fn helper(dt: fn(i32, i32) -> i32) -> i32 {\n dt(7, 7)\n }\n assert_eq!(helper(|a, b| a + b), 14);\n assert_eq!(dt(100, 100), 90);\n}\n", + "nested fn parameter after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_let_chain_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n if let Some(dt) = Some(|a: i32, b: i32| a + b) && 1 > 0 {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + "let-chain", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_while_let_chain_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n while let Some(dt) = Some(|a: i32, b: i32| a + b) && 1 > 0 {\n assert_eq!(dt(7, 7), 14);\n break;\n }\n}\n", + "while-let-chain", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_let_chain_is_the_only_call_then_owner_gets_no_related_test() +-> Result<(), String> { + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write( + root.join("tests/boundary.rs"), + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn only_shadowed() {\n if let Some(dt) = Some(|a: i32, b: i32| a + b) && 1 > 0 {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + ) + .map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence.related_tests.is_empty(), + "a let-chain-only shadowed call must not credit the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a let-chain-only shadowed call must not lend the owner its argument: {:?}", + evidence.observed_values + ); + Ok(()) +} + +fn assert_scoped_alias_shadow(tests_src: &str, label: &str) -> Result<(), String> { + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence + .related_tests + .iter() + .any(|test| test.test_name == "mixed"), + "{label}: the genuine alias call must still credit the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "{label}: a scoped binding must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "{label}: the genuine alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_nested_import_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + // #14508 review: one test can hold an outer owner-bound `dt(100, 101)` + // and an inner `use rival::different_function as dt` whose `dt(7, 7)` + // binds to the rival. The inner call must not borrow the outer alias + // row's authority: neither its arguments as observed values nor its + // equal operands as boundary overlap. + let prod_src = "pub mod rival;\n\npub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let rival_src = "pub fn different_function(_amount: i32, _threshold: i32) -> i32 { 777 }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 101), 100);\n {\n use lib_proptest::rival::different_function as dt;\n assert_eq!(dt(7, 7), 777);\n }\n}\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("src/rival.rs"), rival_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/rival.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence + .related_tests + .iter() + .any(|test| test.test_name == "mixed"), + "the outer genuine alias call still credits the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a nested import-bound `dt(..)` must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the outer genuine alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + assert!( + evidence + .missing_discriminators + .iter() + .any(|fact| fact.value.contains("threshold")), + "the nested equal-operand call must not close the boundary-equality gap: {:?}", + evidence.missing_discriminators + ); + Ok(()) +} + +/// Build an `alias_workspace_root` and write every `(path, source)` into it. +fn alias_workspace_with_files( + package: &str, + files: &[(&str, &str)], +) -> Result { + let root = alias_workspace_root(package)?; + for (path, source) in files { + let full = root.join(path); + if let Some(parent) = full.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + fs::write(full, source).map_err(|error| error.to_string())?; + } + Ok(root) +} + +fn evidence_for_alias_seam( + root: &Path, + files: &[PathBuf], + seam_file: &str, +) -> Result { + let index = build_index(root, files)?; + let seams = inventory_seams_from_index(&[PathBuf::from(seam_file)], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + Ok(evidence_for_seam(seam, &index)) +} + +/// The related tests the direct-owner-alias relation credited. Proximity +/// strategies (`AssertionTargetAffinity`) may also relate a test; those are +/// not the authority this repair reads. +fn direct_owner_call_tests(evidence: &TestGripEvidence) -> Vec<&str> { + evidence + .related_tests + .iter() + .filter(|test| test.relation_reason == RelationReason::DirectOwnerCall) + .map(|test| test.test_name.as_str()) + .collect() +} + +#[test] +fn given_direct_owner_alias_when_an_integration_test_module_shadows_the_library_module_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: `crate::pricing` in an integration test names the test + // crate's own `tests/pricing.rs`, not the library's `src/pricing.rs`. + // The rival call must not credit the library owner; the genuine + // package-qualified alias beside it still must. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let rival = "pub fn owner(amount: i32) -> i32 { amount }\n"; + let control = "mod pricing;\n\nuse crate::pricing::owner as rival_dt;\nuse lib_proptest::pricing::owner as genuine_dt;\n\n#[test]\nfn rival() {\n assert_eq!(rival_dt(100), 100);\n}\n\n#[test]\nfn genuine() {\n assert_eq!(genuine_dt(100), 90);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", library), + ("tests/pricing.rs", rival), + ("tests/control.rs", control), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing.rs"), + PathBuf::from("tests/pricing.rs"), + PathBuf::from("tests/control.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["genuine"], + "a test crate's own `crate::pricing` module must not credit the library owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the genuine alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_binary_inline_module_shadows_the_library_module_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a package with both a library and a binary. The binary's + // inline `mod pricing` is a different compilation unit from the library's + // `src/pricing.rs`, so `crate::pricing::owner` in `src/main.rs` binds to + // the binary's own function. The library unit test beside it still must + // credit the owner, and the rival's argument must not become an observed + // value. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::owner as dt;\n\n #[test]\n fn library_unit_test() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let binary = "mod pricing {\n pub fn owner(amount: i32) -> i32 {\n amount\n }\n}\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn binary_local_rival() {\n assert_eq!(dt(7), 7);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", library), + ("src/main.rs", binary), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing.rs"), + PathBuf::from("src/main.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["library_unit_test"], + "a binary's inline `mod pricing` must not credit the library owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "the binary rival's argument must not become an observed value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_binary_root_imports_the_library_root_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: `crate::` in `src/main.rs` names the binary crate, so it + // can never name the library root `src/lib.rs`. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "use crate::owner as dt;\n\n#[test]\nfn binary_root_rival() {\n assert_eq!(dt(7), 7);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[("src/lib.rs", library), ("src/main.rs", binary)], + )?; + let files = [PathBuf::from("src/lib.rs"), PathBuf::from("src/main.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty(), + "a binary root's `crate::owner` must not credit the library root: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "the binary rival's argument must not become an observed value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a `src/bin/` target's module tree is confined to + // its own directory, so `crate::pricing` there never names the library's + // `src/pricing.rs`. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "use crate::pricing::owner as dt;\n\n#[test]\nfn bin_target_rival() {\n assert_eq!(dt(7), 7);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", library), + ("src/bin/cli.rs", binary), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing.rs"), + PathBuf::from("src/bin/cli.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty(), + "a `src/bin` target's `crate::pricing` must not credit the library module: {:?}", + evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_nested_bin_module_imports_the_library_root_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a module inside a `src/bin/` target is not the + // target root, but its `crate::owner` still names the binary crate, never + // the library root `src/lib.rs`. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary_root = "mod work;\n\nfn main() {}\n"; + let nested = "use crate::owner as dt;\n\n#[test]\nfn nested_bin_rival() {\n assert_eq!(dt(7), 7);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", library), + ("src/bin/cli/main.rs", binary_root), + ("src/bin/cli/work.rs", nested), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/bin/cli/main.rs"), + PathBuf::from("src/bin/cli/work.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty(), + "a nested bin module's `crate::owner` must not credit the library root: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "the nested bin rival's argument must not become an observed value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_library_child_module_imports_the_crate_root_owner_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: `crate::owner` in a library child module names the + // library root, so the alias must credit the root owner. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\npub mod child;\n"; + let child = "use crate::owner as dt;\n\n#[test]\nfn child_module_uses_the_root_owner() {\n assert_eq!(dt(100), 90);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[("src/lib.rs", library), ("src/child.rs", child)], + )?; + let files = [PathBuf::from("src/lib.rs"), PathBuf::from("src/child.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + let mut related = direct_owner_call_tests(&evidence); + related.sort_unstable(); + assert_eq!( + related, + vec!["child_module_uses_the_root_owner"], + "a library child module's `crate::owner` credits the root owner: {:?}", + evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_bin_only_child_module_imports_its_crate_root_owner_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: with no library target, `crate::owner` in a child module + // names the binary root `src/main.rs`, so the alias must credit it. + let main = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\npub mod child;\n\nfn main() {}\n"; + let child = "use crate::owner as dt;\n\n#[test]\nfn bin_child_uses_the_root_owner() {\n assert_eq!(dt(100), 90);\n}\n"; + let root = alias_workspace_with_files( + "bin_only", + &[("src/main.rs", main), ("src/child.rs", child)], + )?; + let files = [PathBuf::from("src/main.rs"), PathBuf::from("src/child.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/main.rs")?; + let mut related = direct_owner_call_tests(&evidence); + related.sort_unstable(); + assert_eq!( + related, + vec!["bin_child_uses_the_root_owner"], + "a bin-only child module's `crate::owner` credits the binary root owner: {:?}", + evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_binary_child_module_imports_the_binary_root_then_library_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a package with both `src/lib.rs` and `src/main.rs` has + // two compilation units. `src/child.rs` is declared only by the binary, so + // `crate::owner` in it names the binary's re-export, never the library + // owner. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "pub fn binary_value(_: i32) -> i32 { 800 }\n\npub use crate::binary_value as owner;\n\nmod child;\n\nfn main() {}\n"; + let child = "use crate::owner as dt;\n\n#[test]\nfn binary_child() {\n assert_eq!(dt(100), 800);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", library), + ("src/main.rs", binary), + ("src/child.rs", child), + ], + )?; + let files = ["src/lib.rs", "src/main.rs", "src/child.rs"].map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty() && evidence.observed_values.is_empty(), + "a binary-only child module's `crate::owner` must not credit the library root: {:?} / {:?}", + evidence.related_tests, + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review control: with no library target, `mod pricing;` in + // `src/main.rs` resolves to `src/pricing.rs`, so the crate-relative alias + // is a genuine direct owner call and must keep its credit. + let pricing = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "mod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn bin_genuine() {\n assert_eq!(dt(100), 90);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "bin_only", + &[("src/main.rs", binary), ("src/pricing.rs", pricing)], + )?; + let files = [ + PathBuf::from("src/main.rs"), + PathBuf::from("src/pricing.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["bin_genuine"], + "a bin-only package's own module is the owner: {:?}", + evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: `#[path = "binary_pricing.rs"]` makes the binary's + // `crate::pricing` name `src/binary_pricing.rs`, not the library's + // `src/pricing.rs`, so the alias must fail closed. + let owner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "#[path = \"binary_pricing.rs\"]\nmod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn binary_redirected() {\n assert_eq!(dt(7), 7);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", owner), + ("src/main.rs", binary), + ("src/binary_pricing.rs", owner), + ], + )?; + let files = [ + "src/lib.rs", + "src/pricing.rs", + "src/main.rs", + "src/binary_pricing.rs", + ] + .map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty() + && evidence + .observed_values + .iter() + .all(|fact| fact.value != "7") + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_an_intermediate_segment_redirects_with_path_then_owner_gets_no_related_test() +-> Result<(), String> { + // `mod pricing` is redirected to `other_pricing.rs`, so + // `crate::pricing::inner` does not name `src/pricing/inner.rs`. + let owner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let lib = "#[path = \"other_pricing.rs\"]\npub mod pricing;\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::inner::owner as dt;\n\n #[test]\n fn redirected() {\n assert_eq!(dt(7), 7);\n }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", lib), + ("src/pricing/inner.rs", owner), + ("src/other_pricing.rs", "pub mod inner;\n"), + ( + "src/other_pricing/inner.rs", + "pub fn owner(amount: i32) -> i32 { amount }\n", + ), + ], + )?; + let files = [ + "src/lib.rs", + "src/pricing/inner.rs", + "src/other_pricing.rs", + "src/other_pricing/inner.rs", + ] + .map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing/inner.rs")?; + assert!(direct_owner_call_tests(&evidence).is_empty()); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_flat_bin_root_imports_its_sibling_module_then_owner_keeps_related_test() +-> Result<(), String> { + let cargo = "[package]\nname = \"lib_proptest\"\nversion = \"0.1.0\"\nedition = \"2021\"\nautobins = false\n\n[[bin]]\nname = \"cli\"\npath = \"src/bin/cli.rs\"\n"; + let cli = "mod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn binary_genuine_flat() {\n assert_eq!(dt(100), 90);\n}\n\nfn main() {}\n"; + let pricing = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("Cargo.toml", cargo), + ("src/bin/cli.rs", cli), + ("src/bin/pricing.rs", pricing), + ], + )?; + let files = ["src/bin/cli.rs", "src/bin/pricing.rs"].map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/bin/pricing.rs")?; + assert_eq!( + direct_owner_call_tests(&evidence), + vec!["binary_genuine_flat"] + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_directory_bin_root_imports_its_own_module_then_owner_keeps_related_test() +-> Result<(), String> { + let cargo = "[package]\nname = \"lib_proptest\"\nversion = \"0.1.0\"\nedition = \"2021\"\nautobins = false\n\n[[bin]]\nname = \"cli\"\npath = \"src/bin/cli/main.rs\"\n"; + let main = "mod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn binary_genuine_dir() {\n assert_eq!(dt(100), 90);\n}\n\nfn main() {}\n"; + let pricing = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("Cargo.toml", cargo), + ("src/bin/cli/main.rs", main), + ("src/bin/cli/pricing.rs", pricing), + ], + )?; + let files = ["src/bin/cli/main.rs", "src/bin/cli/pricing.rs"].map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/bin/cli/pricing.rs")?; + assert_eq!( + direct_owner_call_tests(&evidence), + vec!["binary_genuine_dir"] + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_lib_and_bin_share_the_module_then_owner_keeps_related_test() +-> Result<(), String> { + let owner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "mod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn bin_genuine() {\n assert_eq!(dt(100), 90);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", owner), + ("src/main.rs", binary), + ], + )?; + let files = ["src/lib.rs", "src/pricing.rs", "src/main.rs"].map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["bin_genuine"]); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_owner_is_a_nested_module_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: the alias table stores the import with `::` while the + // owner's module path comes from the index with `/`; the nested owner + // (`pricing/inner`) must still resolve its `crate::pricing::inner` import + // whether `pricing` is `pricing/mod.rs` or `pricing.rs`, whose + // `pub mod inner;` rustc resolves under `pricing/`, not `src/`. + let inner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::inner::owner as dt;\n\n #[test]\n fn aliased() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let lib = "pub mod pricing;\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::inner::owner as dt;\n\n #[test]\n fn aliased_from_root() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + for module in ["src/pricing/mod.rs", "src/pricing.rs"] { + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", lib), + (module, "pub mod inner;\n"), + ("src/pricing/inner.rs", inner), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from(module), + PathBuf::from("src/pricing/inner.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing/inner.rs")?; + let mut related = direct_owner_call_tests(&evidence); + related.sort_unstable(); + assert_eq!(related, vec!["aliased", "aliased_from_root"], "{module}"); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "{module}" + ); + } + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_nested_main_module_declares_the_owner_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: a nested `main.rs` is a module, not a crate root, so its + // `pub mod inner;` resolves under `main/`, not beside it. + let inner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::outer::main::inner::owner as dt;\n\n #[test]\n fn aliased() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let lib = "pub mod outer;\n\n#[cfg(test)]\nmod tests {\n use crate::outer::main::inner::owner as dt;\n\n #[test]\n fn aliased_from_root() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", lib), + ("src/outer.rs", "pub mod main;\n"), + ("src/outer/main.rs", "pub mod inner;\n"), + ("src/outer/main/inner.rs", inner), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/outer.rs"), + PathBuf::from("src/outer/main.rs"), + PathBuf::from("src/outer/main/inner.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/outer/main/inner.rs")?; + let mut related = direct_owner_call_tests(&evidence); + related.sort_unstable(); + assert_eq!(related, vec!["aliased", "aliased_from_root"]); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_owner_is_a_mod_rs_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: `src/pricing/mod.rs` is the `pricing` module, whose + // import is `crate::pricing`; the index's file-stem path (`pricing/mod`) + // must fold the `mod` leaf. + let pricing = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::owner as dt;\n\n #[test]\n fn aliased() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing/mod.rs", pricing), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing/mod.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing/mod.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!(related, vec!["aliased"]); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100") + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_sibling_module_declares_the_alias_name_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: inline modules have separate name scopes. `dt` in + // `mod unrelated` cannot bind the `dt(..)` call in `mod tests`, so the + // import alias still reaches the owner. + let lib = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\nmod unrelated {\n pub fn dt(_amount: i32) -> i32 { 0 }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::owner as dt;\n\n #[test]\n fn aliased() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let root = alias_workspace_with_files("lib_proptest", &[("src/lib.rs", lib)])?; + let files = [PathBuf::from("src/lib.rs")]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&files, &index); + let owner_seam = seams + .iter() + .find(|seam| { + seam.owner() == "src/lib.rs::owner" && seam.kind() == SeamKind::PredicateBoundary + }) + .ok_or_else(|| "expected the owner's predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(owner_seam, &index); + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["aliased"], + "a sibling module's `dt` is a different name scope: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100") + ); + // The sibling function is not the callee: the test's `dt(..)` binds to + // the imported owner, so the sibling must not be credited (#14508 + // review). + let sibling_seam = seams + .iter() + .find(|seam| seam.owner() == "src/lib.rs::unrelated::dt") + .ok_or_else(|| "expected the sibling module's seam".to_string())?; + let sibling_evidence = evidence_for_seam(sibling_seam, &index); + assert!( + direct_owner_call_tests(&sibling_evidence).is_empty(), + "the sibling module's `dt` must not be credited: {:?}", + sibling_evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_test_module_declares_the_alias_name_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review, mirror-image control for the enclosing-module case: the + // `use` is at the crate root and `fn dt` is inside `mod tests`, so the + // innermost binding is the local function and the import must not credit + // the owner. The shape compiles (the two `dt` items are in different + // modules). + let lib = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\nuse crate::owner as dt;\n\n#[cfg(test)]\nmod tests {\n fn dt(_amount: i32) -> i32 { 0 }\n\n #[test]\n fn shadowed() {\n assert_eq!(dt(100), 0);\n }\n}\n"; + let root = alias_workspace_with_files("lib_proptest", &[("src/lib.rs", lib)])?; + let files = [PathBuf::from("src/lib.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty(), + "a same-module `dt` must shadow the import alias: {:?}", + evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_an_enclosing_module_declares_the_alias_name_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: the `use` inside `mod tests` shadows the crate-root + // `fn dt`, so the call binds to the import and the owner is credited. + let lib = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\nfn dt(_amount: i32) -> i32 { 0 }\n\n#[cfg(test)]\nmod tests {\n use crate::owner as dt;\n\n #[test]\n fn aliased_owner_is_reached() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let root = alias_workspace_with_files("lib_proptest", &[("src/lib.rs", lib)])?; + let files = [PathBuf::from("src/lib.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["aliased_owner_is_reached"], + "an inner use shadows the enclosing fn: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100") + ); + Ok(()) +} + #[test] fn given_integration_test_when_rival_nested_in_another_module_then_owner_gets_no_related_test() -> Result<(), String> { @@ -23935,6 +25239,94 @@ fn field_write_facts_with_tail( .collect()) } +/// Build the lib+integration-test fixture and read the alias seam's evidence. +fn alias_evidence_for_lib_and_test( + lib_src: &str, + tests_src: &str, +) -> Result { + let root = alias_workspace_with_files( + "lib_proptest", + &[("src/lib.rs", lib_src), ("tests/boundary.rs", tests_src)], + )?; + evidence_for_alias_seam( + &root, + &[ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ], + "src/lib.rs", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_nearer_unsupported_import_shadows_it_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: `use self::rival::different as dt;` is not a supported + // owner path, but it still binds `dt` nearer than the outer owner alias. + let lib_src = + "pub fn owner(amount: i32) -> i32 { if amount >= 100 { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::owner as dt;\n\nmod rival {\n pub fn different(_amount: i32) -> i32 { 0 }\n}\n\n#[test]\nfn shadowed() {\n use self::rival::different as dt;\n assert_eq!(dt(100), 0);\n}\n\n#[test]\nfn genuine() {\n assert_eq!(dt(100), 90);\n}\n"; + let evidence = alias_evidence_for_lib_and_test(lib_src, tests_src)?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["genuine"]); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_closure_in_a_macro_token_tree_shadows_it_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a closure inside an assertion macro is an opaque token + // tree, so its parameter is not a `ClosureExpr` node. + let lib_src = + "pub fn owner(amount: i32) -> i32 { if amount >= 100 { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::owner as dt;\n\n#[test]\nfn shadowed() {\n assert_eq!((|dt: fn(i32) -> i32| dt(100))(fake), 0);\n}\n\n#[test]\nfn genuine() {\n assert_eq!(dt(100), 90);\n}\n"; + let evidence = alias_evidence_for_lib_and_test(lib_src, tests_src)?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["genuine"]); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_test_function_parameter_shadows_it_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a `#[rstest]` fixture parameter named like the alias + // shadows it for the whole body. + let lib_src = + "pub fn owner(amount: i32) -> i32 { if amount >= 100 { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::owner as dt;\n\n#[rstest]\nfn shadowed(dt: fn(i32) -> i32) {\n assert_eq!(dt(100), 0);\n}\n\n#[test]\nfn genuine() {\n assert_eq!(dt(100), 90);\n}\n"; + let evidence = alias_evidence_for_lib_and_test(lib_src, tests_src)?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["genuine"]); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_cfg_gated_module_has_two_paths_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: two `#[cfg]`-gated `mod pricing;` declarations with + // different `#[path]` targets compile different files per configuration. + let lib_src = "#[cfg(unix)]\n#[path = \"pricing_unix.rs\"]\nmod pricing;\n#[cfg(windows)]\n#[path = \"pricing_windows.rs\"]\nmod pricing;\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::owner as dt;\n\n #[test]\n fn shadowed() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let unix_src = + "pub fn owner(amount: i32) -> i32 { if amount >= 100 { amount - 10 } else { amount } }\n"; + let windows_src = "pub fn owner(amount: i32) -> i32 { amount }\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", lib_src), + ("src/pricing_unix.rs", unix_src), + ("src/pricing_windows.rs", windows_src), + ], + )?; + let evidence = evidence_for_alias_seam( + &root, + &[ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing_unix.rs"), + PathBuf::from("src/pricing_windows.rs"), + ], + "src/pricing_unix.rs", + )?; + assert!(direct_owner_call_tests(&evidence).is_empty()); + Ok(()) +} + /// #14089: the original name before `as` was measured one byte past a /// multibyte char. `क्` ends in U+094D, a virama (an identifier char that is /// not alphanumeric, three bytes); the original is now read whole. diff --git a/docs/spec-index.d/RIPR-SPEC-0442.md b/docs/spec-index.d/RIPR-SPEC-0442.md new file mode 100644 index 00000000000..89a9d3c336c --- /dev/null +++ b/docs/spec-index.d/RIPR-SPEC-0442.md @@ -0,0 +1 @@ +| [RIPR-SPEC-0442](../specs/RIPR-SPEC-0442-aliased-owner-import-credit.md) | accepted | An aliased owner import credits the owner as a direct call only when the import names the owner's module in the same compilation unit; same-module, sibling-module, other-crate, binary and lexical bindings are refused (#14508) | diff --git a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md new file mode 100644 index 00000000000..0fd5b02f70e --- /dev/null +++ b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md @@ -0,0 +1,130 @@ +# RIPR-SPEC-0442: An aliased owner import credits the owner only when the import names its module in the same compilation unit + +Status: accepted + +Owner: product / analysis + +Created: 2026-11-13 + +Linked issues: #14508 (an aliased direct import of the owner is not credited, +and naive name matching over-credits a test crate's own module); #14016 (the +selective control for test-local rival imports). + +Linked PRs: #14513 + +Support-tier impact: no tier change. The change decides which existing +`direct_owner_call` relation a test already-spelled call earns; it adds no +grip class, `static_limit_kind` value or exposure class. Claim boundaries +remain governed by [support tiers](../status/SUPPORT_TIERS.md). + +Policy impact: register this spec in `policy/doc-artifacts.d/RIPR-SPEC-0442.toml` +and `.ripr/traceability.d/RIPR-SPEC-0442.toml`. No schema or JSON field +change; the judged repo-exposure fields stay `grip_class`, `evidence.reach`, +`related_tests[].relation_reason` and `observed_values`. + +## Problem + +A test that writes `use crate::pricing::discounted_total as dt;` and calls +`dt(100, 100)` reaches the owner, but no spec stated that the alias credits +it. The owner module path joined segments with `/` while the import used +`::`, so a nested owner stayed `activation_unknown`; and a test crate's own +`crate::pricing` resolved to `tests/pricing.rs` yet a bare module-name +comparison credited the library's `src/pricing.rs::owner`. + +## Behavior + +A direct import of the owner's function under an alias credits the owner as +`direct_owner_call` when both hold: + +1. The import names the owner's module in the same compilation unit. A unit + test may use `use crate::::owner as dt;` (or `use crate::owner as + dt;` for the crate root); an integration test uses the owner's package + qualification, `use ::::owner as dt;`, and the package + must be the one the test's crate imports the owner's library by. +2. The call's spelling binds to that import at the call line: no nearer + lexical `use`, local function, `let`, closure parameter, + `for`/match-arm/`if let`/`while let` pattern or nested-`fn` parameter of + the same spelling is in scope. + +Both sides of the module comparison use one `/`-segment representation. +`src/pricing/mod.rs` names the `pricing` module; a crate root has the empty +path. A nested `mod x;` resolves as rustc does, following `#[path]`. + +The alias does not credit the owner when: + +- A `crate::` import appears in an integration test (`tests/...`), which + names the test crate's own modules, or in a binary target, which names the + binary. +- The import names another package, a sibling package, or another + compilation unit than the owner's. +- In a binary target root, the alias chain's first segment is declared with a + non-default `#[path]` or is not declared at all. +- A local function of the alias's name is declared in the import's own + module or a nested module (at least as deep as the import) and in the + call's module chain, or a lexical binding of the name is in scope at the + call. A declaration in an enclosing module is shadowed by the import, and a + sibling inline module is a different name scope: neither withholds the + alias, and the sibling does not itself receive the alias credit. + +A test that also spells a genuine local call of the alias name keeps the +generic direct-call credit for that call; only the alias-shaped calls are +routed to the import. The rule decides `related_tests[].relation_reason` in +the seam-grip and repo-exposure paths and adds no reach edge by itself. + +## Required Evidence + +- An aliased unit-test call credits the owner with `direct_owner_call` and + the observed argument; an integration test's genuine package-qualified + alias credits the owner, while the same test crate's own `crate::` module + does not. +- A nested owner (`src/pricing/inner.rs`) reached through `pricing/mod.rs` or + `pricing.rs`, and a `mod.rs` owner, credit their `crate::` imports. +- A same-named local function in the import's module or a nested module, or + a lexical binding, withholds the owner; an enclosing-module declaration is + shadowed by the import and keeps credit; a later genuine alias call keeps + credit. A sibling inline module's same-named function neither shadows the + alias nor receives the alias credit. +- Only a bare `alias(..)` spelling binds to the import: a same-line + `rival::alias(..)` on a lowercase module names that module's function and + lends the owner no argument. +- A free alias of the owner's name lends no argument to a same-named + associated owner; the associated owner keeps only its own calls' values. + +## Non-Goals + +- Grouped (`use a::{b as c}`), chained (`use a::b as c; use c::d;`) and renamed module aliases (`use a as b;`). +- The diff-mode `ripr check` relation path, which is a separate gap. +- Trait or impl alias credit; the alias must name a free function. +- In a lib+bin package whose binary root declares the module with the default + path, the binary's `crate::` compiles the same source file as the + library owner, and the alias still credits it. Tracked in #14558. + +## Acceptance Examples + +1. `src/pricing.rs::owner`, `tests/control.rs` with its own `mod pricing;` + and `use crate::pricing::owner as dt; assert_eq!(dt(100), 100);`: no credit. +2. `src/pricing/inner.rs::owner`, a unit test with + `use crate::pricing::inner::owner as dt; assert_eq!(dt(100), 90);`: + `direct_owner_call`, observed `["100"]`. +3. `src/lib.rs::owner` with a genuine `use crate::owner as dt;` beside + `mod unrelated { pub fn dt(..) { .. } }`: the real owner is credited; + `src/lib.rs::unrelated::dt` is not credited as a direct owner call. + +## Test Mapping + +- `crates/ripr/src/analysis/test_grip_evidence/tests.rs`: the `given_direct_owner_alias_when_*` and `given_integration_test_when_owner_is_imported_under_an_alias_*` cases, including the library-child, bin-only-child and binary-child crate-root controls. +- `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests`: the `scoped_shadow_*` cases. + +## Implementation Mapping + +- `crates/ripr/src/analysis/test_grip_evidence/related_tests.rs`: + `match_direct_owner_call`, `direct_owner_alias_module_matches`, `crate_relative_alias_shares_compilation_unit`, `crate_root_file_for_test`. +- `crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs`: + `direct_owner_import_aliases`, `normalize_direct_owner_module_path`, `local_function_shadows_call`, `alias_binding_shadows_call`, `alias_spelling_binds_other_owner`, `local_module_shadows_alias`. +- `crates/ripr/src/analysis/classify/const_flow.rs`: + `ModuleScopes::declaration_shadows_import`. + +## Metrics + +- `unit_test_pass_rate` +- `corpus_case_pass_rate` diff --git a/fixtures/perl-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml b/fixtures/perl-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..915770dbc17 --- /dev/null +++ b/fixtures/perl-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml @@ -0,0 +1,3 @@ +id = "RIPR-SPEC-0442" +scope = "out" +reason = "Related-test credit and direct-owner evidence kind for an import alias of the owner; the examples assert an evidence classification, not an exposure verdict a Rust diff plus runtime mutant truth labels. Pinned by crates/ripr/src/analysis/test_grip_evidence/tests.rs and the analysis::extract::shadow import-shadow table." diff --git a/fixtures/python-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml b/fixtures/python-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..915770dbc17 --- /dev/null +++ b/fixtures/python-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml @@ -0,0 +1,3 @@ +id = "RIPR-SPEC-0442" +scope = "out" +reason = "Related-test credit and direct-owner evidence kind for an import alias of the owner; the examples assert an evidence classification, not an exposure verdict a Rust diff plus runtime mutant truth labels. Pinned by crates/ripr/src/analysis/test_grip_evidence/tests.rs and the analysis::extract::shadow import-shadow table." diff --git a/fixtures/rust-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml b/fixtures/rust-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..915770dbc17 --- /dev/null +++ b/fixtures/rust-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml @@ -0,0 +1,3 @@ +id = "RIPR-SPEC-0442" +scope = "out" +reason = "Related-test credit and direct-owner evidence kind for an import alias of the owner; the examples assert an evidence classification, not an exposure verdict a Rust diff plus runtime mutant truth labels. Pinned by crates/ripr/src/analysis/test_grip_evidence/tests.rs and the analysis::extract::shadow import-shadow table." diff --git a/fixtures/typescript-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml b/fixtures/typescript-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..915770dbc17 --- /dev/null +++ b/fixtures/typescript-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml @@ -0,0 +1,3 @@ +id = "RIPR-SPEC-0442" +scope = "out" +reason = "Related-test credit and direct-owner evidence kind for an import alias of the owner; the examples assert an evidence classification, not an exposure verdict a Rust diff plus runtime mutant truth labels. Pinned by crates/ripr/src/analysis/test_grip_evidence/tests.rs and the analysis::extract::shadow import-shadow table." diff --git a/policy/doc-artifacts.d/RIPR-SPEC-0442.toml b/policy/doc-artifacts.d/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..7adfa13312c --- /dev/null +++ b/policy/doc-artifacts.d/RIPR-SPEC-0442.toml @@ -0,0 +1,7 @@ +[[artifact]] +id = "RIPR-SPEC-0442" +kind = "spec" +path = "docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md" +status = "accepted" +owner = "product-analysis" +standalone_reason = "Issue #14508 makes an aliased direct import of the owner credit the owner only when the import names its module in the same compilation unit; no existing spec states the alias rule." diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 8cea9dffd08..6fbc0af5d8b 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -14999,10 +14999,15 @@ fn check_rust_source_role_authority() -> Result<(), String> { /// authority may be consumed only by this inventoried set; new consumers /// extend the inventory here with a reason so role consumers stay /// reviewable. - const IS_TEST_FILE_CONSUMERS: [&str; 14] = [ + const IS_TEST_FILE_CONSUMERS: [&str; 15] = [ "crates/ripr/src/analysis/classify/owner_shape.rs", "crates/ripr/src/analysis/test_grip_evidence.rs", "crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs", + // #14508: a crate-relative direct-owner alias in an integration-test + // file names the test crate's own modules, never the library's; the + // layout authority stays `is_test_file` and the module decides no + // role of its own. + "crates/ripr/src/analysis/test_grip_evidence/related_tests.rs", "crates/ripr/src/analysis/source_role_corpus.rs", "crates/ripr/src/analysis/mod.rs", "crates/ripr/src/analysis/language/rust/mod.rs",