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 #[clippy::version = "1.45.0"]
44 pub MATCH_ON_VEC_ITEMS,
46 "matching on vector elements can panic"
49 declare_lint_pass!(MatchOnVecItems => [MATCH_ON_VEC_ITEMS]);
51 impl<'tcx> LateLintPass<'tcx> for MatchOnVecItems {
52 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
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;
60 // FIXME: could be improved to suggest surrounding every pattern with Some(_),
61 // but only when `or_patterns` are stabilized.
66 "indexing into a vector may panic",
70 snippet(cx, vec.span, ".."),
71 snippet(cx, idx.span, "..")
73 Applicability::MaybeIncorrect
80 fn is_vec_indexing<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
82 if let ExprKind::Index(array, index) = expr.kind;
83 if is_vector(cx, array);
84 if !is_full_range(cx, index);
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)
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)