-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathindexing_slicing.rs
290 lines (268 loc) · 10.3 KB
/
indexing_slicing.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use clippy_config::Conf;
use clippy_utils::consts::{ConstEvalCtxt, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
use clippy_utils::ty::{deref_chain, get_adt_inherent_method};
use clippy_utils::{higher, is_from_proc_macro, is_in_test};
use rustc_ast::ast::RangeLimits;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, Ty};
use rustc_session::impl_lint_pass;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// Checks for out of bounds array indexing with a constant
/// index.
///
/// ### Why is this bad?
/// This will always panic at runtime.
///
/// ### Example
/// ```rust,no_run
/// let x = [1, 2, 3, 4];
///
/// x[9];
/// &x[2..9];
/// ```
///
/// Use instead:
/// ```no_run
/// # let x = [1, 2, 3, 4];
/// // Index within bounds
///
/// x[0];
/// x[3];
/// ```
#[clippy::version = "pre 1.29.0"]
pub OUT_OF_BOUNDS_INDEXING,
correctness,
"out of bounds constant indexing"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of indexing or slicing that may panic at runtime.
///
/// This lint does not report on indexing or slicing operations
/// that always panic, clippy's `out_of_bound_indexing` already
/// handles those cases.
///
/// ### Why restrict this?
/// To avoid implicit panics from indexing and slicing.
///
/// There are “checked” alternatives which do not panic, and can be used with `unwrap()` to make
/// an explicit panic when it is desired.
///
/// ### Limitations
/// This lint does not check for the usage of indexing or slicing on strings. These are covered
/// by the more specific `string_slice` lint.
///
/// ### Example
/// ```rust,no_run
/// // Vector
/// let x = vec![0, 1, 2, 3];
///
/// x[2];
/// x[100];
/// &x[2..100];
///
/// // Array
/// let y = [0, 1, 2, 3];
///
/// let i = 10; // Could be a runtime value
/// let j = 20;
/// &y[i..j];
/// ```
///
/// Use instead:
/// ```no_run
/// # let x = vec![0, 1, 2, 3];
/// x.get(2);
/// x.get(100);
/// x.get(2..100);
///
/// # let y = [0, 1, 2, 3];
/// let i = 10;
/// let j = 20;
/// y.get(i..j);
/// ```
#[clippy::version = "pre 1.29.0"]
pub INDEXING_SLICING,
restriction,
"indexing/slicing usage"
}
impl_lint_pass!(IndexingSlicing => [INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING]);
pub struct IndexingSlicing {
allow_indexing_slicing_in_tests: bool,
suppress_restriction_lint_in_const: bool,
}
impl IndexingSlicing {
pub fn new(conf: &'static Conf) -> Self {
Self {
allow_indexing_slicing_in_tests: conf.allow_indexing_slicing_in_tests,
suppress_restriction_lint_in_const: conf.suppress_restriction_lint_in_const,
}
}
}
impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Index(array, index, _) = &expr.kind
&& (!self.suppress_restriction_lint_in_const || !cx.tcx.hir_is_inside_const_context(expr.hir_id))
&& let expr_ty = cx.typeck_results().expr_ty(array)
&& let mut deref = deref_chain(cx, expr_ty)
&& deref.any(|l| {
l.peel_refs().is_slice()
|| l.peel_refs().is_array()
|| ty_has_applicable_get_function(cx, l.peel_refs(), expr_ty, expr)
})
&& !is_from_proc_macro(cx, expr)
{
let note = "the suggestion might not be applicable in constant blocks";
let ty = cx.typeck_results().expr_ty(array).peel_refs();
let allowed_in_tests = self.allow_indexing_slicing_in_tests && is_in_test(cx.tcx, expr.hir_id);
if let Some(range) = higher::Range::hir(index) {
// Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
if let ty::Array(_, s) = ty.kind() {
let size: u128 = if let Some(size) = s.try_to_target_usize(cx.tcx) {
size.into()
} else {
return;
};
let const_range = to_const_range(cx, range, size);
if let (Some(start), _) = const_range {
if start > size {
span_lint(
cx,
OUT_OF_BOUNDS_INDEXING,
range.start.map_or(expr.span, |start| start.span),
"range is out of bounds",
);
return;
}
}
if let (_, Some(end)) = const_range {
if end > size {
span_lint(
cx,
OUT_OF_BOUNDS_INDEXING,
range.end.map_or(expr.span, |end| end.span),
"range is out of bounds",
);
return;
}
}
if let (Some(_), Some(_)) = const_range {
// early return because both start and end are constants
// and we have proven above that they are in bounds
return;
}
}
let help_msg = match (range.start, range.end) {
(None, Some(_)) => "consider using `.get(..n)`or `.get_mut(..n)` instead",
(Some(_), None) => "consider using `.get(n..)` or .get_mut(n..)` instead",
(Some(_), Some(_)) => "consider using `.get(n..m)` or `.get_mut(n..m)` instead",
(None, None) => return, // [..] is ok.
};
if allowed_in_tests {
return;
}
span_lint_and_then(cx, INDEXING_SLICING, expr.span, "slicing may panic", |diag| {
diag.help(help_msg);
if cx.tcx.hir_is_inside_const_context(expr.hir_id) {
diag.note(note);
}
});
} else {
// Catchall non-range index, i.e., [n] or [n << m]
if let ty::Array(..) = ty.kind() {
// Index is a const block.
if let ExprKind::ConstBlock(..) = index.kind {
return;
}
// Index is a constant uint.
if let Some(constant) = ConstEvalCtxt::new(cx).eval(index) {
// only `usize` index is legal in rust array index
// leave other type to rustc
if let Constant::Int(off) = constant
&& off <= usize::MAX as u128
&& let ty::Uint(utype) = cx.typeck_results().expr_ty(index).kind()
&& *utype == ty::UintTy::Usize
&& let ty::Array(_, s) = ty.kind()
&& let Some(size) = s.try_to_target_usize(cx.tcx)
{
// get constant offset and check whether it is in bounds
let off = usize::try_from(off).unwrap();
let size = usize::try_from(size).unwrap();
if off >= size {
span_lint(cx, OUT_OF_BOUNDS_INDEXING, expr.span, "index is out of bounds");
}
}
// Let rustc's `const_err` lint handle constant `usize` indexing on arrays.
return;
}
}
if allowed_in_tests {
return;
}
span_lint_and_then(cx, INDEXING_SLICING, expr.span, "indexing may panic", |diag| {
diag.help("consider using `.get(n)` or `.get_mut(n)` instead");
if cx.tcx.hir_is_inside_const_context(expr.hir_id) {
diag.note(note);
}
});
}
}
}
}
/// Returns a tuple of options with the start and end (exclusive) values of
/// the range. If the start or end is not constant, None is returned.
fn to_const_range(cx: &LateContext<'_>, range: higher::Range<'_>, array_size: u128) -> (Option<u128>, Option<u128>) {
let ecx = ConstEvalCtxt::new(cx);
let s = range.start.map(|expr| ecx.eval(expr));
let start = match s {
Some(Some(Constant::Int(x))) => Some(x),
Some(_) => None,
None => Some(0),
};
let e = range.end.map(|expr| ecx.eval(expr));
let end = match e {
Some(Some(Constant::Int(x))) => {
if range.limits == RangeLimits::Closed {
Some(x + 1)
} else {
Some(x)
}
},
Some(_) => None,
None => Some(array_size),
};
(start, end)
}
/// Checks if the output Ty of the `get` method on this Ty (if any) matches the Ty returned by the
/// indexing operation (if any).
fn ty_has_applicable_get_function<'tcx>(
cx: &LateContext<'tcx>,
ty: Ty<'tcx>,
array_ty: Ty<'tcx>,
index_expr: &Expr<'_>,
) -> bool {
if let ty::Adt(_, _) = array_ty.kind()
&& let Some(get_output_ty) = get_adt_inherent_method(cx, ty, sym!(get)).map(|m| {
cx.tcx
.fn_sig(m.def_id)
.skip_binder()
.output()
.skip_binder()
})
&& let ty::Adt(def, args) = get_output_ty.kind()
&& cx.tcx.is_diagnostic_item(sym::Option, def.0.did)
&& let Some(option_generic_param) = args.first()
&& let generic_ty = option_generic_param.expect_ty().peel_refs()
// FIXME: ideally this would handle type params and projections properly, for now just assume it's the same type
&& (cx.typeck_results().expr_ty(index_expr).peel_refs() == generic_ty.peel_refs()
|| matches!(generic_ty.peel_refs().kind(), ty::Param(_) | ty::Alias(_, _)))
{
true
} else {
false
}
}