Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/6694-parameter-returning-helper-sink.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<!-- section: Fixed -->
- A private generic helper whose whole body is `if cond { a } else { b }` over two different parameters (for example a `capped(value, cap)` helper) now has the condition as its return sink, so a boundary change tested through an exact forwarding wrapper reads `exposed` instead of `propagation_unknown` (#6694).
139 changes: 139 additions & 0 deletions crates/ripr/src/analysis/classify/flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,14 @@ fn predicate_flow_sinks(
owner,
)];
}
if let Some(branch) = tail_if_parameter_branches(probe, owner_fn) {
return vec![flow_sink(
FlowSinkKind::ReturnValue,
branch.text,
branch.line,
owner,
)];
}
if let Some(return_fact) = nearest_return(owner_fn, probe.location.line) {
return vec![flow_sink(
FlowSinkKind::ReturnValue,
Expand Down Expand Up @@ -896,6 +904,67 @@ fn tail_if_branch_value(
})
}

/// #6694: the rustfmt tail `if <cond> {` / `a` / `} else {` / `b` / `}` whose
/// two branch values are different parameters of the owner (`if value > cap {
/// cap } else { value }`, the body of a generic `min`/`max`/clamp helper). The
/// condition decides which parameter the function returns, so the first branch
/// is the value sink. Fails closed: the function body is exactly that `if`
/// (no earlier statement can rebind a parameter), the owner returns a value,
/// the probe is the `if` condition, and each branch is one bare parameter name
/// (distinct, so the choice is observable). A literal, call or other
/// expression branch keeps the adjacency reading of [`next_branch_value`].
fn tail_if_parameter_branches(
probe: &Probe,
owner_fn: Option<&FunctionSummary>,
) -> Option<LocalTextFact> {
let function = owner_fn?;
if probe.owner.as_ref() != Some(&function.id) || probe.location.line != function.start_line + 1
{
return None;
}
let masked = crate::analysis::language::mask_rust_comments_and_strings(&function.body);
let lines: Vec<&str> = masked.lines().map(str::trim).collect();
let [
signature,
head,
then_value,
else_head,
else_value,
inner_close,
outer_close,
] = lines.as_slice()
else {
return None;
};
if !signature_returns_value(signature)
|| !signature.ends_with('{')
|| *else_head != "} else {"
|| *inner_close != "}"
|| *outer_close != "}"
{
return None;
}
let condition = head.strip_prefix("if ")?.strip_suffix('{')?.trim();
let code = |text: &str| {
crate::analysis::language::mask_rust_comments_and_strings(text)
.trim()
.to_string()
};
if condition.is_empty() || condition != code(&probe.expression) {
return None;
}
let parameters = super::call_parameter_names(function);
let is_parameter =
|name: &str| is_plain_identifier(name) && parameters.iter().any(|known| known == name);
if !is_parameter(then_value) || !is_parameter(else_value) || then_value == else_value {
return None;
}
Some(LocalTextFact {
line: probe.location.line + 1,
text: (*then_value).to_string(),
})
}

/// Whether the signature's top-level return type (the arrow after the
/// parameter list) names a non-unit value. Arrows inside parameter types
/// (`fn() -> i32`) do not count.
Expand Down Expand Up @@ -2905,6 +2974,76 @@ mod tests {
}
}

/// #6694: `if c { a } else { b }` as a helper's whole body over two
/// distinct parameters sinks the condition at the first branch value;
/// every other shape keeps no sink.
#[test]
fn parameter_returning_tail_if_sinks_the_condition_only_when_whole_and_distinct() {
let sinks = |body: &str| {
let owner = function(body);
local_flow_sinks(
&probe(ProbeFamily::Predicate, "cap < value", 2),
Some(&owner),
)
};
let capped = |branches: &str, prefix: &str| {
format!(
"fn capped<T: PartialOrd + Copy>(value: T, cap: T) -> T {{\n{prefix} if cap < value {{\n{branches}}}\n}}"
)
};
let found = sinks(&capped(
" cap\n } else {\n value\n ",
"",
));
assert!(
found
.iter()
.any(|sink| sink.kind == FlowSinkKind::ReturnValue
&& sink.text == "cap"
&& sink.line == 3),
"{found:?}"
);
for (label, body) in [
(
"a statement before the if",
capped(
" cap\n } else {\n value\n ",
" let value = value;\n",
),
),
(
"the same parameter in both branches",
capped(" value\n } else {\n value\n ", ""),
),
(
"a branch that is no parameter",
capped(" cap\n } else {\n other\n ", ""),
),
(
"a statement after the branches",
capped(" cap\n } else {\n value\n ", "")
.replace(" }\n}", " }\n ;\n}"),
),
] {
let found = sinks(&body);
assert!(
found
.iter()
.all(|sink| sink.text != "cap" && sink.text != "value"),
"{label}: {found:?}"
);
}
// A unit-returning function has no value to decide.
let unit = sinks(
"fn capped(value: u32, cap: u32) {\n if cap < value {\n cap\n } else {\n value\n }\n}",
);
assert!(
unit.iter()
.all(|sink| sink.text != "cap" && sink.text != "value"),
"{unit:?}"
);
}

// ── #6695: `.ok_or(Variant)?` propagates that error from the owner ──

const OK_OR_LINE: &str = "let d = digit(c).ok_or_else(|| CodeError::NotDigit)?;";
Expand Down
62 changes: 60 additions & 2 deletions crates/ripr/tests/helper_wrapper_reach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -661,13 +661,71 @@ fn generic_helper_behind_a_constant_argument_wrapper_pairs() -> Result<(), Strin
);
assert_eq!(finding["ripr"]["infect"]["state"], "yes", "{finding}");
// The wrapper's exact pin at `capped_score(10)` pairs with `cap ==
// value`; propagation through `if .. { cap } else { value }` remains a
// separate syntax-first limit, so the class is not asserted here.
// value`, and the condition decides which parameter the helper returns
// (#6694), so the finding is no longer an abstention.
assert_eq!(finding["ripr"]["discriminate"]["state"], "yes", "{finding}");
assert!(
!discriminate_summary(&finding).contains("same_test_pairing_missing"),
"{finding}"
);
assert_eq!(finding["classification"], "exposed", "{finding}");
Ok(())
}

const CAPPED_DIFF: &str = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1,3 +1,3 @@\n fn capped<T: PartialOrd + Copy>(value: T, cap: T) -> T {\n- if value > cap {\n+ if cap < value {\n cap\n";
const CAPPED_HELPER: &str = "fn capped<T: PartialOrd + Copy>(value: T, cap: T) -> T {\n if cap < value {\n cap\n } else {\n value\n }\n}\n";
const CAPPED_WRAPPER: &str = "pub fn capped_score(value: u32) -> u32 {\n capped(value, 10)\n}\n";
const CAPPED_TESTS: &str = " assert_eq!(capped_score(11), 10);\n assert_eq!(capped_score(10), 10);\n assert_eq!(capped_score(3), 3);\n";

fn capped_source(helper: &str, wrapper: &str, tests: &str) -> String {
format!(
"{helper}\n{wrapper}\n#[cfg(test)]\nmod tests {{\n use super::*;\n\n #[test]\n fn scores_above_the_cap_are_capped() {{\n{tests} }}\n}}\n"
)
}

// #6694: the helper's branches return its two parameters, so the condition
// decides the returned value; every control below keeps the abstention or a
// weaker class because the pairing, the sink or the oracle is not exact.
#[test]
fn parameter_returning_helper_is_exposed_only_through_an_exact_forwarding_wrapper()
-> Result<(), String> {
let exposed = predicate_finding(
&capped_source(CAPPED_HELPER, CAPPED_WRAPPER, CAPPED_TESTS),
CAPPED_DIFF,
)?;
assert_eq!(exposed["classification"], "exposed", "{exposed}");
// The wrapper transforms the argument by a value ripr cannot read.
let transformed = predicate_finding(
&capped_source(
CAPPED_HELPER,
"fn step() -> u32 {\n 1\n}\n\npub fn capped_score(value: u32) -> u32 {\n capped(value * step(), 10)\n}\n",
CAPPED_TESTS,
),
CAPPED_DIFF,
)?;
assert_ne!(transformed["classification"], "exposed", "{transformed}");
// A wrapper assertion that is not an exact value.
let loose = predicate_finding(
&capped_source(
CAPPED_HELPER,
CAPPED_WRAPPER,
" assert!(capped_score(11) > 5);\n assert!(capped_score(10) > 5);\n",
),
CAPPED_DIFF,
)?;
assert_ne!(loose["classification"], "exposed", "{loose}");
// A second helper of the same name: the wrapper may call either.
let two_helpers = predicate_finding(
&capped_source(
&format!(
"{CAPPED_HELPER}\nmod other {{\n pub fn capped<T: PartialOrd + Copy>(value: T, cap: T) -> T {{\n if value > cap {{\n cap\n }} else {{\n value\n }}\n }}\n}}\n"
),
CAPPED_WRAPPER,
CAPPED_TESTS,
),
CAPPED_DIFF,
)?;
assert_ne!(two_helpers["classification"], "exposed", "{two_helpers}");
Ok(())
}

Expand Down
13 changes: 11 additions & 2 deletions docs/specs/RIPR-SPEC-0186-same-test-boundary-oracle-pairing.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,15 @@ parameter it forwards to the hop, and its tail is the hop call itself or
literals of distinct values (`05` and `5` are equal; an escaped string or
char literal never counts as distinct). A discarded, let-bound, transformed, branch-guarded or
computed-branch result, or a rebound forwarded parameter, keeps the
pairing missing (and RIPR-SPEC-0159 makes propagation unknown). A match
pairing missing (and RIPR-SPEC-0159 makes propagation unknown). The helper's
own propagation (#6694) reads a helper whose whole body is the tail
`if <cond> {` / `a` / `} else {` / `b` / `}` over two distinct parameters of
the helper (`if cap < value { cap } else { value }`) as returning the first
branch's parameter: the condition decides the returned value, so the
predicate has a return sink. It needs the `if` to be the only statement (an
earlier `let` could rebind a parameter), a non-unit return, the probe to be
that condition, and distinct bare parameter names; a literal, call, repeated
or non-parameter branch keeps the adjacency reading and its abstention. A match
guard that only reads a forwarded parameter (`n if n > qty =>`) is not a
rebinding; a pattern that binds it (`Some(qty) =>`) is. The row must come
from the entry call on the assertion's own line, in the assertion's own
Expand Down Expand Up @@ -324,7 +332,8 @@ relation are out of scope.
- `fixtures/predicate_pairing_mutably_borrowed_binding`
- `fixtures/predicate_pairing_newline_split_reassigned_binding`
- `crates/ripr/tests/owner_pin_execution.rs::predicate_pairing_cannot_reuse_refused_boundary_equalities`
- `crates/ripr/tests/helper_wrapper_reach.rs`
- `crates/ripr/tests/helper_wrapper_reach.rs` (including `parameter_returning_helper_is_exposed_only_through_an_exact_forwarding_wrapper`)
- `crates/ripr/src/analysis/classify/flow.rs::parameter_returning_tail_if_sinks_the_condition_only_when_whole_and_distinct`
- `fixtures/rust_wrapper_boolean_return_discarded`
- `fixtures/rust_wrapper_user_macro_guard`
- `fixtures/rust_wrapper_closure_shadowed_callee`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"edit_kind": "behavior_preserving_rewrite",
"behavior_family": "predicate_boundary",
"test_shape": "generic_helper_via_wrapper_exact_result",
"hard_case": "capped is generic and private, and the tests call only the capped_score wrapper; ripr relates them to capped by same_test_file only, does not pair the wrapper's exact pins with the boundary (same_test_pairing_missing), and reports propagation_unknown.",
"hard_case": "capped is generic and private, and the tests call only the capped_score wrapper. ripr relates them through the forwarding call chain and pairs the wrapper's exact pins with the boundary; the helper's `if cap < value { cap } else { value }` body returns its two parameters, so the condition is the returned value's sink and the row credits (#6694). Before that sink reading it read propagation_unknown.",
"truth": {
"state": "discriminated",
"method": "runtime_mutant_kill",
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 0 additions & 4 deletions fixtures/rust-verdict-corpus/missed-credit.toml
Original file line number Diff line number Diff line change
Expand Up @@ -640,10 +640,6 @@ reason = "Discriminated at runtime, abstained on purpose: a callee with a statem
case = "spec0360-ex09-call-term-second-argument"
reason = "Discriminated at runtime, abstained on purpose: a call term with a second argument is outside the folded call terms and keeps its `static_unknown` probe (RIPR-SPEC-0360 example 9). Delete this entry if multi-argument call terms become evaluable."

[[entry]]
case = "spot-cap-generic-via-wrapper"
reason = "Tests discriminate the change but ripr abstains because propagation is not established: the owner is reached through a caller that does not forward its result, or the flow is not syntactically obvious (#12773; parent #12766). Delete this entry when the row credits."

[[entry]]
case = "strsim-sorensen-dice-equal"
reason = "Compares a local rebound from the parameter (`let a = a.chars()..collect()`), so the name-only credit is withheld and the row abstains; fail-closed by design (#9197)."
Expand Down
Loading