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