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
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[[extend]]
id = "RIPR-SPEC-0231"
tests = [
"crates/ripr/tests/matches_bool_equality_strength.rs::a_matches_compared_with_true_is_only_as_strong_as_its_pattern",
]
code = [
"crates/ripr/src/analysis/extract/oracles/pattern_admission.rs",
]
2 changes: 2 additions & 0 deletions changelog.d/16290-matches-bool-equality-strength.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<!-- section: Fixed -->
- `assert_eq!(matches!(value, PATTERN), true)` in Rust tests is now only as strong as its pattern, as `assert!(matches!(value, PATTERN))` already was. A wildcard, side-only (`Some(_)`) or several-value pattern no longer makes a change read `exposed` when it is written as an equality with `true`; a pattern that pins one value stays exact (#16290).
2 changes: 1 addition & 1 deletion crates/ripr/src/analysis/extract/oracles/bool_operands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ fn literal_spelling_value(side: &str) -> Option<bool> {
/// The expression inside a block that holds only that expression
/// (`{ r == Err(E::Bad) }`): the first `{` closes at the last `}` and no
/// top-level `;` ends a statement before it.
fn unwrap_block(text: &str) -> Option<&str> {
pub(super) fn unwrap_block(text: &str) -> Option<&str> {
let text = text.trim();
let inner = text.strip_prefix('{')?.strip_suffix('}')?;
let masked = mask_comments_and_strings(inner);
Expand Down
85 changes: 80 additions & 5 deletions crates/ripr/src/analysis/extract/oracles/pattern_admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,13 @@ use std::collections::{BTreeMap, BTreeSet};
use crate::analysis::extract::mask_comments_and_strings;
use crate::domain::{OracleKind, OracleStrength};

use super::arguments::{complete_macro_arguments, parenthesized_contents};
use super::arguments::{
AssertionComparison, assertion_comparison, complete_macro_arguments, parenthesized_contents,
};
use super::classify::OracleClassification;
use super::patterns::{
PatternPolarity, pattern_comparison_polarity, pattern_operand_negations, transparent_operand,
};

/// The `Option` and `Result` constructors, which only say which side a value
/// is on.
Expand Down Expand Up @@ -323,10 +328,12 @@ fn pattern_pair_classification(
reading_classification(read_pattern(pattern, decls), guarded)
}

/// The pattern operand of an `assert_matches!` / `debug_assert_matches!`, or
/// of a `matches!` that is the whole condition of `assert!`, `debug_assert!`,
/// `prop_assert!` or `ensure!`. A compound condition is not a pattern
/// assertion.
/// The pattern operand of an `assert_matches!` / `debug_assert_matches!`, of
/// a `matches!` that is the whole condition of `assert!`, `debug_assert!`,
/// `prop_assert!` or `ensure!`, or of a `matches!` an equality macro
/// compares with positive polarity (`assert_eq!(matches!(..), true)`,
/// `assert_ne!(false, matches!(..))`; #16290). A compound condition is not a
/// pattern assertion.
fn asserted_pattern(line: &str) -> Option<(String, String)> {
let pair = |arguments: Vec<String>| match arguments.as_slice() {
[scrutinee, pattern] => Some((scrutinee.clone(), pattern.clone())),
Expand All @@ -338,6 +345,20 @@ fn asserted_pattern(line: &str) -> Option<(String, String)> {
{
return pair(arguments);
}
// RIPR-SPEC-0231 rule 1 owns the polarity: only `== true`, `!= false`
// and their negated-literal spellings assert the pattern. Any other
// comparison is capped at the inequality strength before this reading.
if pattern_comparison_polarity(line) == Some(PatternPolarity::Positive)
&& let Some(AssertionComparison::Operands { left, right, .. }) = assertion_comparison(line)
{
let operand = [left, right]
.into_iter()
.find(|operand| pattern_operand_negations(operand) == Some(0))?;
return pair(complete_macro_arguments(
transparent_operand(&operand),
"matches!",
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
)?);
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
}
let condition = ["assert!", "debug_assert!", "prop_assert!", "ensure!"]
.into_iter()
.find_map(|name| complete_macro_arguments(line, name)?.into_iter().next())?;
Expand Down Expand Up @@ -1426,6 +1447,51 @@ mod tests {
RelationalCheck,
Weak,
),
// #16290: an equality macro that compares a whole `matches!` with
// a boolean literal at positive polarity asserts the pattern, in
// either operand order and through parentheses.
(
"assert_eq!(matches!(check(5), Ok(_)), true)",
SmokeOnly,
Smoke,
),
(
"assert_eq!(true, matches!(score(2), 4 | 5))",
RelationalCheck,
Weak,
),
(
"assert_eq!((matches!(value, _)), (true))",
RelationalCheck,
Weak,
),
(
"assert_ne!(matches!(value, _), false)",
RelationalCheck,
Weak,
),
(
"debug_assert_eq!(matches!(check(20), Err(_)), true)",
BroadError,
Weak,
),
// Comments, groups and a block holding only the operand are
// transparent to the compared pattern.
(
"assert_eq!((matches!(score(2), 4 | 5)) /* either */, true)",
RelationalCheck,
Weak,
),
(
"assert_eq!({ matches!(score(2), 4 | 5) }, true)",
RelationalCheck,
Weak,
),
(
"assert_eq!(true, /* note */ { (matches!(value, _)) })",
RelationalCheck,
Weak,
),
];
for (text, kind, strength) in weakened {
let actual = pattern_assertion_classification(text);
Expand Down Expand Up @@ -1476,6 +1542,15 @@ mod tests {
// a guard that pins a value decides as before (decision 7).
"assert!(matches!(pair(), (3, 4 | 5)))",
"assert!(matches!(value, 4 | 5 if value == 4))",
// A pinned compared pattern keeps the chain's reading, and a
// comparison that is not positive is rule 1's, not this one's.
"assert_eq!(matches!(check(5), Ok(5)), true)",
"assert_eq!(matches!(check(5), Ok(_)), false)",
"assert_ne!(matches!(check(5), Ok(_)), true)",
"assert_eq!(matches!(check(5), Ok(_)), flag)",
"assert_eq!({ matches!(check(5), Ok(_)) } /* no */, false)",
// A block with a statement before its tail is not transparent.
"assert_eq!({ let _ = 1; matches!(value, _) }, true)",
] {
let actual = pattern_assertion_classification(text);
if actual.is_some() {
Expand Down
36 changes: 33 additions & 3 deletions crates/ripr/src/analysis/extract/oracles/patterns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1149,9 +1149,10 @@ fn resolve_pattern_comparison(left: &str, right: &str, not_equal: bool) -> Patte

/// How many negations (`!` prefixes and `.not()` calls) wrap one complete
/// `matches!` or `assert_matches!` operand, or `None` when the operand is not
/// such a pattern.
/// such a pattern. Comments, grouping parentheses and a block holding only the
/// operand are transparent (`(matches!(..)) /* note */`, `{ matches!(..) }`).
pub(super) fn pattern_operand_negations(operand: &str) -> Option<usize> {
let mut text = unwrap_parentheses(operand.trim());
let mut text = transparent_operand(operand);
let mut negations = 0;
loop {
if is_complete_macro_invocation(text, "matches!")
Expand All @@ -1160,11 +1161,40 @@ pub(super) fn pattern_operand_negations(operand: &str) -> Option<usize> {
return Some(negations);
}
let rest = text.strip_prefix('!').or_else(|| strip_not_call(text))?;
text = unwrap_parentheses(rest.trim());
text = transparent_operand(rest);
negations += 1;
}
}

/// `operand` without the comments around it, the parentheses that group it,
/// or a block that holds only it, repeated until none is left
/// (`{ (matches!(..)) /* note */ }` is `matches!(..)`; #16290).
pub(super) fn transparent_operand(operand: &str) -> &str {
let mut text = operand.trim();
loop {
let unwrapped = unwrap_parentheses(without_edge_comments(text));
let next = super::bool_operands::unwrap_block(unwrapped).unwrap_or(unwrapped);
if next.len() == text.len() {
return text;
}
text = next;
}
}

/// `text` without comments before its first or after its last code byte.
fn without_edge_comments(text: &str) -> &str {
let masked = mask_comments_and_strings(text);
let bytes = masked.as_bytes();
let Some(start) = bytes.iter().position(|byte| !byte.is_ascii_whitespace()) else {
return text.trim();
};
let end = bytes
.iter()
.rposition(|byte| !byte.is_ascii_whitespace())
.map_or(start, |last| last + 1);
text.get(start..end).unwrap_or(text).trim()
}

/// The receiver of a trailing `.not()` call (`std::ops::Not`).
pub(super) fn strip_not_call(text: &str) -> Option<&str> {
text.trim_end()
Expand Down
18 changes: 12 additions & 6 deletions crates/ripr/src/analysis/seam_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -801,7 +801,9 @@ pub(crate) struct CachedSeamLimitInfo {
/// weak, not exact (#16286).
/// `1.201`: a renamed call in a test's own module file (`src/tests.rs`) reads
/// the enclosing module files, so a nested-block rename settles there too (#16277).
pub(crate) const CACHE_SCHEMA_VERSION: &str = "1.201";
/// `1.202`: `assert_eq!(matches!(..), true)` reads only as strong as its
/// pattern (#16290).
pub(crate) const CACHE_SCHEMA_VERSION: &str = "1.202";
/// `0.2` → `0.3`: same semantic transition as the outer cache (#3273 /
/// #3286) — sharded entries derive from the same facts and cannot bypass
/// the outer generation bump.
Expand Down Expand Up @@ -1040,7 +1042,8 @@ pub(crate) const CACHE_SCHEMA_VERSION: &str = "1.201";
/// `0.201`: same include-reading wrapper forwarding as full `1.199` (#10357).
/// `0.202`: same or-pattern oracle reading as full `1.200` (#16286).
/// `0.203`: same file-module nested-block rename as full `1.201` (#16277).
const SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION: &str = "0.203";
/// `0.204`: same compared-pattern oracle reading as full `1.202` (#16290).
const SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION: &str = "0.204";

/// Compact-classified seam cache schema. This cache stores the same
/// `ClassifiedSeam` envelope shape as the full repo exposure cache, but
Expand Down Expand Up @@ -1281,7 +1284,8 @@ const SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION: &str = "0.203";
/// `0.201`: same include-reading wrapper forwarding as full `1.199` (#10357).
/// `0.202`: same or-pattern oracle reading as full `1.200` (#16286).
/// `0.203`: same file-module nested-block rename as full `1.201` (#16277).
pub(crate) const COMPACT_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION: &str = "0.203";
/// `0.204`: same compared-pattern oracle reading as full `1.202` (#16290).
pub(crate) const COMPACT_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION: &str = "0.204";

/// Compact class-count cache used by repo badge rendering. It keys off
/// the same workspace state as the full fact cache, but stores only
Expand Down Expand Up @@ -5890,7 +5894,8 @@ mod tests {
// 1.198 -> 1.199: include_str!/include_bytes! wrappers forward their helper result (#10357).
// 1.199 -> 1.200: matches! or-patterns of values read weak (#16286).
// 1.200 -> 1.201: nested-block renames settle in a test's own module file (#16277).
assert_eq!(CACHE_SCHEMA_VERSION, "1.201");
// 1.201 -> 1.202: assert_eq!(matches!(..), true) follows its pattern (#16290).
assert_eq!(CACHE_SCHEMA_VERSION, "1.202");
// 1.168 -> 1.169: plain `assert_eq!` literal withhold in the audit (#13005).
// 0.12 -> 0.13 through 0.14 / 0.15 / 0.16 / 0.17 / 0.18: same
// #3731 semantic transition as the outer classified-seam cache,
Expand Down Expand Up @@ -6069,8 +6074,9 @@ mod tests {
// 0.200 -> 0.201: same include-reading wrapper forwarding as full 1.199 (#10357).
// 0.201 -> 0.202: same or-pattern oracle reading as full 1.200 (#16286).
// 0.202 -> 0.203: same file-module nested-block rename as full 1.201 (#16277).
assert_eq!(SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION, "0.203");
assert_eq!(COMPACT_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION, "0.203");
// 0.203 -> 0.204: same compared-pattern oracle reading as full 1.202 (#16290).
assert_eq!(SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION, "0.204");
assert_eq!(COMPACT_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION, "0.204");
// 0.170 -> 0.171: same plain `assert_eq!` literal withhold as full 1.169 (#13005).
}

Expand Down
2 changes: 1 addition & 1 deletion crates/ripr/tests/lsp_lifecycle/gap_corpus_currentness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::path::{Path, PathBuf};
mod fixture_git;

const GAP: &str = "gap:54c07ec8eeadf203";
const CURRENT_CORPUS_CACHE_SCHEMA_VERSION: &str = "1.201";
const CURRENT_CORPUS_CACHE_SCHEMA_VERSION: &str = "1.202";
const SEAM: &str = "67f9714ba37b3967";
const SOURCE: &str = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 {\n if amount >= threshold {\n amount - 10\n } else {\n amount\n }\n}\n";
const PRICING: &str = "use ordinary_shop::discounted_total;\n#[test]\nfn below_threshold_has_no_discount() {\n assert_eq!(discounted_total(50, 100), 50);\n}\n#[test]\nfn above_threshold_discounts() {\n assert_eq!(discounted_total(1_000, 100), 990);\n}\n";
Expand Down
119 changes: 119 additions & 0 deletions crates/ripr/tests/matches_bool_equality_strength.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
//! `assert_eq!(matches!(x, PATTERN), true)` asserts the pattern exactly as
//! `assert!(matches!(x, PATTERN))` does, so it is only as strong as its
//! pattern (#16290, RIPR-SPEC-0231 rules 1 and 3). The changed boundary moves
//! `discount(100)` from 100 to 90, so an unpinned pattern passes on both
//! versions and must not read `exposed`.

use ripr::{CheckInput, ExposureClass, Mode, OutputFormat, ProbeFamily, check_workspace};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};

const MANIFEST: &str =
"[package]\nname = \"demo\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[workspace]\n";

const LIB: &str = "pub fn discount(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n";

const 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 pub fn discount(amount: i32) -> i32 {\n- if amount > 100 { amount - 10 } else { amount }\n+ if amount >= 100 { amount - 10 } else { amount }\n }\n";

struct Fixture(PathBuf);

impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}

/// The class of the changed predicate when the one boundary test in
/// `tests/pin.rs` has `body`.
fn class_with(body: &str) -> Result<ExposureClass, String> {
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
let root = std::env::temp_dir().join(format!(
"ripr-matches-bool-equality-{}-{}",
std::process::id(),
SEQUENCE.fetch_add(1, Ordering::Relaxed)
));
// `create_dir` refuses a path that already exists, a symlink included,
// so the fixture never writes through a directory it did not create.
std::fs::create_dir(&root)
.map_err(|error| format!("create fixture root {}: {error}", root.display()))?;
let fixture = Fixture(root);
let test = format!("#[test]\nfn discount_boundary() {{\n {body}\n}}\n");
for (relative, text) in [
("Cargo.toml", MANIFEST),
("src/lib.rs", LIB),
("tests/pin.rs", test.as_str()),
("diff.patch", DIFF),
] {
let path = fixture.0.join(relative);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|error| format!("create directory {}: {error}", parent.display()))?;
}
std::fs::write(&path, text)
.map_err(|error| format!("write file {}: {error}", path.display()))?;
}
let output = check_workspace(CheckInput {
root: fixture.0.clone(),
diff_file: Some(fixture.0.join("diff.patch")),
mode: Mode::Ready,
format: OutputFormat::Json,
include_unchanged_tests: true,
..CheckInput::default()
})?;
let finding = output
.findings
.into_iter()
.find(|finding| finding.probe.family == ProbeFamily::Predicate)
.ok_or("missing changed predicate probe")?;
assert!(
finding
.related_tests
.iter()
.any(|related| related.name == "discount_boundary"),
"the boundary test must be the related test: {finding:?}"
);
Ok(finding.class)
}

#[test]
fn a_matches_compared_with_true_is_only_as_strong_as_its_pattern() -> Result<(), String> {
// Controls: a pinned pattern stays exact in both operand orders, as the
// `assert!` spelling does.
for body in [
"assert!(matches!(demo::discount(100), 90));",
"assert_eq!(matches!(demo::discount(100), 90), true);",
"assert_eq!(true, matches!(demo::discount(100), 90));",
"assert_eq!({ matches!(demo::discount(100), 90) } /* pinned */, true);",
] {
assert_eq!(class_with(body)?, ExposureClass::Exposed, "{body}");
}
// The `assert!` spelling of an unpinned pattern is already weak.
assert_eq!(
class_with("assert!(matches!(demo::discount(100), _));")?,
ExposureClass::WeaklyExposed
);
for body in [
"assert_eq!(matches!(demo::discount(100), _), true);",
"assert_eq!(matches!(Some(demo::discount(100)), Some(_)), true);",
"assert_eq!(matches!(demo::discount(100), 90 | 100), true);",
"assert_eq!(true, matches!(demo::discount(100), 90 | 100));",
"assert_eq!((matches!(demo::discount(100), _)), (true));",
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
"assert_ne!(matches!(demo::discount(100), _), false);",
// Comments, groups and a block holding only the operand are
// transparent.
"assert_eq!((matches!(demo::discount(100), 90 | 100)) /* either */, true);",
"assert_eq!({ matches!(demo::discount(100), 90 | 100) }, true);",
// `assert_ne!` stays an inequality macro whatever the literal, so
// even a pinned pattern is capped there (rule 1).
"assert_ne!(matches!(demo::discount(100), 90), false);",
// A comparison that excludes the pattern stays capped (rule 1).
"assert_eq!(matches!(demo::discount(100), 90), false);",
] {
assert_eq!(
class_with(body)?,
ExposureClass::WeaklyExposed,
"a compared pattern reads as its pattern: {body}"
);
}
Ok(())
}
4 changes: 2 additions & 2 deletions docs/OUTPUT_SCHEMA.md
Original file line number Diff line number Diff line change
Expand Up @@ -21159,7 +21159,7 @@ top-level `source_subject`:

- `digest_algorithm`: always `"sha256"`.
- `corpus` (additive, full Rust inventory only): the analysis-owned
`{ "scope": "rust_workspace", "cache_schema_version": "1.201",
`{ "scope": "rust_workspace", "cache_schema_version": "1.202",
"files_content_hash": "<16 lowercase hex digits>" }` from the actual
classified inventory cache key, including both production and test Rust
files after the existing generated-file exclusions. Repo-exposure producers
Expand Down Expand Up @@ -21963,7 +21963,7 @@ targeted-rerun receipt shape:
"recomputation_reasons": ["selected_test_scope_recomputed"],
"invalidation_status": "not_available",
"input_fingerprint": {
"schema_version": "1.201",
"schema_version": "1.202",
"analyzer_version": "0.11.0+0123456789abcdef0123456789abcdef01234567+languages:rust=1,typescript=1,python=1,perl=0",
"workspace_root_hash": "…",
"files_content_hash": "…",
Expand Down
Loading
Loading