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