]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/indexing_slicing.rs
Reintroduce `extern crate` for non-Cargo dependencies.
[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 crate::rustc::hir::*;
8 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use crate::rustc::{declare_tool_lint, lint_array};
10 use crate::rustc::ty;
11 use crate::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
96 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IndexingSlicing {
97     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
98         if let ExprKind::Index(ref array, ref index) = &expr.node {
99             let ty = cx.tables.expr_ty(array);
100             if let Some(range) = higher::range(cx, index) {
101                 // Ranged indexes, i.e. &x[n..m], &x[n..], &x[..n] and &x[..]
102                 if let ty::Array(_, s) = ty.sty {
103                     let size: u128 = s.assert_usize(cx.tcx).unwrap().into();
104                     // Index is a constant range.
105                     if let Some((start, end)) = to_const_range(cx, range, size) {
106                         if start > size || end > size {
107                             utils::span_lint(
108                                 cx,
109                                 OUT_OF_BOUNDS_INDEXING,
110                                 expr.span,
111                                 "range is out of bounds",
112                             );
113                         }
114                         return;
115                     }
116                 }
117
118                 let help_msg = match (range.start, range.end) {
119                     (None, Some(_)) => "Consider using `.get(..n)`or `.get_mut(..n)` instead",
120                     (Some(_), None) => "Consider using `.get(n..)` or .get_mut(n..)` instead",
121                     (Some(_), Some(_)) => "Consider using `.get(n..m)` or `.get_mut(n..m)` instead",
122                     (None, None) => return, // [..] is ok.
123                 };
124
125                 utils::span_help_and_lint(
126                     cx,
127                     INDEXING_SLICING,
128                     expr.span,
129                     "slicing may panic.",
130                     help_msg,
131                 );
132             } else {
133                 // Catchall non-range index, i.e. [n] or [n << m]
134                 if let ty::Array(..) = ty.sty {
135                     // Index is a constant uint.
136                     if let Some(..) = constant(cx, cx.tables, index) {
137                         // Let rustc's `const_err` lint handle constant `usize` indexing on arrays.
138                         return;
139                     }
140                 }
141
142                 utils::span_help_and_lint(
143                     cx,
144                     INDEXING_SLICING,
145                     expr.span,
146                     "indexing may panic.",
147                     "Consider using `.get(n)` or `.get_mut(n)` instead",
148                 );
149             }
150         }
151     }
152 }
153
154 /// Returns an option containing a tuple with the start and end (exclusive) of
155 /// the range.
156 fn to_const_range<'a, 'tcx>(
157     cx: &LateContext<'a, 'tcx>,
158     range: Range<'_>,
159     array_size: u128,
160 ) -> Option<(u128, u128)> {
161     let s = range
162         .start
163         .map(|expr| constant(cx, cx.tables, expr).map(|(c, _)| c));
164     let start = match s {
165         Some(Some(Constant::Int(x))) => x,
166         Some(_) => return None,
167         None => 0,
168     };
169
170     let e = range
171         .end
172         .map(|expr| constant(cx, cx.tables, expr).map(|(c, _)| c));
173     let end = match e {
174         Some(Some(Constant::Int(x))) => if range.limits == RangeLimits::Closed {
175             x + 1
176         } else {
177             x
178         },
179         Some(_) => return None,
180         None => array_size,
181     };
182
183     Some((start, end))
184 }