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};
12 declare_clippy_lint! {
14 /// Checks for `match vec[idx]` or `match vec[n..m]`.
16 /// ### Why is this bad?
17 /// This can panic at runtime.
21 /// let arr = vec![0, 1, 2, 3];
26 /// 0 => println!("{}", 0),
27 /// 1 => println!("{}", 3),
33 /// let arr = vec![0, 1, 2, 3];
37 /// match arr.get(idx) {
38 /// Some(0) => println!("{}", 0),
39 /// Some(1) => println!("{}", 3),
43 pub MATCH_ON_VEC_ITEMS,
45 "matching on vector elements can panic"
48 declare_lint_pass!(MatchOnVecItems => [MATCH_ON_VEC_ITEMS]);
50 impl<'tcx> LateLintPass<'tcx> for MatchOnVecItems {
51 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
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;
59 // FIXME: could be improved to suggest surrounding every pattern with Some(_),
60 // but only when `or_patterns` are stabilized.
65 "indexing into a vector may panic",
69 snippet(cx, vec.span, ".."),
70 snippet(cx, idx.span, "..")
72 Applicability::MaybeIncorrect
79 fn is_vec_indexing<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
81 if let ExprKind::Index(array, index) = expr.kind;
82 if is_vector(cx, array);
83 if !is_full_range(cx, index);
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)
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)