Skip to content

Commit c68a08a

Browse files
committed
Improve get_char_span with a more compact version
1 parent 0b874bd commit c68a08a

File tree

1 file changed

+12
-25
lines changed

1 file changed

+12
-25
lines changed

clippy_lints/src/string_patterns.rs

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@ use std::cmp::Ordering;
22
use std::ops::ControlFlow;
33

44
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
5+
use clippy_utils::eager_or_lazy::switch_to_eager_eval;
56
use clippy_utils::macros::matching_root_macro_call;
67
use clippy_utils::path_to_local_id;
7-
use clippy_utils::source::{snippet_opt, str_literal_to_char_literal};
8+
use clippy_utils::source::{snippet, str_literal_to_char_literal};
89
use clippy_utils::visitors::{for_each_expr, Descend};
910
use itertools::Itertools;
1011
use rustc_ast::{BinOpKind, LitKind};
1112
use rustc_errors::Applicability;
12-
use rustc_hir::{Expr, ExprKind, PatKind, QPath};
13+
use rustc_hir::{Expr, ExprKind, PatKind};
1314
use rustc_lint::{LateContext, LateLintPass};
1415
use rustc_middle::ty;
1516
use rustc_session::declare_lint_pass;
@@ -112,24 +113,13 @@ fn check_single_char_pattern_lint(cx: &LateContext<'_>, arg: &Expr<'_>) {
112113
}
113114

114115
fn get_char_span<'tcx>(cx: &'_ LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<Span> {
115-
if !cx.typeck_results().expr_ty_adjusted(expr).is_char() || expr.span.from_expansion() {
116-
return None;
117-
}
118-
match expr.kind {
119-
ExprKind::Lit(lit) if let LitKind::Char(_) = lit.node => Some(lit.span),
120-
ExprKind::Path(QPath::Resolved(_, path)) => {
121-
if path.segments.len() == 1 {
122-
let segment = &path.segments[0];
123-
if segment.args.is_none() {
124-
Some(segment.ident.span)
125-
} else {
126-
None
127-
}
128-
} else {
129-
None
130-
}
131-
},
132-
_ => None,
116+
if cx.typeck_results().expr_ty_adjusted(expr).is_char()
117+
&& !expr.span.from_expansion()
118+
&& switch_to_eager_eval(cx, expr)
119+
{
120+
Some(expr.span)
121+
} else {
122+
None
133123
}
134124
}
135125

@@ -200,7 +190,7 @@ fn check_manual_pattern_char_comparison(cx: &LateContext<'_>, method_arg: &Expr<
200190
diag.span_suggestion(
201191
method_arg.span,
202192
"consider using a `char`",
203-
snippet_opt(cx, set_char_spans[0]).unwrap(),
193+
snippet(cx, set_char_spans[0], "c"),
204194
applicability,
205195
);
206196
},
@@ -210,10 +200,7 @@ fn check_manual_pattern_char_comparison(cx: &LateContext<'_>, method_arg: &Expr<
210200
"consider using an array of `char`",
211201
format!(
212202
"[{}]",
213-
set_char_spans
214-
.into_iter()
215-
.map(|span| snippet_opt(cx, span).unwrap())
216-
.join(", ")
203+
set_char_spans.into_iter().map(|span| snippet(cx, span, "c")).join(", ")
217204
),
218205
applicability,
219206
);

0 commit comments

Comments
 (0)