about summary refs log tree commit diff
path: root/clippy_lints/src/methods
diff options
context:
space:
mode:
authorKrishna Sundarram <krishnasundarram@monzo.com>2023-02-16 16:41:04 +0000
committerKrishna Sundarram <krishnasundarram@monzo.com>2023-02-16 17:05:21 +0000
commit7e53e27dfdb5ce4cda44912fcc6c288c34ac7d91 (patch)
tree842487fc6e2b82629145eb48caa483ae0adc3a7e /clippy_lints/src/methods
parent52c8b536c954bc543290f36f2d90f3e75facaa0b (diff)
downloadrust-7e53e27dfdb5ce4cda44912fcc6c288c34ac7d91.tar.gz
rust-7e53e27dfdb5ce4cda44912fcc6c288c34ac7d91.zip
Stop bytes_nth from suggesting code that does not compile
Diffstat (limited to 'clippy_lints/src/methods')
-rw-r--r--clippy_lints/src/methods/bytes_nth.rs42
1 files changed, 29 insertions, 13 deletions
diff --git a/clippy_lints/src/methods/bytes_nth.rs b/clippy_lints/src/methods/bytes_nth.rs
index d512cc4eeae..c5fc145b289 100644
--- a/clippy_lints/src/methods/bytes_nth.rs
+++ b/clippy_lints/src/methods/bytes_nth.rs
@@ -5,6 +5,8 @@ use rustc_errors::Applicability;
 use rustc_hir::{Expr, LangItem};
 use rustc_lint::LateContext;
 
+use crate::methods::method_call;
+
 use super::BYTES_NTH;
 
 pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, recv: &'tcx Expr<'tcx>, n_arg: &'tcx Expr<'tcx>) {
@@ -16,18 +18,32 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, recv: &'tcx E
     } else {
         return;
     };
+
     let mut applicability = Applicability::MachineApplicable;
-    span_lint_and_sugg(
-        cx,
-        BYTES_NTH,
-        expr.span,
-        &format!("called `.bytes().nth()` on a `{caller_type}`"),
-        "try",
-        format!(
-            "{}.as_bytes().get({})",
-            snippet_with_applicability(cx, recv.span, "..", &mut applicability),
-            snippet_with_applicability(cx, n_arg.span, "..", &mut applicability)
-        ),
-        applicability,
-    );
+    let receiver = snippet_with_applicability(cx, recv.span, "..", &mut applicability);
+    let n = snippet_with_applicability(cx, n_arg.span, "..", &mut applicability);
+
+    if let Some(parent) = clippy_utils::get_parent_expr(cx, expr)
+      && let Some((name, _, _, _, _)) = method_call(parent)
+      && name == "unwrap" {
+        span_lint_and_sugg(
+            cx,
+            BYTES_NTH,
+            parent.span,
+            &format!("called `.bytes().nth().unwrap()` on a `{caller_type}`"),
+            "try",
+            format!("{receiver}.as_bytes()[{n}]",),
+            applicability
+        );
+    } else {
+        span_lint_and_sugg(
+            cx,
+            BYTES_NTH,
+            expr.span,
+            &format!("called `.bytes().nth()` on a `{caller_type}`"),
+            "try",
+            format!("{receiver}.as_bytes().get({n}).copied()"), 
+            applicability
+        );
+    };
 }