Skip to content

Commit a07322d

Browse files
authored
Use parentheses in the assert_eq macros to avoid chained comparison operators error (rust-lang#1202)
1 parent 25dfce5 commit a07322d

File tree

3 files changed

+35
-4
lines changed

3 files changed

+35
-4
lines changed

library/std/src/lib.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,20 +63,24 @@ macro_rules! assert {
6363
#[macro_export]
6464
macro_rules! assert_eq {
6565
($left:expr, $right:expr $(,)?) => ({
66-
assert!($left == $right);
66+
// Add parentheses around the operands to avoid a "comparison operators
67+
// cannot be chained" error, but exclude the parentheses in the message
68+
kani::assert(($left) == ($right), concat!("assertion failed: ", stringify!($left == $right)));
6769
});
6870
($left:expr, $right:expr, $($arg:tt)+) => ({
69-
assert!($left == $right, $($arg)+);
71+
assert!(($left) == ($right), $($arg)+);
7072
});
7173
}
7274

7375
#[macro_export]
7476
macro_rules! assert_ne {
7577
($left:expr, $right:expr $(,)?) => ({
76-
assert!($left != $right);
78+
// Add parentheses around the operands to avoid a "comparison operators
79+
// cannot be chained" error, but exclude the parentheses in the message
80+
kani::assert(($left) != ($right), concat!("assertion failed: ", stringify!($left != $right)));
7781
});
7882
($left:expr, $right:expr, $($arg:tt)+) => ({
79-
assert!($left != $right, $($arg)+);
83+
assert!(($left) != ($right), $($arg)+);
8084
});
8185
}
8286

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Status: SUCCESS\
2+
Description: "assertion failed: x > 3 == true"
3+
4+
Status: SUCCESS\
5+
Description: "assertion failed: x == 1 == false"
6+
7+
Status: SUCCESS\
8+
Description: "assertion failed: x < 10 != false"
9+
10+
Status: FAILURE\
11+
Description: "assertion failed: x == 7 != false"
12+
13+
VERIFICATION:- FAILED
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Copyright Kani Contributors
2+
// SPDX-License-Identifier: Apache-2.0 OR MIT
3+
4+
// This test checks that chained operators work with Kani's overridden assert_eq
5+
// macros
6+
7+
#[kani::proof]
8+
fn check_chained_operators() {
9+
let x = 5;
10+
assert_eq!(x > 3, true);
11+
debug_assert_eq!(x == 1, false);
12+
assert_ne!(x < 10, false);
13+
debug_assert_ne!(x == 7, false); // fails
14+
}

0 commit comments

Comments
 (0)