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};
10 /// **What it does:** Checks for `match vec[idx]` or `match vec[n..m]`.
12 /// **Why is this bad?** This can panic at runtime.
14 /// **Known problems:** None.
18 /// let arr = vec![0, 1, 2, 3];
23 /// 0 => println!("{}", 0),
24 /// 1 => println!("{}", 3),
30 /// let arr = vec![0, 1, 2, 3];
34 /// match arr.get(idx) {
35 /// Some(0) => println!("{}", 0),
36 /// Some(1) => println!("{}", 3),
40 pub MATCH_ON_VEC_ITEMS,
42 "matching on vector elements can panic"
45 declare_lint_pass!(MatchOnVecItems => [MATCH_ON_VEC_ITEMS]);
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchOnVecItems {
48 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) {
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;
56 // FIXME: could be improved to suggest surrounding every pattern with Some(_),
57 // but only when `or_patterns` are stabilized.
62 "indexing into a vector may panic",
66 snippet(cx, vec.span, ".."),
67 snippet(cx, idx.span, "..")
69 Applicability::MaybeIncorrect
76 fn is_vec_indexing<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
78 if let ExprKind::Index(ref array, ref index) = expr.kind;
79 if is_vector(cx, array);
80 if !is_full_range(cx, index);
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))
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)