1 use crate::utils::{is_type_diagnostic_item, is_type_lang_item, snippet, span_lint_and_sugg};
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Expr, ExprKind, LangItem, 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 declare_clippy_lint! {
11 /// **What it does:** Checks for `match vec[idx]` or `match vec[n..m]`.
13 /// **Why is this bad?** This can panic at runtime.
15 /// **Known problems:** None.
19 /// let arr = vec![0, 1, 2, 3];
24 /// 0 => println!("{}", 0),
25 /// 1 => println!("{}", 3),
31 /// let arr = vec![0, 1, 2, 3];
35 /// match arr.get(idx) {
36 /// Some(0) => println!("{}", 0),
37 /// Some(1) => println!("{}", 3),
41 pub MATCH_ON_VEC_ITEMS,
43 "matching on vector elements can panic"
46 declare_lint_pass!(MatchOnVecItems => [MATCH_ON_VEC_ITEMS]);
48 impl<'tcx> LateLintPass<'tcx> for MatchOnVecItems {
49 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
51 if !in_external_macro(cx.sess(), expr.span);
52 if let ExprKind::Match(ref match_expr, _, MatchSource::Normal) = expr.kind;
53 if let Some(idx_expr) = is_vec_indexing(cx, match_expr);
54 if let ExprKind::Index(vec, idx) = idx_expr.kind;
57 // FIXME: could be improved to suggest surrounding every pattern with Some(_),
58 // but only when `or_patterns` are stabilized.
63 "indexing into a vector may panic",
67 snippet(cx, vec.span, ".."),
68 snippet(cx, idx.span, "..")
70 Applicability::MaybeIncorrect
77 fn is_vec_indexing<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
79 if let ExprKind::Index(ref array, ref index) = expr.kind;
80 if is_vector(cx, array);
81 if !is_full_range(cx, index);
91 fn is_vector(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
92 let ty = cx.typeck_results().expr_ty(expr);
93 let ty = ty.peel_refs();
94 is_type_diagnostic_item(cx, ty, sym::vec_type)
97 fn is_full_range(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
98 let ty = cx.typeck_results().expr_ty(expr);
99 let ty = ty.peel_refs();
100 is_type_lang_item(cx, ty, LangItem::RangeFull)