]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/bytes_nth.rs
Auto merge of #6957 - camsteffen:eq-ty-kind, r=flip1995
[rust.git] / clippy_lints / src / methods / bytes_nth.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Expr, ExprKind};
7 use rustc_lint::LateContext;
8 use rustc_span::sym;
9
10 use super::BYTES_NTH;
11
12 pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, iter_args: &'tcx [Expr<'tcx>]) {
13     if_chain! {
14         if let ExprKind::MethodCall(_, _, ref args, _) = expr.kind;
15         let ty = cx.typeck_results().expr_ty(&iter_args[0]).peel_refs();
16         let caller_type = if is_type_diagnostic_item(cx, ty, sym::string_type) {
17             Some("String")
18         } else if ty.is_str() {
19             Some("str")
20         } else {
21             None
22         };
23         if let Some(caller_type) = caller_type;
24         then {
25             let mut applicability = Applicability::MachineApplicable;
26             span_lint_and_sugg(
27                 cx,
28                 BYTES_NTH,
29                 expr.span,
30                 &format!("called `.byte().nth()` on a `{}`", caller_type),
31                 "try",
32                 format!(
33                     "{}.as_bytes().get({})",
34                     snippet_with_applicability(cx, iter_args[0].span, "..", &mut applicability),
35                     snippet_with_applicability(cx, args[1].span, "..", &mut applicability)
36                 ),
37                 applicability,
38             );
39         }
40     }
41 }