]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/match_on_vec_items.rs
Auto merge of #85013 - Mark-Simulacrum:dominators-bitset, r=pnkfelix
[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     #[clippy::version = "1.45.0"]
44     pub MATCH_ON_VEC_ITEMS,
45     pedantic,
46     "matching on vector elements can panic"
47 }
48
49 declare_lint_pass!(MatchOnVecItems => [MATCH_ON_VEC_ITEMS]);
50
51 impl<'tcx> LateLintPass<'tcx> for MatchOnVecItems {
52     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
53         if_chain! {
54             if !in_external_macro(cx.sess(), expr.span);
55             if let ExprKind::Match(match_expr, _, MatchSource::Normal) = expr.kind;
56             if let Some(idx_expr) = is_vec_indexing(cx, match_expr);
57             if let ExprKind::Index(vec, idx) = idx_expr.kind;
58
59             then {
60                 // FIXME: could be improved to suggest surrounding every pattern with Some(_),
61                 // but only when `or_patterns` are stabilized.
62                 span_lint_and_sugg(
63                     cx,
64                     MATCH_ON_VEC_ITEMS,
65                     match_expr.span,
66                     "indexing into a vector may panic",
67                     "try this",
68                     format!(
69                         "{}.get({})",
70                         snippet(cx, vec.span, ".."),
71                         snippet(cx, idx.span, "..")
72                     ),
73                     Applicability::MaybeIncorrect
74                 );
75             }
76         }
77     }
78 }
79
80 fn is_vec_indexing<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
81     if_chain! {
82         if let ExprKind::Index(array, index) = expr.kind;
83         if is_vector(cx, array);
84         if !is_full_range(cx, index);
85
86         then {
87             return Some(expr);
88         }
89     }
90
91     None
92 }
93
94 fn is_vector(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
95     let ty = cx.typeck_results().expr_ty(expr);
96     let ty = ty.peel_refs();
97     is_type_diagnostic_item(cx, ty, sym::Vec)
98 }
99
100 fn is_full_range(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
101     let ty = cx.typeck_results().expr_ty(expr);
102     let ty = ty.peel_refs();
103     is_type_lang_item(cx, ty, LangItem::RangeFull)
104 }