]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/get_first.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / methods / get_first.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_slice_of_primitives;
3 use clippy_utils::source::snippet_with_applicability;
4 use if_chain::if_chain;
5 use rustc_ast::LitKind;
6 use rustc_errors::Applicability;
7 use rustc_hir as hir;
8 use rustc_lint::LateContext;
9 use rustc_span::source_map::Spanned;
10
11 use super::GET_FIRST;
12
13 pub(super) fn check<'tcx>(
14     cx: &LateContext<'tcx>,
15     expr: &'tcx hir::Expr<'_>,
16     recv: &'tcx hir::Expr<'_>,
17     arg: &'tcx hir::Expr<'_>,
18 ) {
19     if_chain! {
20         if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
21         if let Some(impl_id) = cx.tcx.impl_of_method(method_id);
22         if cx.tcx.type_of(impl_id).is_slice();
23         if let Some(_) = is_slice_of_primitives(cx, recv);
24         if let hir::ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = arg.kind;
25         then {
26             let mut app = Applicability::MachineApplicable;
27             let slice_name = snippet_with_applicability(cx, recv.span, "..", &mut app);
28             span_lint_and_sugg(
29                 cx,
30                 GET_FIRST,
31                 expr.span,
32                 &format!("accessing first element with `{slice_name}.get(0)`"),
33                 "try",
34                 format!("{slice_name}.first()"),
35                 app,
36             );
37         }
38     }
39 }