]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/indexing_slicing.rs
Merge #3312
[rust.git] / clippy_lints / src / indexing_slicing.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 //! lint on indexing and slicing operations
12
13 use crate::consts::{constant, Constant};
14 use crate::utils;
15 use crate::utils::higher;
16 use crate::utils::higher::Range;
17 use crate::rustc::hir::*;
18 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
19 use crate::rustc::{declare_tool_lint, lint_array};
20 use crate::rustc::ty;
21 use crate::syntax::ast::RangeLimits;
22
23 /// **What it does:** Checks for out of bounds array indexing with a constant
24 /// index.
25 ///
26 /// **Why is this bad?** This will always panic at runtime.
27 ///
28 /// **Known problems:** Hopefully none.
29 ///
30 /// **Example:**
31 /// ```rust
32 /// let x = [1,2,3,4];
33 ///
34 /// // Bad
35 /// x[9];
36 /// &x[2..9];
37 ///
38 /// // Good
39 /// x[0];
40 /// x[3];
41 /// ```
42 declare_clippy_lint! {
43     pub OUT_OF_BOUNDS_INDEXING,
44     correctness,
45     "out of bounds constant indexing"
46 }
47
48 /// **What it does:** Checks for usage of indexing or slicing. Arrays are special cased, this lint
49 /// does report on arrays if we can tell that slicing operations are in bounds and does not
50 /// lint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint.
51 ///
52 /// **Why is this bad?** Indexing and slicing can panic at runtime and there are
53 /// safe alternatives.
54 ///
55 /// **Known problems:** Hopefully none.
56 ///
57 /// **Example:**
58 /// ```rust
59 /// // Vector
60 /// let x = vec![0; 5];
61 ///
62 /// // Bad
63 /// x[2];
64 /// &x[2..100];
65 /// &x[2..];
66 /// &x[..100];
67 ///
68 /// // Good
69 /// x.get(2);
70 /// x.get(2..100);
71 /// x.get(2..);
72 /// x.get(..100);
73 ///
74 /// // Array
75 /// let y = [0, 1, 2, 3];
76 ///
77 /// // Bad
78 /// &y[10..100];
79 /// &y[10..];
80 /// &y[..100];
81 ///
82 /// // Good
83 /// &y[2..];
84 /// &y[..2];
85 /// &y[0..3];
86 /// y.get(10);
87 /// y.get(10..100);
88 /// y.get(10..);
89 /// y.get(..100);
90 /// ```
91 declare_clippy_lint! {
92     pub INDEXING_SLICING,
93     restriction,
94     "indexing/slicing usage"
95 }
96
97 #[derive(Copy, Clone)]
98 pub struct IndexingSlicing;
99
100 impl LintPass for IndexingSlicing {
101     fn get_lints(&self) -> LintArray {
102         lint_array!(INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING)
103     }
104 }
105
106 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IndexingSlicing {
107     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
108         if let ExprKind::Index(ref array, ref index) = &expr.node {
109             let ty = cx.tables.expr_ty(array);
110             if let Some(range) = higher::range(cx, index) {
111
112                 // Ranged indexes, i.e. &x[n..m], &x[n..], &x[..n] and &x[..]
113                 if let ty::Array(_, s) = ty.sty {
114                     let size: u128 = s.assert_usize(cx.tcx).unwrap().into();
115
116                     let const_range = to_const_range(cx, range, size);
117
118                     if let (Some(start), _) = const_range {
119                         if start > size {
120                             utils::span_lint(
121                                 cx,
122                                 OUT_OF_BOUNDS_INDEXING,
123                                 range.start.map_or(expr.span, |start| start.span),
124                                 "range is out of bounds",
125                             );
126                             return;
127                         }
128                     }
129
130                     if let (_, Some(end)) = const_range {
131                         if end > size {
132                             utils::span_lint(
133                                 cx,
134                                 OUT_OF_BOUNDS_INDEXING,
135                                 range.end.map_or(expr.span, |end| end.span),
136                                 "range is out of bounds",
137                             );
138                             return;
139                         }
140                     }
141
142                     if let (Some(_), Some(_)) = const_range {
143                         // early return because both start and end are constants
144                         // and we have proven above that they are in bounds
145                         return;
146                     }
147                 }
148
149                 let help_msg = match (range.start, range.end) {
150                     (None, Some(_)) => "Consider using `.get(..n)`or `.get_mut(..n)` instead",
151                     (Some(_), None) => "Consider using `.get(n..)` or .get_mut(n..)` instead",
152                     (Some(_), Some(_)) => "Consider using `.get(n..m)` or `.get_mut(n..m)` instead",
153                     (None, None) => return, // [..] is ok.
154                 };
155
156                 utils::span_help_and_lint(
157                     cx,
158                     INDEXING_SLICING,
159                     expr.span,
160                     "slicing may panic.",
161                     help_msg,
162                 );
163             } else {
164                 // Catchall non-range index, i.e. [n] or [n << m]
165                 if let ty::Array(..) = ty.sty {
166                     // Index is a constant uint.
167                     if let Some(..) = constant(cx, cx.tables, index) {
168                         // Let rustc's `const_err` lint handle constant `usize` indexing on arrays.
169                         return;
170                     }
171                 }
172
173                 utils::span_help_and_lint(
174                     cx,
175                     INDEXING_SLICING,
176                     expr.span,
177                     "indexing may panic.",
178                     "Consider using `.get(n)` or `.get_mut(n)` instead",
179                 );
180             }
181         }
182     }
183 }
184
185 /// Returns a tuple of options with the start and end (exclusive) values of
186 /// the range. If the start or end is not constant, None is returned.
187 fn to_const_range<'a, 'tcx>(
188     cx: &LateContext<'a, 'tcx>,
189     range: Range<'_>,
190     array_size: u128,
191 ) -> (Option<u128>, Option<u128>) {
192     let s = range
193         .start
194         .map(|expr| constant(cx, cx.tables, expr).map(|(c, _)| c));
195     let start = match s {
196         Some(Some(Constant::Int(x))) => Some(x),
197         Some(_) => None,
198         None => Some(0),
199     };
200
201     let e = range
202         .end
203         .map(|expr| constant(cx, cx.tables, expr).map(|(c, _)| c));
204     let end = match e {
205         Some(Some(Constant::Int(x))) => if range.limits == RangeLimits::Closed {
206             Some(x + 1)
207         } else {
208             Some(x)
209         },
210         Some(_) => None,
211         None => Some(array_size),
212     };
213
214     (start, end)
215 }