1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::{is_slice_of_primitives, match_def_path, paths};
4 use if_chain::if_chain;
5 use rustc_ast::LitKind;
6 use rustc_errors::Applicability;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::source_map::Spanned;
12 declare_clippy_lint! {
14 /// Checks for using `x.get(0)` instead of
17 /// ### Why is this bad?
18 /// Using `x.first()` is easier to read and has the same
24 /// let x = vec![2, 3, 5];
25 /// let first_element = x.get(0);
30 /// let x = vec![2, 3, 5];
31 /// let first_element = x.first();
33 #[clippy::version = "1.63.0"]
36 "Using `x.get(0)` when `x.first()` is simpler"
38 declare_lint_pass!(GetFirst => [GET_FIRST]);
40 impl<'tcx> LateLintPass<'tcx> for GetFirst {
41 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
43 if let hir::ExprKind::MethodCall(_, [struct_calling_on, method_arg], _) = &expr.kind;
44 if let Some(expr_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
45 if match_def_path(cx, expr_def_id, &paths::SLICE_GET);
47 if let Some(_) = is_slice_of_primitives(cx, struct_calling_on);
48 if let hir::ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = method_arg.kind;
51 let mut applicability = Applicability::MachineApplicable;
52 let slice_name = snippet_with_applicability(
54 struct_calling_on.span, "..",
61 &format!("accessing first element with `{0}.get(0)`", slice_name),
63 format!("{}.first()", slice_name),