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