1 //! lint on indexing and slicing operations
2
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};
9 use rustc_middle::ty;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11
12 declare_clippy_lint! {
13 /// ### What it does
14 /// Checks for out of bounds array indexing with a constant
15 /// index.
16 ///
17 /// ### Why is this bad?
18 /// This will always panic at runtime.
19 ///
20 /// ### Known problems
21 /// Hopefully none.
22 ///
23 /// ### Example
24 /// ```no_run
25 /// # #![allow(const_err)]
26 /// let x = [1, 2, 3, 4];
27 ///
28 /// // Bad
29 /// x[9];
30 /// &x[2..9];
31 ///
32 /// // Good
33 /// x[0];
34 /// x[3];
35 /// ```
36 pub OUT_OF_BOUNDS_INDEXING,
37 correctness,
38 "out of bounds constant indexing"
39 }
40
41 declare_clippy_lint! {
42 /// ### What it does
43 /// Checks for usage of indexing or slicing. Arrays are special cases, this lint
44 /// does report on arrays if we can tell that slicing operations are in bounds and does not
45 /// lint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint.
46 ///
47 /// ### Why is this bad?
48 /// Indexing and slicing can panic at runtime and there are
49 /// safe alternatives.
50 ///
51 /// ### Known problems
52 /// Hopefully none.
53 ///
54 /// ### Example
55 /// ```rust,no_run
56 /// // Vector
57 /// let x = vec![0; 5];
58 ///
59 /// // Bad
60 /// x[2];
61 /// &x[2..100];
62 /// &x[2..];
63 /// &x[..100];
64 ///
65 /// // Good
66 /// x.get(2);
67 /// x.get(2..100);
68 /// x.get(2..);
69 /// x.get(..100);
70 ///
71 /// // Array
72 /// let y = [0, 1, 2, 3];
73 ///
74 /// // Bad
75 /// &y[10..100];
76 /// &y[10..];
77 /// &y[..100];
78 ///
79 /// // Good
80 /// &y[2..];
81 /// &y[..2];
82 /// &y[0..3];
83 /// y.get(10);
84 /// y.get(10..100);
85 /// y.get(10..);
86 /// y.get(..100);
87 /// ```
88 pub INDEXING_SLICING,
89 restriction,
90 "indexing/slicing usage"
91 }
92
93 declare_lint_pass!(IndexingSlicing => [INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING]);
94
95 impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>)96 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
97 if let ExprKind::Index(array, index) = &expr.kind {
98 let ty = cx.typeck_results().expr_ty(array).peel_refs();
99 if let Some(range) = higher::Range::hir(index) {
100 // Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
101 if let ty::Array(_, s) = ty.kind() {
102 let size: u128 = if let Some(size) = s.try_eval_usize(cx.tcx, cx.param_env) {
103 size.into()
104 } else {
105 return;
106 };
107
108 let const_range = to_const_range(cx, range, size);
109
110 if let (Some(start), _) = const_range {
111 if start > size {
112 span_lint(
113 cx,
114 OUT_OF_BOUNDS_INDEXING,
115 range.start.map_or(expr.span, |start| start.span),
116 "range is out of bounds",
117 );
118 return;
119 }
120 }
121
122 if let (_, Some(end)) = const_range {
123 if end > size {
124 span_lint(
125 cx,
126 OUT_OF_BOUNDS_INDEXING,
127 range.end.map_or(expr.span, |end| end.span),
128 "range is out of bounds",
129 );
130 return;
131 }
132 }
133
134 if let (Some(_), Some(_)) = const_range {
135 // early return because both start and end are constants
136 // and we have proven above that they are in bounds
137 return;
138 }
139 }
140
141 let help_msg = match (range.start, range.end) {
142 (None, Some(_)) => "consider using `.get(..n)`or `.get_mut(..n)` instead",
143 (Some(_), None) => "consider using `.get(n..)` or .get_mut(n..)` instead",
144 (Some(_), Some(_)) => "consider using `.get(n..m)` or `.get_mut(n..m)` instead",
145 (None, None) => return, // [..] is ok.
146 };
147
148 span_lint_and_help(cx, INDEXING_SLICING, expr.span, "slicing may panic", None, help_msg);
149 } else {
150 // Catchall non-range index, i.e., [n] or [n << m]
151 if let ty::Array(..) = ty.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.
155 return;
156 }
157 }
158
159 span_lint_and_help(
160 cx,
161 INDEXING_SLICING,
162 expr.span,
163 "indexing may panic",
164 None,
165 "consider using `.get(n)` or `.get_mut(n)` instead",
166 );
167 }
168 }
169 }
170 }
171
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.
to_const_range<'tcx>( cx: &LateContext<'tcx>, range: higher::Range<'_>, array_size: u128, ) -> (Option<u128>, Option<u128>)174 fn to_const_range<'tcx>(
175 cx: &LateContext<'tcx>,
176 range: higher::Range<'_>,
177 array_size: u128,
178 ) -> (Option<u128>, Option<u128>) {
179 let s = range
180 .start
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),
184 Some(_) => None,
185 None => Some(0),
186 };
187
188 let e = range
189 .end
190 .map(|expr| constant(cx, cx.typeck_results(), expr).map(|(c, _)| c));
191 let end = match e {
192 Some(Some(Constant::Int(x))) => {
193 if range.limits == RangeLimits::Closed {
194 Some(x + 1)
195 } else {
196 Some(x)
197 }
198 },
199 Some(_) => None,
200 None => Some(array_size),
201 };
202
203 (start, end)
204 }
205