]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/indexing_slicing.rs
Rollup merge of #106465 - compiler-errors:bump-IMPLIED_BOUNDS_ENTAILMENT, r=lcnr
[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_then};
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_tool_lint, impl_lint_pass};
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     /// let x = [1, 2, 3, 4];
23     ///
24     /// x[9];
25     /// &x[2..9];
26     /// ```
27     ///
28     /// Use instead:
29     /// ```rust
30     /// # let x = [1, 2, 3, 4];
31     /// // Index within bounds
32     ///
33     /// x[0];
34     /// x[3];
35     /// ```
36     #[clippy::version = "pre 1.29.0"]
37     pub OUT_OF_BOUNDS_INDEXING,
38     correctness,
39     "out of bounds constant indexing"
40 }
41
42 declare_clippy_lint! {
43     /// ### What it does
44     /// Checks for usage of indexing or slicing. Arrays are special cases, this lint
45     /// does report on arrays if we can tell that slicing operations are in bounds and does not
46     /// lint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint.
47     ///
48     /// ### Why is this bad?
49     /// Indexing and slicing can panic at runtime and there are
50     /// safe alternatives.
51     ///
52     /// ### Example
53     /// ```rust,no_run
54     /// // Vector
55     /// let x = vec![0; 5];
56     ///
57     /// x[2];
58     /// &x[2..100];
59     ///
60     /// // Array
61     /// let y = [0, 1, 2, 3];
62     ///
63     /// &y[10..100];
64     /// &y[10..];
65     /// ```
66     ///
67     /// Use instead:
68     /// ```rust
69     /// # #![allow(unused)]
70     ///
71     /// # let x = vec![0; 5];
72     /// # let y = [0, 1, 2, 3];
73     /// x.get(2);
74     /// x.get(2..100);
75     ///
76     /// y.get(10);
77     /// y.get(10..100);
78     /// ```
79     #[clippy::version = "pre 1.29.0"]
80     pub INDEXING_SLICING,
81     restriction,
82     "indexing/slicing usage"
83 }
84
85 impl_lint_pass!(IndexingSlicing => [INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING]);
86
87 #[derive(Copy, Clone)]
88 pub struct IndexingSlicing {
89     suppress_restriction_lint_in_const: bool,
90 }
91
92 impl IndexingSlicing {
93     pub fn new(suppress_restriction_lint_in_const: bool) -> Self {
94         Self {
95             suppress_restriction_lint_in_const,
96         }
97     }
98 }
99
100 impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
101     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
102         if self.suppress_restriction_lint_in_const && cx.tcx.hir().is_inside_const_context(expr.hir_id) {
103             return;
104         }
105
106         if let ExprKind::Index(array, index) = &expr.kind {
107             let note = "the suggestion might not be applicable in constant blocks";
108             let ty = cx.typeck_results().expr_ty(array).peel_refs();
109             if let Some(range) = higher::Range::hir(index) {
110                 // Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
111                 if let ty::Array(_, s) = ty.kind() {
112                     let size: u128 = if let Some(size) = s.try_eval_usize(cx.tcx, cx.param_env) {
113                         size.into()
114                     } else {
115                         return;
116                     };
117
118                     let const_range = to_const_range(cx, range, size);
119
120                     if let (Some(start), _) = const_range {
121                         if start > size {
122                             span_lint(
123                                 cx,
124                                 OUT_OF_BOUNDS_INDEXING,
125                                 range.start.map_or(expr.span, |start| start.span),
126                                 "range is out of bounds",
127                             );
128                             return;
129                         }
130                     }
131
132                     if let (_, Some(end)) = const_range {
133                         if end > size {
134                             span_lint(
135                                 cx,
136                                 OUT_OF_BOUNDS_INDEXING,
137                                 range.end.map_or(expr.span, |end| end.span),
138                                 "range is out of bounds",
139                             );
140                             return;
141                         }
142                     }
143
144                     if let (Some(_), Some(_)) = const_range {
145                         // early return because both start and end are constants
146                         // and we have proven above that they are in bounds
147                         return;
148                     }
149                 }
150
151                 let help_msg = match (range.start, range.end) {
152                     (None, Some(_)) => "consider using `.get(..n)`or `.get_mut(..n)` instead",
153                     (Some(_), None) => "consider using `.get(n..)` or .get_mut(n..)` instead",
154                     (Some(_), Some(_)) => "consider using `.get(n..m)` or `.get_mut(n..m)` instead",
155                     (None, None) => return, // [..] is ok.
156                 };
157
158                 span_lint_and_then(cx, INDEXING_SLICING, expr.span, "slicing may panic", |diag| {
159                     diag.help(help_msg);
160
161                     if cx.tcx.hir().is_inside_const_context(expr.hir_id) {
162                         diag.note(note);
163                     }
164                 });
165             } else {
166                 // Catchall non-range index, i.e., [n] or [n << m]
167                 if let ty::Array(..) = ty.kind() {
168                     // Index is a const block.
169                     if let ExprKind::ConstBlock(..) = index.kind {
170                         return;
171                     }
172                     // Index is a constant uint.
173                     if let Some(..) = constant(cx, cx.typeck_results(), index) {
174                         // Let rustc's `const_err` lint handle constant `usize` indexing on arrays.
175                         return;
176                     }
177                 }
178
179                 span_lint_and_then(cx, INDEXING_SLICING, expr.span, "indexing may panic", |diag| {
180                     diag.help("consider using `.get(n)` or `.get_mut(n)` instead");
181
182                     if cx.tcx.hir().is_inside_const_context(expr.hir_id) {
183                         diag.note(note);
184                     }
185                 });
186             }
187         }
188     }
189 }
190
191 /// Returns a tuple of options with the start and end (exclusive) values of
192 /// the range. If the start or end is not constant, None is returned.
193 fn to_const_range(cx: &LateContext<'_>, range: higher::Range<'_>, array_size: u128) -> (Option<u128>, Option<u128>) {
194     let s = range
195         .start
196         .map(|expr| constant(cx, cx.typeck_results(), expr).map(|(c, _)| c));
197     let start = match s {
198         Some(Some(Constant::Int(x))) => Some(x),
199         Some(_) => None,
200         None => Some(0),
201     };
202
203     let e = range
204         .end
205         .map(|expr| constant(cx, cx.typeck_results(), expr).map(|(c, _)| c));
206     let end = match e {
207         Some(Some(Constant::Int(x))) => {
208             if range.limits == RangeLimits::Closed {
209                 Some(x + 1)
210             } else {
211                 Some(x)
212             }
213         },
214         Some(_) => None,
215         None => Some(array_size),
216     };
217
218     (start, end)
219 }