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