]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/match_on_vec_items.rs
Rollup merge of #72026 - botika:master, r=estebank
[rust.git] / src / tools / clippy / clippy_lints / src / match_on_vec_items.rs
1 use crate::utils::{self, is_type_diagnostic_item, match_type, snippet, span_lint_and_sugg, walk_ptrs_ty};
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Expr, ExprKind, MatchSource};
5 use rustc_lint::{LateContext, LateLintPass, LintContext};
6 use rustc_middle::lint::in_external_macro;
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for `match vec[idx]` or `match vec[n..m]`.
11     ///
12     /// **Why is this bad?** This can panic at runtime.
13     ///
14     /// **Known problems:** None.
15     ///
16     /// **Example:**
17     /// ```rust, no_run
18     /// let arr = vec![0, 1, 2, 3];
19     /// let idx = 1;
20     ///
21     /// // Bad
22     /// match arr[idx] {
23     ///     0 => println!("{}", 0),
24     ///     1 => println!("{}", 3),
25     ///     _ => {},
26     /// }
27     /// ```
28     /// Use instead:
29     /// ```rust, no_run
30     /// let arr = vec![0, 1, 2, 3];
31     /// let idx = 1;
32     ///
33     /// // Good
34     /// match arr.get(idx) {
35     ///     Some(0) => println!("{}", 0),
36     ///     Some(1) => println!("{}", 3),
37     ///     _ => {},
38     /// }
39     /// ```
40     pub MATCH_ON_VEC_ITEMS,
41     pedantic,
42     "matching on vector elements can panic"
43 }
44
45 declare_lint_pass!(MatchOnVecItems => [MATCH_ON_VEC_ITEMS]);
46
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchOnVecItems {
48     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) {
49         if_chain! {
50             if !in_external_macro(cx.sess(), expr.span);
51             if let ExprKind::Match(ref match_expr, _, MatchSource::Normal) = expr.kind;
52             if let Some(idx_expr) = is_vec_indexing(cx, match_expr);
53             if let ExprKind::Index(vec, idx) = idx_expr.kind;
54
55             then {
56                 // FIXME: could be improved to suggest surrounding every pattern with Some(_),
57                 // but only when `or_patterns` are stabilized.
58                 span_lint_and_sugg(
59                     cx,
60                     MATCH_ON_VEC_ITEMS,
61                     match_expr.span,
62                     "indexing into a vector may panic",
63                     "try this",
64                     format!(
65                         "{}.get({})",
66                         snippet(cx, vec.span, ".."),
67                         snippet(cx, idx.span, "..")
68                     ),
69                     Applicability::MaybeIncorrect
70                 );
71             }
72         }
73     }
74 }
75
76 fn is_vec_indexing<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
77     if_chain! {
78         if let ExprKind::Index(ref array, ref index) = expr.kind;
79         if is_vector(cx, array);
80         if !is_full_range(cx, index);
81
82         then {
83             return Some(expr);
84         }
85     }
86
87     None
88 }
89
90 fn is_vector(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
91     let ty = cx.tables.expr_ty(expr);
92     let ty = walk_ptrs_ty(ty);
93     is_type_diagnostic_item(cx, ty, sym!(vec_type))
94 }
95
96 fn is_full_range(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
97     let ty = cx.tables.expr_ty(expr);
98     let ty = walk_ptrs_ty(ty);
99     match_type(cx, ty, &utils::paths::RANGE_FULL)
100 }