Skip to content

Commit 25510cf

Browse files
authored
Merge pull request #2790 from shnewto/vectors-to-indexing-slicing-lint
Extend `indexing_slicing` lint
2 parents dbc9e36 + c479b3b commit 25510cf

File tree

7 files changed

+542
-295
lines changed

7 files changed

+542
-295
lines changed

clippy_lints/src/array_indexing.rs

-123
This file was deleted.

clippy_lints/src/indexing_slicing.rs

+183
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
//! lint on indexing and slicing operations
2+
3+
use crate::consts::{constant, Constant};
4+
use crate::utils;
5+
use crate::utils::higher;
6+
use crate::utils::higher::Range;
7+
use rustc::hir::*;
8+
use rustc::lint::*;
9+
use rustc::ty;
10+
use syntax::ast::RangeLimits;
11+
12+
/// **What it does:** Checks for out of bounds array indexing with a constant
13+
/// index.
14+
///
15+
/// **Why is this bad?** This will always panic at runtime.
16+
///
17+
/// **Known problems:** Hopefully none.
18+
///
19+
/// **Example:**
20+
/// ```rust
21+
/// let x = [1,2,3,4];
22+
///
23+
/// // Bad
24+
/// x[9];
25+
/// &x[2..9];
26+
///
27+
/// // Good
28+
/// x[0];
29+
/// x[3];
30+
/// ```
31+
declare_clippy_lint! {
32+
pub OUT_OF_BOUNDS_INDEXING,
33+
correctness,
34+
"out of bounds constant indexing"
35+
}
36+
37+
/// **What it does:** Checks for usage of indexing or slicing. Arrays are special cased, this lint
38+
/// does report on arrays if we can tell that slicing operations are in bounds and does not
39+
/// lint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint.
40+
///
41+
/// **Why is this bad?** Indexing and slicing can panic at runtime and there are
42+
/// safe alternatives.
43+
///
44+
/// **Known problems:** Hopefully none.
45+
///
46+
/// **Example:**
47+
/// ```rust
48+
/// // Vector
49+
/// let x = vec![0; 5];
50+
///
51+
/// // Bad
52+
/// x[2];
53+
/// &x[2..100];
54+
/// &x[2..];
55+
/// &x[..100];
56+
///
57+
/// // Good
58+
/// x.get(2);
59+
/// x.get(2..100);
60+
/// x.get(2..);
61+
/// x.get(..100);
62+
///
63+
/// // Array
64+
/// let y = [0, 1, 2, 3];
65+
///
66+
/// // Bad
67+
/// &y[10..100];
68+
/// &y[10..];
69+
/// &y[..100];
70+
///
71+
/// // Good
72+
/// &y[2..];
73+
/// &y[..2];
74+
/// &y[0..3];
75+
/// y.get(10);
76+
/// y.get(10..100);
77+
/// y.get(10..);
78+
/// y.get(..100);
79+
/// ```
80+
declare_clippy_lint! {
81+
pub INDEXING_SLICING,
82+
pedantic,
83+
"indexing/slicing usage"
84+
}
85+
86+
#[derive(Copy, Clone)]
87+
pub struct IndexingSlicing;
88+
89+
impl LintPass for IndexingSlicing {
90+
fn get_lints(&self) -> LintArray {
91+
lint_array!(INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING)
92+
}
93+
}
94+
95+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IndexingSlicing {
96+
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
97+
if let ExprIndex(ref array, ref index) = &expr.node {
98+
let ty = cx.tables.expr_ty(array);
99+
if let Some(range) = higher::range(cx, index) {
100+
// Ranged indexes, i.e. &x[n..m], &x[n..], &x[..n] and &x[..]
101+
if let ty::TyArray(_, s) = ty.sty {
102+
let size: u128 = s.assert_usize(cx.tcx).unwrap().into();
103+
// Index is a constant range.
104+
if let Some((start, end)) = to_const_range(cx, range, size) {
105+
if start > size || end > size {
106+
utils::span_lint(
107+
cx,
108+
OUT_OF_BOUNDS_INDEXING,
109+
expr.span,
110+
"range is out of bounds",
111+
);
112+
}
113+
return;
114+
}
115+
}
116+
117+
let help_msg = match (range.start, range.end) {
118+
(None, Some(_)) => "Consider using `.get(..n)`or `.get_mut(..n)` instead",
119+
(Some(_), None) => "Consider using `.get(n..)` or .get_mut(n..)` instead",
120+
(Some(_), Some(_)) => "Consider using `.get(n..m)` or `.get_mut(n..m)` instead",
121+
(None, None) => return, // [..] is ok.
122+
};
123+
124+
utils::span_help_and_lint(
125+
cx,
126+
INDEXING_SLICING,
127+
expr.span,
128+
"slicing may panic.",
129+
help_msg,
130+
);
131+
} else {
132+
// Catchall non-range index, i.e. [n] or [n << m]
133+
if let ty::TyArray(..) = ty.sty {
134+
// Index is a constant uint.
135+
if let Some(..) = constant(cx, cx.tables, index) {
136+
// Let rustc's `const_err` lint handle constant `usize` indexing on arrays.
137+
return;
138+
}
139+
}
140+
141+
utils::span_help_and_lint(
142+
cx,
143+
INDEXING_SLICING,
144+
expr.span,
145+
"indexing may panic.",
146+
"Consider using `.get(n)` or `.get_mut(n)` instead",
147+
);
148+
}
149+
}
150+
}
151+
}
152+
153+
/// Returns an option containing a tuple with the start and end (exclusive) of
154+
/// the range.
155+
fn to_const_range<'a, 'tcx>(
156+
cx: &LateContext<'a, 'tcx>,
157+
range: Range,
158+
array_size: u128,
159+
) -> Option<(u128, u128)> {
160+
let s = range
161+
.start
162+
.map(|expr| constant(cx, cx.tables, expr).map(|(c, _)| c));
163+
let start = match s {
164+
Some(Some(Constant::Int(x))) => x,
165+
Some(_) => return None,
166+
None => 0,
167+
};
168+
169+
let e = range
170+
.end
171+
.map(|expr| constant(cx, cx.tables, expr).map(|(c, _)| c));
172+
let end = match e {
173+
Some(Some(Constant::Int(x))) => if range.limits == RangeLimits::Closed {
174+
x + 1
175+
} else {
176+
x
177+
},
178+
Some(_) => return None,
179+
None => array_size,
180+
};
181+
182+
Some((start, end))
183+
}

clippy_lints/src/lib.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
#![feature(stmt_expr_attributes)]
77
#![feature(range_contains)]
88
#![feature(macro_vis_matcher)]
9-
#![allow(unknown_lints, indexing_slicing, shadow_reuse, missing_docs_in_private_items)]
9+
#![allow(unknown_lints, shadow_reuse, missing_docs_in_private_items)]
1010
#![recursion_limit = "256"]
1111
#![allow(stable_features)]
1212
#![feature(iterator_find_map)]
@@ -99,7 +99,6 @@ pub mod utils;
9999
// begin lints modules, do not remove this comment, it’s used in `update_lints`
100100
pub mod approx_const;
101101
pub mod arithmetic;
102-
pub mod array_indexing;
103102
pub mod assign_ops;
104103
pub mod attrs;
105104
pub mod bit_mask;
@@ -139,6 +138,7 @@ pub mod identity_conversion;
139138
pub mod identity_op;
140139
pub mod if_let_redundant_pattern_matching;
141140
pub mod if_not_else;
141+
pub mod indexing_slicing;
142142
pub mod infallible_destructuring_match;
143143
pub mod infinite_iter;
144144
pub mod inherent_impl;
@@ -355,7 +355,6 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
355355
);
356356
reg.register_late_lint_pass(box escape::Pass{too_large_for_stack: conf.too_large_for_stack});
357357
reg.register_early_lint_pass(box misc_early::MiscEarly);
358-
reg.register_late_lint_pass(box array_indexing::ArrayIndexing);
359358
reg.register_late_lint_pass(box panic_unimplemented::Pass);
360359
reg.register_late_lint_pass(box strings::StringLitAsBytes);
361360
reg.register_late_lint_pass(box derive::Derive);
@@ -432,12 +431,11 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
432431
reg.register_late_lint_pass(box unwrap::Pass);
433432
reg.register_late_lint_pass(box duration_subsec::DurationSubsec);
434433
reg.register_late_lint_pass(box default_trait_access::DefaultTraitAccess);
435-
434+
reg.register_late_lint_pass(box indexing_slicing::IndexingSlicing);
436435

437436
reg.register_lint_group("clippy_restriction", vec![
438437
arithmetic::FLOAT_ARITHMETIC,
439438
arithmetic::INTEGER_ARITHMETIC,
440-
array_indexing::INDEXING_SLICING,
441439
assign_ops::ASSIGN_OPS,
442440
else_if_without_else::ELSE_IF_WITHOUT_ELSE,
443441
inherent_impl::MULTIPLE_INHERENT_IMPL,
@@ -468,6 +466,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
468466
enum_variants::PUB_ENUM_VARIANT_NAMES,
469467
enum_variants::STUTTER,
470468
if_not_else::IF_NOT_ELSE,
469+
indexing_slicing::INDEXING_SLICING,
471470
infinite_iter::MAYBE_INFINITE_ITER,
472471
items_after_statements::ITEMS_AFTER_STATEMENTS,
473472
matches::SINGLE_MATCH_ELSE,
@@ -500,7 +499,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
500499

501500
reg.register_lint_group("clippy", vec![
502501
approx_const::APPROX_CONSTANT,
503-
array_indexing::OUT_OF_BOUNDS_INDEXING,
502+
indexing_slicing::OUT_OF_BOUNDS_INDEXING,
504503
assign_ops::ASSIGN_OP_PATTERN,
505504
assign_ops::MISREFACTORED_ASSIGN_OP,
506505
attrs::DEPRECATED_SEMVER,
@@ -863,7 +862,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
863862

864863
reg.register_lint_group("clippy_correctness", vec![
865864
approx_const::APPROX_CONSTANT,
866-
array_indexing::OUT_OF_BOUNDS_INDEXING,
865+
indexing_slicing::OUT_OF_BOUNDS_INDEXING,
867866
attrs::DEPRECATED_SEMVER,
868867
attrs::USELESS_ATTRIBUTE,
869868
bit_mask::BAD_BIT_MASK,

0 commit comments

Comments
 (0)