1 //! lint on indexing and slicing operations
3 use clippy_utils::consts::{constant, Constant};
4 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
5 use clippy_utils::higher;
6 use rustc_ast::ast::RangeLimits;
7 use rustc_hir::{Expr, ExprKind};
8 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 declare_clippy_lint! {
14 /// Checks for out of bounds array indexing with a constant
17 /// ### Why is this bad?
18 /// This will always panic at runtime.
22 /// let x = [1, 2, 3, 4];
30 /// # let x = [1, 2, 3, 4];
31 /// // Index within bounds
36 #[clippy::version = "pre 1.29.0"]
37 pub OUT_OF_BOUNDS_INDEXING,
39 "out of bounds constant indexing"
42 declare_clippy_lint! {
44 /// Checks for usage of indexing or slicing. Arrays are special cases, this lint
45 /// does report on arrays if we can tell that slicing operations are in bounds and does not
46 /// lint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint.
48 /// ### Why is this bad?
49 /// Indexing and slicing can panic at runtime and there are
50 /// safe alternatives.
55 /// let x = vec![0; 5];
61 /// let y = [0, 1, 2, 3];
69 /// # #![allow(unused)]
71 /// # let x = vec![0; 5];
72 /// # let y = [0, 1, 2, 3];
79 #[clippy::version = "pre 1.29.0"]
82 "indexing/slicing usage"
85 declare_lint_pass!(IndexingSlicing => [INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING]);
87 impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
88 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
89 if cx.tcx.hir().is_inside_const_context(expr.hir_id) {
93 if let ExprKind::Index(array, index) = &expr.kind {
94 let ty = cx.typeck_results().expr_ty(array).peel_refs();
95 if let Some(range) = higher::Range::hir(index) {
96 // Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
97 if let ty::Array(_, s) = ty.kind() {
98 let size: u128 = if let Some(size) = s.try_eval_usize(cx.tcx, cx.param_env) {
104 let const_range = to_const_range(cx, range, size);
106 if let (Some(start), _) = const_range {
110 OUT_OF_BOUNDS_INDEXING,
111 range.start.map_or(expr.span, |start| start.span),
112 "range is out of bounds",
118 if let (_, Some(end)) = const_range {
122 OUT_OF_BOUNDS_INDEXING,
123 range.end.map_or(expr.span, |end| end.span),
124 "range is out of bounds",
130 if let (Some(_), Some(_)) = const_range {
131 // early return because both start and end are constants
132 // and we have proven above that they are in bounds
137 let help_msg = match (range.start, range.end) {
138 (None, Some(_)) => "consider using `.get(..n)`or `.get_mut(..n)` instead",
139 (Some(_), None) => "consider using `.get(n..)` or .get_mut(n..)` instead",
140 (Some(_), Some(_)) => "consider using `.get(n..m)` or `.get_mut(n..m)` instead",
141 (None, None) => return, // [..] is ok.
144 span_lint_and_help(cx, INDEXING_SLICING, expr.span, "slicing may panic", None, help_msg);
146 // Catchall non-range index, i.e., [n] or [n << m]
147 if let ty::Array(..) = ty.kind() {
148 // Index is a const block.
149 if let ExprKind::ConstBlock(..) = index.kind {
152 // Index is a constant uint.
153 if let Some(..) = constant(cx, cx.typeck_results(), index) {
154 // Let rustc's `const_err` lint handle constant `usize` indexing on arrays.
163 "indexing may panic",
165 "consider using `.get(n)` or `.get_mut(n)` instead",
172 /// Returns a tuple of options with the start and end (exclusive) values of
173 /// the range. If the start or end is not constant, None is returned.
174 fn to_const_range<'tcx>(
175 cx: &LateContext<'tcx>,
176 range: higher::Range<'_>,
178 ) -> (Option<u128>, Option<u128>) {
181 .map(|expr| constant(cx, cx.typeck_results(), expr).map(|(c, _)| c));
182 let start = match s {
183 Some(Some(Constant::Int(x))) => Some(x),
190 .map(|expr| constant(cx, cx.typeck_results(), expr).map(|(c, _)| c));
192 Some(Some(Constant::Int(x))) => {
193 if range.limits == RangeLimits::Closed {
200 None => Some(array_size),