]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/indexing_slicing.rs
Fix lint registration
[rust.git] / 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     /// ### Known problems
21     /// Hopefully none.
22     ///
23     /// ### Example
24     /// ```no_run
25     /// # #![allow(const_err)]
26     /// let x = [1, 2, 3, 4];
27     ///
28     /// // Bad
29     /// x[9];
30     /// &x[2..9];
31     ///
32     /// // Good
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     /// ### Known problems
53     /// Hopefully none.
54     ///
55     /// ### Example
56     /// ```rust,no_run
57     /// // Vector
58     /// let x = vec![0; 5];
59     ///
60     /// // Bad
61     /// x[2];
62     /// &x[2..100];
63     /// &x[2..];
64     /// &x[..100];
65     ///
66     /// // Good
67     /// x.get(2);
68     /// x.get(2..100);
69     /// x.get(2..);
70     /// x.get(..100);
71     ///
72     /// // Array
73     /// let y = [0, 1, 2, 3];
74     ///
75     /// // Bad
76     /// &y[10..100];
77     /// &y[10..];
78     /// &y[..100];
79     ///
80     /// // Good
81     /// &y[2..];
82     /// &y[..2];
83     /// &y[0..3];
84     /// y.get(10);
85     /// y.get(10..100);
86     /// y.get(10..);
87     /// y.get(..100);
88     /// ```
89     #[clippy::version = "pre 1.29.0"]
90     pub INDEXING_SLICING,
91     restriction,
92     "indexing/slicing usage"
93 }
94
95 declare_lint_pass!(IndexingSlicing => [INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING]);
96
97 impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
98     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
99         if cx.tcx.hir().is_inside_const_context(expr.hir_id) {
100             return;
101         }
102
103         if let ExprKind::Index(array, index) = &expr.kind {
104             let ty = cx.typeck_results().expr_ty(array).peel_refs();
105             if let Some(range) = higher::Range::hir(index) {
106                 // Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
107                 if let ty::Array(_, s) = ty.kind() {
108                     let size: u128 = if let Some(size) = s.try_eval_usize(cx.tcx, cx.param_env) {
109                         size.into()
110                     } else {
111                         return;
112                     };
113
114                     let const_range = to_const_range(cx, range, size);
115
116                     if let (Some(start), _) = const_range {
117                         if start > size {
118                             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                             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                 span_lint_and_help(cx, INDEXING_SLICING, expr.span, "slicing may panic", None, help_msg);
155             } else {
156                 // Catchall non-range index, i.e., [n] or [n << m]
157                 if let ty::Array(..) = ty.kind() {
158                     // Index is a const block.
159                     if let ExprKind::ConstBlock(..) = index.kind {
160                         return;
161                     }
162                     // Index is a constant uint.
163                     if let Some(..) = constant(cx, cx.typeck_results(), index) {
164                         // Let rustc's `const_err` lint handle constant `usize` indexing on arrays.
165                         return;
166                     }
167                 }
168
169                 span_lint_and_help(
170                     cx,
171                     INDEXING_SLICING,
172                     expr.span,
173                     "indexing may panic",
174                     None,
175                     "consider using `.get(n)` or `.get_mut(n)` instead",
176                 );
177             }
178         }
179     }
180 }
181
182 /// Returns a tuple of options with the start and end (exclusive) values of
183 /// the range. If the start or end is not constant, None is returned.
184 fn to_const_range<'tcx>(
185     cx: &LateContext<'tcx>,
186     range: higher::Range<'_>,
187     array_size: u128,
188 ) -> (Option<u128>, Option<u128>) {
189     let s = range
190         .start
191         .map(|expr| constant(cx, cx.typeck_results(), expr).map(|(c, _)| c));
192     let start = match s {
193         Some(Some(Constant::Int(x))) => Some(x),
194         Some(_) => None,
195         None => Some(0),
196     };
197
198     let e = range
199         .end
200         .map(|expr| constant(cx, cx.typeck_results(), expr).map(|(c, _)| c));
201     let end = match e {
202         Some(Some(Constant::Int(x))) => {
203             if range.limits == RangeLimits::Closed {
204                 Some(x + 1)
205             } else {
206                 Some(x)
207             }
208         },
209         Some(_) => None,
210         None => Some(array_size),
211     };
212
213     (start, end)
214 }