]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/single_char_pattern.rs
Auto merge of #7546 - mgeier:patch-1, r=giraffate
[rust.git] / clippy_lints / src / methods / single_char_pattern.rs
1 use super::utils::get_hint_if_single_char_arg;
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir as hir;
6 use rustc_lint::LateContext;
7 use rustc_middle::ty;
8 use rustc_span::symbol::Symbol;
9
10 use super::SINGLE_CHAR_PATTERN;
11
12 const PATTERN_METHODS: [(&str, usize); 19] = [
13     ("contains", 1),
14     ("starts_with", 1),
15     ("ends_with", 1),
16     ("find", 1),
17     ("rfind", 1),
18     ("split", 1),
19     ("rsplit", 1),
20     ("split_terminator", 1),
21     ("rsplit_terminator", 1),
22     ("splitn", 2),
23     ("rsplitn", 2),
24     ("matches", 1),
25     ("rmatches", 1),
26     ("match_indices", 1),
27     ("rmatch_indices", 1),
28     ("strip_prefix", 1),
29     ("strip_suffix", 1),
30     ("trim_start_matches", 1),
31     ("trim_end_matches", 1),
32 ];
33
34 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
35 pub(super) fn check(cx: &LateContext<'_>, _expr: &hir::Expr<'_>, method_name: Symbol, args: &[hir::Expr<'_>]) {
36     for &(method, pos) in &PATTERN_METHODS {
37         if_chain! {
38             if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty_adjusted(&args[0]).kind();
39             if *ty.kind() == ty::Str;
40             if method_name.as_str() == method && args.len() > pos;
41             let arg = &args[pos];
42             let mut applicability = Applicability::MachineApplicable;
43             if let Some(hint) = get_hint_if_single_char_arg(cx, arg, &mut applicability);
44             then {
45                 span_lint_and_sugg(
46                     cx,
47                     SINGLE_CHAR_PATTERN,
48                     arg.span,
49                     "single-character string constant used as pattern",
50                     "try using a `char` instead",
51                     hint,
52                     applicability,
53                 );
54             }
55         }
56     }
57 }