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