]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/get_first.rs
Auto merge of #9148 - arieluy:then_some_unwrap_or, r=Jarcho
[rust.git] / clippy_lints / src / get_first.rs
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;
7 use rustc_hir as hir;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::source_map::Spanned;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Checks for using `x.get(0)` instead of
15     /// `x.first()`.
16     ///
17     /// ### Why is this bad?
18     /// Using `x.first()` is easier to read and has the same
19     /// result.
20     ///
21     /// ### Example
22     /// ```rust
23     /// let x = vec![2, 3, 5];
24     /// let first_element = x.get(0);
25     /// ```
26     ///
27     /// Use instead:
28     /// ```rust
29     /// let x = vec![2, 3, 5];
30     /// let first_element = x.first();
31     /// ```
32     #[clippy::version = "1.63.0"]
33     pub GET_FIRST,
34     style,
35     "Using `x.get(0)` when `x.first()` is simpler"
36 }
37 declare_lint_pass!(GetFirst => [GET_FIRST]);
38
39 impl<'tcx> LateLintPass<'tcx> for GetFirst {
40     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
41         if_chain! {
42             if let hir::ExprKind::MethodCall(_, [struct_calling_on, method_arg], _) = &expr.kind;
43             if let Some(expr_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
44             if match_def_path(cx, expr_def_id, &paths::SLICE_GET);
45
46             if let Some(_) = is_slice_of_primitives(cx, struct_calling_on);
47             if let hir::ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = method_arg.kind;
48
49             then {
50                 let mut applicability = Applicability::MachineApplicable;
51                 let slice_name = snippet_with_applicability(
52                     cx,
53                     struct_calling_on.span, "..",
54                     &mut applicability,
55                 );
56                 span_lint_and_sugg(
57                     cx,
58                     GET_FIRST,
59                     expr.span,
60                     &format!("accessing first element with `{0}.get(0)`", slice_name),
61                     "try",
62                     format!("{}.first()", slice_name),
63                     applicability,
64                 );
65             }
66         }
67     }
68 }