Skip to content

Commit 4cb43f4

Browse files
authored
Optimize needless_bool lint (#15423)
Two optimizations have been done when checking for the context in which to apply the lint: - Checking for the mere presence of comments does not require building a `String` with the comment to then check if it is empty and discard it. - Checking for the presence of comment can be done after we have checked that we do have a `if` construct that we intend to lint instead of for every expression. changelog: none r? blyxyas
2 parents a4d4321 + 8602faa commit 4cb43f4

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

clippy_lints/src/needless_bool.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use clippy_utils::source::snippet_with_applicability;
33
use clippy_utils::sugg::Sugg;
44
use clippy_utils::{
55
SpanlessEq, get_parent_expr, higher, is_block_like, is_else_clause, is_expn_of, is_parent_stmt,
6-
is_receiver_of_method_call, peel_blocks, peel_blocks_with_stmt, span_extract_comment, sym,
6+
is_receiver_of_method_call, peel_blocks, peel_blocks_with_stmt, span_contains_comment, sym,
77
};
88
use rustc_ast::ast::LitKind;
99
use rustc_errors::Applicability;
@@ -128,14 +128,13 @@ fn condition_needs_parentheses(e: &Expr<'_>) -> bool {
128128
impl<'tcx> LateLintPass<'tcx> for NeedlessBool {
129129
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
130130
use self::Expression::{Bool, RetBool};
131-
if e.span.from_expansion() || !span_extract_comment(cx.tcx.sess.source_map(), e.span).is_empty() {
132-
return;
133-
}
134-
if let Some(higher::If {
135-
cond,
136-
then,
137-
r#else: Some(r#else),
138-
}) = higher::If::hir(e)
131+
if !e.span.from_expansion()
132+
&& let Some(higher::If {
133+
cond,
134+
then,
135+
r#else: Some(else_expr),
136+
}) = higher::If::hir(e)
137+
&& !span_contains_comment(cx.tcx.sess.source_map(), e.span)
139138
{
140139
let reduce = |ret, not| {
141140
let mut applicability = Applicability::MachineApplicable;
@@ -167,7 +166,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBool {
167166
applicability,
168167
);
169168
};
170-
if let Some((a, b)) = fetch_bool_block(then).and_then(|a| Some((a, fetch_bool_block(r#else)?))) {
169+
if let Some((a, b)) = fetch_bool_block(then).and_then(|a| Some((a, fetch_bool_block(else_expr)?))) {
171170
match (a, b) {
172171
(RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
173172
span_lint(
@@ -193,7 +192,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBool {
193192
}
194193
}
195194
if let Some((lhs_a, a)) = fetch_assign(then)
196-
&& let Some((lhs_b, b)) = fetch_assign(r#else)
195+
&& let Some((lhs_b, b)) = fetch_assign(else_expr)
197196
&& SpanlessEq::new(cx).eq_expr(lhs_a, lhs_b)
198197
{
199198
let mut applicability = Applicability::MachineApplicable;

0 commit comments

Comments
 (0)