|
| 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 | + /// // Bad |
| 24 | + /// let x = vec![2, 3, 5]; |
| 25 | + /// let first_element = x.get(0); |
| 26 | + /// ``` |
| 27 | + /// Use instead: |
| 28 | + /// ```rust |
| 29 | + /// // Good |
| 30 | + /// let x = vec![2, 3, 5]; |
| 31 | + /// let first_element = x.first(); |
| 32 | + /// ``` |
| 33 | + #[clippy::version = "1.63.0"] |
| 34 | + pub GET_FIRST, |
| 35 | + style, |
| 36 | + "Using `x.get(0)` when `x.first()` is simpler" |
| 37 | +} |
| 38 | +declare_lint_pass!(GetFirst => [GET_FIRST]); |
| 39 | + |
| 40 | +impl<'tcx> LateLintPass<'tcx> for GetFirst { |
| 41 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { |
| 42 | + if_chain! { |
| 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); |
| 46 | + |
| 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; |
| 49 | + |
| 50 | + then { |
| 51 | + let mut applicability = Applicability::MachineApplicable; |
| 52 | + let slice_name = snippet_with_applicability( |
| 53 | + cx, |
| 54 | + struct_calling_on.span, "..", |
| 55 | + &mut applicability, |
| 56 | + ); |
| 57 | + span_lint_and_sugg( |
| 58 | + cx, |
| 59 | + GET_FIRST, |
| 60 | + expr.span, |
| 61 | + &format!("accessing first element with `{0}.get(0)`", slice_name), |
| 62 | + "try", |
| 63 | + format!("{}.first()", slice_name), |
| 64 | + applicability, |
| 65 | + ); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments