Skip to content

Commit

Permalink
check_manual_pattern_char_comparison: avoid indexing and increase rea…
Browse files Browse the repository at this point in the history
…dability
  • Loading branch information
AurelienFT committed Jun 7, 2024
1 parent c68a08a commit 48f9915
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions clippy_lints/src/string_patterns.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::cmp::Ordering;
use std::ops::ControlFlow;

use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
Expand All @@ -18,19 +17,19 @@ use rustc_span::{sym, Span};

declare_clippy_lint! {
/// ### What it does
/// Checks for manual char comparison in string patterns
/// Checks for manual `char` comparison in string patterns
///
/// ### Why is this bad?
/// This can be written more concisely using a `char` or an array of `char`.
/// This is more readable and more optimized when comparing to only one `char`.
///
/// ### Example
/// ```no_run
/// "Hello World !".trim_end_matches(|c: char| c == '.' || c == ',' || c == '!' || c == '?');
/// "Hello World!".trim_end_matches(|c| c == '.' || c == ',' || c == '!' || c == '?');
/// ```
/// Use instead:
/// ```no_run
/// "Hello World !".trim_end_matches(['.', ',', '!', '?']);
/// "Hello World!".trim_end_matches(['.', ',', '!', '?']);
/// ```
#[clippy::version = "1.80.0"]
pub MANUAL_PATTERN_CHAR_COMPARISON,
Expand Down Expand Up @@ -124,10 +123,9 @@ fn get_char_span<'tcx>(cx: &'_ LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Optio
}

fn check_manual_pattern_char_comparison(cx: &LateContext<'_>, method_arg: &Expr<'_>) {
let applicability = Applicability::MachineApplicable;
if let ExprKind::Closure(closure) = method_arg.kind
&& let body = cx.tcx.hir().body(closure.body)
&& let PatKind::Binding(_, binding, ..) = body.params[0].pat.kind
&& let Some(PatKind::Binding(_, binding, ..)) = body.params.first().map(|p| p.pat.kind)
{
let mut set_char_spans: Vec<Span> = Vec::new();

Expand Down Expand Up @@ -185,27 +183,25 @@ fn check_manual_pattern_char_comparison(cx: &LateContext<'_>, method_arg: &Expr<
MANUAL_PATTERN_CHAR_COMPARISON,
method_arg.span,
"this manual char comparison can be written more succinctly",
|diag| match set_char_spans.len().cmp(&1) {
Ordering::Equal => {
|diag| {
if let [set_char_span] = set_char_spans[..] {
diag.span_suggestion(
method_arg.span,
"consider using a `char`",
snippet(cx, set_char_spans[0], "c"),
applicability,
snippet(cx, set_char_span, "c"),
Applicability::MachineApplicable,
);
},
Ordering::Greater => {
} else {
diag.span_suggestion(
method_arg.span,
"consider using an array of `char`",
format!(
"[{}]",
set_char_spans.into_iter().map(|span| snippet(cx, span, "c")).join(", ")
),
applicability,
Applicability::MachineApplicable,
);
},
Ordering::Less => {},
}
},
);
}
Expand Down

0 comments on commit 48f9915

Please sign in to comment.