]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[rust.git] / src / tools / clippy / clippy_lints / src / methods / iter_skip_next.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::is_trait_method;
3 use clippy_utils::path_to_local;
4 use clippy_utils::source::snippet;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
7 use rustc_hir::{BindingAnnotation, Node, PatKind};
8 use rustc_lint::LateContext;
9 use rustc_span::sym;
10
11 use super::ITER_SKIP_NEXT;
12
13 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
14     // lint if caller of skip is an Iterator
15     if is_trait_method(cx, expr, sym::Iterator) {
16         let mut application = Applicability::MachineApplicable;
17         span_lint_and_then(
18             cx,
19             ITER_SKIP_NEXT,
20             expr.span.trim_start(recv.span).unwrap(),
21             "called `skip(..).next()` on an iterator",
22             |diag| {
23                 if_chain! {
24                     if let Some(id) = path_to_local(recv);
25                     if let Node::Pat(pat) = cx.tcx.hir().get(id);
26                     if let PatKind::Binding(ann, _, _, _)  = pat.kind;
27                     if ann != BindingAnnotation::MUT;
28                     then {
29                         application = Applicability::Unspecified;
30                         diag.span_help(
31                             pat.span,
32                             format!("for this change `{}` has to be mutable", snippet(cx, pat.span, "..")),
33                         );
34                     }
35                 }
36
37                 diag.span_suggestion(
38                     expr.span.trim_start(recv.span).unwrap(),
39                     "use `nth` instead",
40                     format!(".nth({})", snippet(cx, arg.span, "..")),
41                     application,
42                 );
43             },
44         );
45     }
46 }