Skip to content

Commit 65778fa

Browse files
committed
fix a false-positive inside const fn in comparison_chain
1 parent 79b9eb5 commit 65778fa

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

clippy_lints/src/comparison_chain.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use clippy_utils::diagnostics::span_lint_and_help;
22
use clippy_utils::ty::implements_trait;
33
use clippy_utils::{get_trait_def_id, if_sequence, is_else_clause, paths, SpanlessEq};
4-
use rustc_hir::{BinOpKind, Expr, ExprKind};
4+
use rustc_hir::{BinOpKind, Expr, ExprKind, Node};
55
use rustc_lint::{LateContext, LateLintPass};
66
use rustc_session::{declare_lint_pass, declare_tool_lint};
77

@@ -64,6 +64,10 @@ impl<'tcx> LateLintPass<'tcx> for ComparisonChain {
6464
return;
6565
}
6666

67+
if parent_node_is_if_const_fn(cx, expr) {
68+
return;
69+
}
70+
6771
// Check that there exists at least one explicit else condition
6872
let (conds, _) = if_sequence(expr);
6973
if conds.len() < 2 {
@@ -123,3 +127,11 @@ impl<'tcx> LateLintPass<'tcx> for ComparisonChain {
123127
fn kind_is_cmp(kind: BinOpKind) -> bool {
124128
matches!(kind, BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Eq)
125129
}
130+
131+
fn parent_node_is_if_const_fn(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
132+
match cx.tcx.hir().find(cx.tcx.hir().get_parent_item(expr.hir_id)) {
133+
Some(Node::Item(item)) => rustc_mir::const_eval::is_const_fn(cx.tcx, item.def_id.to_def_id()),
134+
Some(Node::ImplItem(impl_item)) => rustc_mir::const_eval::is_const_fn(cx.tcx, impl_item.def_id.to_def_id()),
135+
_ => false,
136+
}
137+
}

tests/ui/comparison_chain.rs

+28
Original file line numberDiff line numberDiff line change
@@ -203,4 +203,32 @@ mod issue_5212 {
203203
}
204204
}
205205

206+
enum Sign {
207+
Negative,
208+
Positive,
209+
Zero,
210+
}
211+
212+
impl Sign {
213+
const fn sign_i8(n: i8) -> Self {
214+
if n == 0 {
215+
Sign::Zero
216+
} else if n > 0 {
217+
Sign::Positive
218+
} else {
219+
Sign::Negative
220+
}
221+
}
222+
}
223+
224+
const fn sign_i8(n: i8) -> Sign {
225+
if n == 0 {
226+
Sign::Zero
227+
} else if n > 0 {
228+
Sign::Positive
229+
} else {
230+
Sign::Negative
231+
}
232+
}
233+
206234
fn main() {}

0 commit comments

Comments
 (0)