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