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