Skip to content

Commit eba4143

Browse files
committed
Merge branch 'aochagavia-indexing_slicing'
2 parents f255734 + 2f13c3b commit eba4143

File tree

5 files changed

+141
-30
lines changed

5 files changed

+141
-30
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ A collection of lints to catch common mistakes and improve your Rust code.
1111
[Jump to link with clippy-service](#link-with-clippy-service)
1212

1313
##Lints
14-
There are 133 lints included in this crate:
14+
There are 134 lints included in this crate:
1515

1616
name | default | meaning
1717
---------------------------------------------------------------------------------------------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -58,6 +58,7 @@ name
5858
[if_not_else](https://github.com/Manishearth/rust-clippy/wiki#if_not_else) | warn | finds if branches that could be swapped so no negation operation is necessary on the condition
5959
[if_same_then_else](https://github.com/Manishearth/rust-clippy/wiki#if_same_then_else) | warn | if with the same *then* and *else* blocks
6060
[ifs_same_cond](https://github.com/Manishearth/rust-clippy/wiki#ifs_same_cond) | warn | consecutive `ifs` with the same condition
61+
[indexing_slicing](https://github.com/Manishearth/rust-clippy/wiki#indexing_slicing) | allow | indexing/slicing usage
6162
[ineffective_bit_mask](https://github.com/Manishearth/rust-clippy/wiki#ineffective_bit_mask) | warn | expressions where a bit mask will be rendered useless by a comparison, e.g. `(x | 1) > 2`
6263
[inline_always](https://github.com/Manishearth/rust-clippy/wiki#inline_always) | warn | `#[inline(always)]` is a bad idea in most cases
6364
[invalid_regex](https://github.com/Manishearth/rust-clippy/wiki#invalid_regex) | deny | finds invalid regular expressions in `Regex::new(_)` invocations
@@ -234,7 +235,7 @@ And, in your `main.rs` or `lib.rs`:
234235

235236
Both projects are independent and maintained by different people (even if some `clippy-service`'s contributions are authored by some `rust-clippy` members).
236237

237-
You can check it out this great service at [clippy.bashy.io](https://clippy.bashy.io/)
238+
You can check it out this great service at [clippy.bashy.io](https://clippy.bashy.io/).
238239

239240
##License
240241
Licensed under [MPL](https://www.mozilla.org/MPL/2.0/). If you're having issues with the license, let me know and I'll try to change it to something more permissive.

src/array_indexing.rs

Lines changed: 95 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ use rustc::middle::const_eval::EvalHint::ExprTypeChecked;
33
use rustc::middle::const_eval::{eval_const_expr_partial, ConstVal};
44
use rustc::middle::ty::TyArray;
55
use rustc_front::hir::*;
6-
use utils::span_lint;
6+
use syntax::ast::RangeLimits;
7+
use utils;
78

89
/// **What it does:** Check for out of bounds array indexing with a constant index.
910
///
@@ -17,35 +18,122 @@ use utils::span_lint;
1718
/// let x = [1,2,3,4];
1819
/// ...
1920
/// x[9];
21+
/// &x[2..9];
2022
/// ```
2123
declare_lint! {
2224
pub OUT_OF_BOUNDS_INDEXING,
2325
Deny,
2426
"out of bound constant indexing"
2527
}
2628

29+
/// **What it does:** Check for usage of indexing or slicing.
30+
///
31+
/// **Why is this bad?** Usually, this can be safely allowed. However,
32+
/// in some domains such as kernel development, a panic can cause the
33+
/// whole operating system to crash.
34+
///
35+
/// **Known problems:** Hopefully none.
36+
///
37+
/// **Example:**
38+
///
39+
/// ```
40+
/// ...
41+
/// x[2];
42+
/// &x[0..2];
43+
/// ```
44+
declare_lint! {
45+
pub INDEXING_SLICING,
46+
Allow,
47+
"indexing/slicing usage"
48+
}
49+
2750
#[derive(Copy,Clone)]
2851
pub struct ArrayIndexing;
2952

3053
impl LintPass for ArrayIndexing {
3154
fn get_lints(&self) -> LintArray {
32-
lint_array!(OUT_OF_BOUNDS_INDEXING)
55+
lint_array!(INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING)
3356
}
3457
}
3558

3659
impl LateLintPass for ArrayIndexing {
3760
fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
3861
if let ExprIndex(ref array, ref index) = e.node {
62+
// Array with known size can be checked statically
3963
let ty = cx.tcx.expr_ty(array);
40-
4164
if let TyArray(_, size) = ty.sty {
42-
let index = eval_const_expr_partial(cx.tcx, &index, ExprTypeChecked, None);
43-
if let Ok(ConstVal::Uint(index)) = index {
44-
if size as u64 <= index {
45-
span_lint(cx, OUT_OF_BOUNDS_INDEXING, e.span, "const index-expr is out of bounds");
65+
let size = size as u64;
66+
67+
// Index is a constant uint
68+
let const_index = eval_const_expr_partial(cx.tcx, &index, ExprTypeChecked, None);
69+
if let Ok(ConstVal::Uint(const_index)) = const_index {
70+
if size <= const_index {
71+
utils::span_lint(cx, OUT_OF_BOUNDS_INDEXING, e.span, "const index is out of bounds");
72+
}
73+
74+
return;
75+
}
76+
77+
// Index is a constant range
78+
if let Some(range) = utils::unsugar_range(index) {
79+
let start = range.start.map(|start|
80+
eval_const_expr_partial(cx.tcx, start, ExprTypeChecked, None)).map(|v| v.ok());
81+
let end = range.end.map(|end|
82+
eval_const_expr_partial(cx.tcx, end, ExprTypeChecked, None)).map(|v| v.ok());
83+
84+
if let Some((start, end)) = to_const_range(start, end, range.limits, size) {
85+
if start >= size || end >= size {
86+
utils::span_lint(cx,
87+
OUT_OF_BOUNDS_INDEXING,
88+
e.span,
89+
"range is out of bounds");
90+
}
91+
return;
4692
}
4793
}
4894
}
95+
96+
if let Some(range) = utils::unsugar_range(index) {
97+
// Full ranges are always valid
98+
if range.start.is_none() && range.end.is_none() {
99+
return;
100+
}
101+
102+
// Impossible to know if indexing or slicing is correct
103+
utils::span_lint(cx, INDEXING_SLICING, e.span, "slicing may panic");
104+
} else {
105+
utils::span_lint(cx, INDEXING_SLICING, e.span, "indexing may panic");
106+
}
49107
}
50108
}
51109
}
110+
111+
/// Returns an option containing a tuple with the start and end (exclusive) of the range
112+
///
113+
/// Note: we assume the start and the end of the range are unsigned, since array slicing
114+
/// works only on usize
115+
fn to_const_range(start: Option<Option<ConstVal>>,
116+
end: Option<Option<ConstVal>>,
117+
limits: RangeLimits,
118+
array_size: u64)
119+
-> Option<(u64, u64)> {
120+
let start = match start {
121+
Some(Some(ConstVal::Uint(x))) => x,
122+
Some(_) => return None,
123+
None => 0,
124+
};
125+
126+
let end = match end {
127+
Some(Some(ConstVal::Uint(x))) => {
128+
if limits == RangeLimits::Closed {
129+
x
130+
} else {
131+
x - 1
132+
}
133+
}
134+
Some(_) => return None,
135+
None => array_size - 1,
136+
};
137+
138+
Some((start, end))
139+
}

src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
#![feature(rustc_private, collections)]
33
#![feature(iter_arith)]
44
#![feature(custom_attribute)]
5-
#![allow(unknown_lints)]
5+
#![allow(indexing_slicing, shadow_reuse, unknown_lints)]
66

77
// this only exists to allow the "dogfood" integration test to work
88
#[allow(dead_code)]
@@ -181,6 +181,7 @@ pub fn plugin_registrar(reg: &mut Registry) {
181181
reg.register_late_lint_pass(box new_without_default::NewWithoutDefault);
182182

183183
reg.register_lint_group("clippy_pedantic", vec![
184+
array_indexing::INDEXING_SLICING,
184185
enum_glob_use::ENUM_GLOB_USE,
185186
matches::SINGLE_MATCH_ELSE,
186187
methods::OPTION_UNWRAP_USED,

src/utils/mod.rs

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,7 @@ pub fn camel_case_from(s: &str) -> usize {
681681
}
682682

683683
/// Represents a range akin to `ast::ExprKind::Range`.
684+
#[derive(Debug, Copy, Clone)]
684685
pub struct UnsugaredRange<'a> {
685686
pub start: Option<&'a Expr>,
686687
pub end: Option<&'a Expr>,
@@ -711,24 +712,30 @@ pub fn unsugar_range(expr: &Expr) -> Option<UnsugaredRange> {
711712
Some(unwrap_unstable(expr))
712713
}
713714

714-
if let ExprStruct(ref path, ref fields, None) = unwrap_unstable(&expr).node {
715-
if match_path(path, &RANGE_FROM_PATH) {
716-
Some(UnsugaredRange { start: get_field("start", fields), end: None, limits: RangeLimits::HalfOpen })
717-
} else if match_path(path, &RANGE_FULL_PATH) {
718-
Some(UnsugaredRange { start: None, end: None, limits: RangeLimits::HalfOpen })
719-
} else if match_path(path, &RANGE_INCLUSIVE_NON_EMPTY_PATH) {
720-
Some(UnsugaredRange { start: get_field("start", fields), end: get_field("end", fields), limits: RangeLimits::Closed })
721-
} else if match_path(path, &RANGE_PATH) {
722-
Some(UnsugaredRange { start: get_field("start", fields), end: get_field("end", fields), limits: RangeLimits::HalfOpen })
723-
} else if match_path(path, &RANGE_TO_INCLUSIVE_PATH) {
724-
Some(UnsugaredRange { start: None, end: get_field("end", fields), limits: RangeLimits::Closed })
725-
} else if match_path(path, &RANGE_TO_PATH) {
726-
Some(UnsugaredRange { start: None, end: get_field("end", fields), limits: RangeLimits::HalfOpen })
727-
} else {
728-
None
715+
match unwrap_unstable(&expr).node {
716+
ExprPath(None, ref path) => {
717+
if match_path(path, &RANGE_FULL_PATH) {
718+
Some(UnsugaredRange { start: None, end: None, limits: RangeLimits::HalfOpen })
719+
} else {
720+
None
721+
}
729722
}
730-
} else {
731-
None
723+
ExprStruct(ref path, ref fields, None) => {
724+
if match_path(path, &RANGE_FROM_PATH) {
725+
Some(UnsugaredRange { start: get_field("start", fields), end: None, limits: RangeLimits::HalfOpen })
726+
} else if match_path(path, &RANGE_INCLUSIVE_NON_EMPTY_PATH) {
727+
Some(UnsugaredRange { start: get_field("start", fields), end: get_field("end", fields), limits: RangeLimits::Closed })
728+
} else if match_path(path, &RANGE_PATH) {
729+
Some(UnsugaredRange { start: get_field("start", fields), end: get_field("end", fields), limits: RangeLimits::HalfOpen })
730+
} else if match_path(path, &RANGE_TO_INCLUSIVE_PATH) {
731+
Some(UnsugaredRange { start: None, end: get_field("end", fields), limits: RangeLimits::Closed })
732+
} else if match_path(path, &RANGE_TO_PATH) {
733+
Some(UnsugaredRange { start: None, end: get_field("end", fields), limits: RangeLimits::HalfOpen })
734+
} else {
735+
None
736+
}
737+
}
738+
_ => None,
732739
}
733740
}
734741

tests/compile-fail/array_indexing.rs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,27 @@
1-
#![feature(plugin)]
1+
#![feature(inclusive_range_syntax, plugin)]
22
#![plugin(clippy)]
33

4+
#![deny(indexing_slicing)]
45
#![deny(out_of_bounds_indexing)]
56
#![allow(no_effect)]
67

78
fn main() {
89
let x = [1,2,3,4];
910
x[0];
1011
x[3];
11-
x[4]; //~ERROR: const index-expr is out of bounds
12-
x[1 << 3]; //~ERROR: const index-expr is out of bounds
12+
x[4]; //~ERROR: const index is out of bounds
13+
x[1 << 3]; //~ERROR: const index is out of bounds
14+
&x[1..5]; //~ERROR: range is out of bounds
15+
&x[0..3];
16+
&x[0...4]; //~ERROR: range is out of bounds
17+
&x[..];
18+
&x[1..];
19+
&x[..4];
20+
&x[..5]; //~ERROR: range is out of bounds
21+
22+
let y = &x;
23+
y[0]; //~ERROR: indexing may panic
24+
&y[1..2]; //~ERROR: slicing may panic
25+
&y[..];
26+
&y[0...4]; //~ERROR: slicing may panic
1327
}

0 commit comments

Comments
 (0)