Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

needless bool lint suggestion is wrapped in brackets if it is an "els… #3680

Merged
merged 4 commits into from
Jan 21, 2019
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
19 changes: 18 additions & 1 deletion clippy_lints/src/needless_bool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
let snip = if not { !snip } else { snip };

let hint = if ret {
let mut hint = if ret {
format!("return {}", snip)
} else {
snip.to_string()
};

if parent_node_is_if_expr(&e, &cx) {
hint = format!("{{ {} }}", hint);
}

span_lint_and_sugg(
cx,
NEEDLESS_BOOL,
Expand Down Expand Up @@ -119,6 +123,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
}
}

fn parent_node_is_if_expr<'a, 'b>(expr: &Expr, cx: &LateContext<'a, 'b>) -> bool {
let parent_id = cx.tcx.hir().get_parent_node(expr.id);
let parent_node = cx.tcx.hir().get(parent_id);

if let rustc::hir::Node::Expr(e) = parent_node {
if let ExprKind::If(_, _, _) = e.node {
return true;
}
}

false
}

#[derive(Copy, Clone)]
pub struct BoolComparison;

Expand Down
13 changes: 13 additions & 0 deletions tests/ui/needless_bool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,16 @@ fn needless_bool3(x: bool) {
if x == true {};
if x == false {};
}

fn needless_bool_in_the_suggestion_wraps_the_predicate_of_if_else_statement_in_brackets() {
let b = false;
let returns_bool = || false;

let x = if b {
true
} else if returns_bool() {
false
} else {
true
};
}
13 changes: 12 additions & 1 deletion tests/ui/needless_bool.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -136,5 +136,16 @@ error: equality checks against false can be replaced by a negation
LL | if x == false {};
| ^^^^^^^^^^ help: try simplifying it as shown: `!x`

error: aborting due to 15 previous errors
error: this if-then-else expression returns a bool literal
--> $DIR/needless_bool.rs:151:12
|
LL | } else if returns_bool() {
| ____________^
LL | | false
LL | | } else {
LL | | true
LL | | };
| |_____^ help: you can reduce it to: `{ !returns_bool() }`

error: aborting due to 16 previous errors