]>
Commit | Line | Data |
---|---|---|
f2b60f7d | 1 | use clippy_utils::diagnostics::span_lint_and_sugg; |
f2b60f7d | 2 | use clippy_utils::source::snippet_with_applicability; |
ed00b5ec | 3 | use clippy_utils::ty::is_type_diagnostic_item; |
f2b60f7d FG |
4 | use rustc_ast::LitKind; |
5 | use rustc_errors::Applicability; | |
6 | use rustc_hir as hir; | |
7 | use rustc_lint::LateContext; | |
8 | use rustc_span::source_map::Spanned; | |
ed00b5ec | 9 | use rustc_span::sym; |
f2b60f7d FG |
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 | ) { | |
4b012472 FG |
19 | if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) |
20 | && let Some(impl_id) = cx.tcx.impl_of_method(method_id) | |
21 | && let identity = cx.tcx.type_of(impl_id).instantiate_identity() | |
22 | && let hir::ExprKind::Lit(Spanned { | |
23 | node: LitKind::Int(0, _), | |
24 | .. | |
25 | }) = arg.kind | |
26 | { | |
27 | if identity.is_slice() { | |
28 | let mut app = Applicability::MachineApplicable; | |
29 | let slice_name = snippet_with_applicability(cx, recv.span, "..", &mut app); | |
30 | span_lint_and_sugg( | |
31 | cx, | |
32 | GET_FIRST, | |
33 | expr.span, | |
34 | &format!("accessing first element with `{slice_name}.get(0)`"), | |
35 | "try", | |
36 | format!("{slice_name}.first()"), | |
37 | app, | |
38 | ); | |
39 | } else if is_type_diagnostic_item(cx, identity, sym::VecDeque) { | |
40 | let mut app = Applicability::MachineApplicable; | |
41 | let slice_name = snippet_with_applicability(cx, recv.span, "..", &mut app); | |
42 | span_lint_and_sugg( | |
43 | cx, | |
44 | GET_FIRST, | |
45 | expr.span, | |
46 | &format!("accessing first element with `{slice_name}.get(0)`"), | |
47 | "try", | |
48 | format!("{slice_name}.front()"), | |
49 | app, | |
50 | ); | |
f2b60f7d FG |
51 | } |
52 | } | |
53 | } |