Skip to content

Commit 54978a5

Browse files
committed
Auto merge of #3680 - g-bartoszek:needless-bool-else-if-brackets, r=oli-obk
needless bool lint suggestion is wrapped in brackets if it is an "els… …e" clause of an "if-else" statement
2 parents 1838bfe + 34785a1 commit 54978a5

File tree

3 files changed

+43
-2
lines changed

3 files changed

+43
-2
lines changed

clippy_lints/src/needless_bool.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
7272
let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
7373
let snip = if not { !snip } else { snip };
7474

75-
let hint = if ret {
75+
let mut hint = if ret {
7676
format!("return {}", snip)
7777
} else {
7878
snip.to_string()
7979
};
8080

81+
if parent_node_is_if_expr(&e, &cx) {
82+
hint = format!("{{ {} }}", hint);
83+
}
84+
8185
span_lint_and_sugg(
8286
cx,
8387
NEEDLESS_BOOL,
@@ -119,6 +123,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
119123
}
120124
}
121125

126+
fn parent_node_is_if_expr<'a, 'b>(expr: &Expr, cx: &LateContext<'a, 'b>) -> bool {
127+
let parent_id = cx.tcx.hir().get_parent_node(expr.id);
128+
let parent_node = cx.tcx.hir().get(parent_id);
129+
130+
if let rustc::hir::Node::Expr(e) = parent_node {
131+
if let ExprKind::If(_, _, _) = e.node {
132+
return true;
133+
}
134+
}
135+
136+
false
137+
}
138+
122139
#[derive(Copy, Clone)]
123140
pub struct BoolComparison;
124141

tests/ui/needless_bool.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,3 +141,16 @@ fn needless_bool3(x: bool) {
141141
if x == true {};
142142
if x == false {};
143143
}
144+
145+
fn needless_bool_in_the_suggestion_wraps_the_predicate_of_if_else_statement_in_brackets() {
146+
let b = false;
147+
let returns_bool = || false;
148+
149+
let x = if b {
150+
true
151+
} else if returns_bool() {
152+
false
153+
} else {
154+
true
155+
};
156+
}

tests/ui/needless_bool.stderr

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,5 +136,16 @@ error: equality checks against false can be replaced by a negation
136136
LL | if x == false {};
137137
| ^^^^^^^^^^ help: try simplifying it as shown: `!x`
138138

139-
error: aborting due to 15 previous errors
139+
error: this if-then-else expression returns a bool literal
140+
--> $DIR/needless_bool.rs:151:12
141+
|
142+
LL | } else if returns_bool() {
143+
| ____________^
144+
LL | | false
145+
LL | | } else {
146+
LL | | true
147+
LL | | };
148+
| |_____^ help: you can reduce it to: `{ !returns_bool() }`
149+
150+
error: aborting due to 16 previous errors
140151

0 commit comments

Comments
 (0)