Skip to content

Commit d020196

Browse files
committed
Add check for illegal accessing known length array with a constant index
1 parent 7e650b7 commit d020196

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

clippy_lints/src/indexing_slicing.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,23 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
170170
return;
171171
}
172172
// Index is a constant uint.
173-
if constant(cx, cx.typeck_results(), index).is_some() {
173+
if let Some(constant) = constant(cx, cx.typeck_results(), index) {
174+
// only `usize` index is legal in rust array index
175+
// leave other type to rustc
176+
if let Constant::Int(off) = constant
177+
&& let ty::Uint(utype) = cx.typeck_results().expr_ty(index).kind()
178+
&& *utype == ty::UintTy::Usize
179+
&& let ty::Array(_, s) = ty.kind()
180+
&& let Some(size) = s.try_eval_target_usize(cx.tcx, cx.param_env)
181+
{
182+
// get constant offset and check whether it is in bounds
183+
let off = usize::try_from(off).unwrap();
184+
let size = usize::try_from(size).unwrap();
185+
186+
if off >= size {
187+
span_lint(cx, OUT_OF_BOUNDS_INDEXING, expr.span, "index is out of bounds");
188+
}
189+
}
174190
// Let rustc's `const_err` lint handle constant `usize` indexing on arrays.
175191
return;
176192
}

0 commit comments

Comments
 (0)