Skip to content

Commit 5877504

Browse files
committed
Auto merge of rust-lang#11214 - y21:issue11213, r=Jarcho
check that the types are equal in `SpanlessEq::eq_expr` Fixes rust-lang#11213 changelog: [`if_same_then_else`]: don't lint for integer literals of different types
2 parents a4e64ff + e975d05 commit 5877504

File tree

3 files changed

+67
-8
lines changed

3 files changed

+67
-8
lines changed

clippy_utils/src/hir_utils.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -252,15 +252,15 @@ impl HirEqInterExpr<'_, '_, '_> {
252252
return false;
253253
}
254254

255-
if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results {
256-
if let (Some(l), Some(r)) = (
255+
if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results
256+
&& typeck_lhs.expr_ty(left) == typeck_rhs.expr_ty(right)
257+
&& let (Some(l), Some(r)) = (
257258
constant_simple(self.inner.cx, typeck_lhs, left),
258259
constant_simple(self.inner.cx, typeck_rhs, right),
259-
) {
260-
if l == r {
261-
return true;
262-
}
263-
}
260+
)
261+
&& l == r
262+
{
263+
return true;
264264
}
265265

266266
let is_eq = match (

tests/ui/if_same_then_else.rs

+41
Original file line numberDiff line numberDiff line change
@@ -214,4 +214,45 @@ mod issue_8836 {
214214
}
215215
}
216216

217+
mod issue_11213 {
218+
fn reproducer(x: bool) -> bool {
219+
if x {
220+
0_u8.is_power_of_two()
221+
} else {
222+
0_u16.is_power_of_two()
223+
}
224+
}
225+
226+
// a more obvious reproducer that shows
227+
// why the code above is problematic:
228+
fn v2(x: bool) -> bool {
229+
trait Helper {
230+
fn is_u8(&self) -> bool;
231+
}
232+
impl Helper for u8 {
233+
fn is_u8(&self) -> bool {
234+
true
235+
}
236+
}
237+
impl Helper for u16 {
238+
fn is_u8(&self) -> bool {
239+
false
240+
}
241+
}
242+
243+
// this is certainly not the same code in both branches
244+
// it returns a different bool depending on the branch.
245+
if x { 0_u8.is_u8() } else { 0_u16.is_u8() }
246+
}
247+
248+
fn do_lint(x: bool) -> bool {
249+
// but do lint if the type of the literal is the same
250+
if x {
251+
0_u8.is_power_of_two()
252+
} else {
253+
0_u8.is_power_of_two()
254+
}
255+
}
256+
}
257+
217258
fn main() {}

tests/ui/if_same_then_else.stderr

+19-1
Original file line numberDiff line numberDiff line change
@@ -108,5 +108,23 @@ LL | | bar + 1;
108108
LL | | }
109109
| |_____^
110110

111-
error: aborting due to 5 previous errors
111+
error: this `if` has identical blocks
112+
--> $DIR/if_same_then_else.rs:250:14
113+
|
114+
LL | if x {
115+
| ______________^
116+
LL | | 0_u8.is_power_of_two()
117+
LL | | } else {
118+
| |_________^
119+
|
120+
note: same as this
121+
--> $DIR/if_same_then_else.rs:252:16
122+
|
123+
LL | } else {
124+
| ________________^
125+
LL | | 0_u8.is_power_of_two()
126+
LL | | }
127+
| |_________^
128+
129+
error: aborting due to 6 previous errors
112130

0 commit comments

Comments
 (0)