]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/chars_cmp.rs
Merge commit '0e87918536b9833bbc6c683d1f9d51ee2bf03ef1' into clippyup
[rust.git] / clippy_lints / src / methods / chars_cmp.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::{method_chain_args, single_segment_path};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
7 use rustc_lint::LateContext;
8 use rustc_lint::Lint;
9 use rustc_middle::ty;
10 use rustc_span::sym;
11
12 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
13 pub(super) fn check(
14     cx: &LateContext<'_>,
15     info: &crate::methods::BinaryExprInfo<'_>,
16     chain_methods: &[&str],
17     lint: &'static Lint,
18     suggest: &str,
19 ) -> bool {
20     if_chain! {
21         if let Some(args) = method_chain_args(info.chain, chain_methods);
22         if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
23         if arg_char.len() == 1;
24         if let hir::ExprKind::Path(ref qpath) = fun.kind;
25         if let Some(segment) = single_segment_path(qpath);
26         if segment.ident.name == sym::Some;
27         then {
28             let mut applicability = Applicability::MachineApplicable;
29             let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
30
31             if *self_ty.kind() != ty::Str {
32                 return false;
33             }
34
35             span_lint_and_sugg(
36                 cx,
37                 lint,
38                 info.expr.span,
39                 &format!("you should use the `{}` method", suggest),
40                 "like this",
41                 format!("{}{}.{}({})",
42                         if info.eq { "" } else { "!" },
43                         snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
44                         suggest,
45                         snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)),
46                 applicability,
47             );
48
49             return true;
50         }
51     }
52
53     false
54 }