Skip to content

Commit 469b3d5

Browse files
committed
Merge pull request #889 from Manishearth/fix-887
fix #887: New lints for integer/floating-point arithmetic
2 parents 5150088 + 0b40ae1 commit 469b3d5

File tree

6 files changed

+182
-9
lines changed

6 files changed

+182
-9
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ All notable changes to this project will be documented in this file.
107107
[`explicit_iter_loop`]: https://github.com/Manishearth/rust-clippy/wiki#explicit_iter_loop
108108
[`extend_from_slice`]: https://github.com/Manishearth/rust-clippy/wiki#extend_from_slice
109109
[`filter_next`]: https://github.com/Manishearth/rust-clippy/wiki#filter_next
110+
[`float_arithmetic`]: https://github.com/Manishearth/rust-clippy/wiki#float_arithmetic
110111
[`float_cmp`]: https://github.com/Manishearth/rust-clippy/wiki#float_cmp
111112
[`for_kv_map`]: https://github.com/Manishearth/rust-clippy/wiki#for_kv_map
112113
[`for_loop_over_option`]: https://github.com/Manishearth/rust-clippy/wiki#for_loop_over_option
@@ -118,6 +119,7 @@ All notable changes to this project will be documented in this file.
118119
[`indexing_slicing`]: https://github.com/Manishearth/rust-clippy/wiki#indexing_slicing
119120
[`ineffective_bit_mask`]: https://github.com/Manishearth/rust-clippy/wiki#ineffective_bit_mask
120121
[`inline_always`]: https://github.com/Manishearth/rust-clippy/wiki#inline_always
122+
[`integer_arithmetic`]: https://github.com/Manishearth/rust-clippy/wiki#integer_arithmetic
121123
[`invalid_regex`]: https://github.com/Manishearth/rust-clippy/wiki#invalid_regex
122124
[`invalid_upcast_comparisons`]: https://github.com/Manishearth/rust-clippy/wiki#invalid_upcast_comparisons
123125
[`items_after_statements`]: https://github.com/Manishearth/rust-clippy/wiki#items_after_statements

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ Table of contents:
1414
* [License](#license)
1515

1616
##Lints
17-
There are 144 lints included in this crate:
17+
There are 146 lints included in this crate:
1818

1919
name | default | meaning
2020
---------------------------------------------------------------------------------------------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -56,6 +56,7 @@ name
5656
[explicit_iter_loop](https://github.com/Manishearth/rust-clippy/wiki#explicit_iter_loop) | warn | for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do
5757
[extend_from_slice](https://github.com/Manishearth/rust-clippy/wiki#extend_from_slice) | warn | `.extend_from_slice(_)` is a faster way to extend a Vec by a slice
5858
[filter_next](https://github.com/Manishearth/rust-clippy/wiki#filter_next) | warn | using `filter(p).next()`, which is more succinctly expressed as `.find(p)`
59+
[float_arithmetic](https://github.com/Manishearth/rust-clippy/wiki#float_arithmetic) | allow | Any floating-point arithmetic statement
5960
[float_cmp](https://github.com/Manishearth/rust-clippy/wiki#float_cmp) | warn | using `==` or `!=` on float values (as floating-point operations usually involve rounding errors, it is always better to check for approximate equality within small bounds)
6061
[for_kv_map](https://github.com/Manishearth/rust-clippy/wiki#for_kv_map) | warn | looping on a map using `iter` when `keys` or `values` would do
6162
[for_loop_over_option](https://github.com/Manishearth/rust-clippy/wiki#for_loop_over_option) | warn | for-looping over an `Option`, which is more clearly expressed as an `if let`
@@ -67,6 +68,7 @@ name
6768
[indexing_slicing](https://github.com/Manishearth/rust-clippy/wiki#indexing_slicing) | allow | indexing/slicing usage
6869
[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`
6970
[inline_always](https://github.com/Manishearth/rust-clippy/wiki#inline_always) | warn | `#[inline(always)]` is a bad idea in most cases
71+
[integer_arithmetic](https://github.com/Manishearth/rust-clippy/wiki#integer_arithmetic) | allow | Any integer arithmetic statement
7072
[invalid_regex](https://github.com/Manishearth/rust-clippy/wiki#invalid_regex) | deny | finds invalid regular expressions in `Regex::new(_)` invocations
7173
[invalid_upcast_comparisons](https://github.com/Manishearth/rust-clippy/wiki#invalid_upcast_comparisons) | warn | a comparison involving an upcast which is always true or false
7274
[items_after_statements](https://github.com/Manishearth/rust-clippy/wiki#items_after_statements) | allow | finds blocks where an item comes after a statement

src/arithmetic.rs

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
use rustc::hir;
2+
use rustc::lint::*;
3+
use syntax::codemap::Span;
4+
use utils::span_lint;
5+
6+
/// **What it does:** This lint checks for plain integer arithmetic
7+
///
8+
/// **Why is this bad?** This is only checked against overflow in debug builds.
9+
/// In some applications one wants explicitly checked, wrapping or saturating
10+
/// arithmetic.
11+
///
12+
/// **Known problems:** None
13+
///
14+
/// **Example:**
15+
/// ```
16+
/// a + 1
17+
/// ```
18+
declare_restriction_lint! {
19+
pub INTEGER_ARITHMETIC,
20+
"Any integer arithmetic statement"
21+
}
22+
23+
/// **What it does:** This lint checks for float arithmetic
24+
///
25+
/// **Why is this bad?** For some embedded systems or kernel development, it
26+
/// can be useful to rule out floating-point numbers
27+
///
28+
/// **Known problems:** None
29+
///
30+
/// **Example:**
31+
/// ```
32+
/// a + 1.0
33+
/// ```
34+
declare_restriction_lint! {
35+
pub FLOAT_ARITHMETIC,
36+
"Any floating-point arithmetic statement"
37+
}
38+
39+
#[derive(Copy, Clone, Default)]
40+
pub struct Arithmetic {
41+
span: Option<Span>
42+
}
43+
44+
impl LintPass for Arithmetic {
45+
fn get_lints(&self) -> LintArray {
46+
lint_array!(INTEGER_ARITHMETIC, FLOAT_ARITHMETIC)
47+
}
48+
}
49+
50+
impl LateLintPass for Arithmetic {
51+
fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
52+
if let Some(_) = self.span { return; }
53+
match expr.node {
54+
hir::ExprBinary(ref op, ref l, ref r) => {
55+
match op.node {
56+
hir::BiAnd | hir::BiOr | hir::BiBitAnd |
57+
hir::BiBitOr | hir::BiBitXor | hir::BiShl | hir::BiShr |
58+
hir::BiEq | hir::BiLt | hir::BiLe | hir::BiNe | hir::BiGe |
59+
hir::BiGt => return,
60+
_ => ()
61+
}
62+
let (l_ty, r_ty) = (cx.tcx.expr_ty(l), cx.tcx.expr_ty(r));
63+
if l_ty.is_integral() && r_ty.is_integral() {
64+
span_lint(cx,
65+
INTEGER_ARITHMETIC,
66+
expr.span,
67+
"integer arithmetic detected");
68+
self.span = Some(expr.span);
69+
} else if l_ty.is_floating_point() && r_ty.is_floating_point() {
70+
span_lint(cx,
71+
FLOAT_ARITHMETIC,
72+
expr.span,
73+
"floating-point arithmetic detected");
74+
self.span = Some(expr.span);
75+
}
76+
},
77+
hir::ExprUnary(hir::UnOp::UnNeg, ref arg) => {
78+
let ty = cx.tcx.expr_ty(arg);
79+
if ty.is_integral() {
80+
span_lint(cx,
81+
INTEGER_ARITHMETIC,
82+
expr.span,
83+
"integer arithmetic detected");
84+
self.span = Some(expr.span);
85+
} else if ty.is_floating_point() {
86+
span_lint(cx,
87+
FLOAT_ARITHMETIC,
88+
expr.span,
89+
"floating-point arithmetic detected");
90+
self.span = Some(expr.span);
91+
}
92+
},
93+
_ => ()
94+
}
95+
}
96+
97+
fn check_expr_post(&mut self, _: &LateContext, expr: &hir::Expr) {
98+
if Some(expr.span) == self.span {
99+
self.span = None;
100+
}
101+
}
102+
}

src/lib.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#![feature(question_mark)]
88
#![feature(stmt_expr_attributes)]
99
#![allow(indexing_slicing, shadow_reuse, unknown_lints)]
10+
#![allow(float_arithmetic, integer_arithmetic)]
1011

1112
// this only exists to allow the "dogfood" integration test to work
1213
#[allow(dead_code)]
@@ -43,12 +44,19 @@ extern crate rustc_const_eval;
4344
extern crate rustc_const_math;
4445
use rustc_plugin::Registry;
4546

47+
macro_rules! declare_restriction_lint {
48+
{ pub $name:tt, $description:tt } => {
49+
declare_lint! { pub $name, Allow, $description }
50+
};
51+
}
52+
4653
pub mod consts;
4754
#[macro_use]
4855
pub mod utils;
4956

5057
// begin lints modules, do not remove this comment, it’s used in `update_lints`
5158
pub mod approx_const;
59+
pub mod arithmetic;
5260
pub mod array_indexing;
5361
pub mod attrs;
5462
pub mod bit_mask;
@@ -238,6 +246,12 @@ pub fn plugin_registrar(reg: &mut Registry) {
238246
reg.register_late_lint_pass(box neg_multiply::NegMultiply);
239247
reg.register_late_lint_pass(box unsafe_removed_from_name::UnsafeNameRemoval);
240248
reg.register_late_lint_pass(box mem_forget::MemForget);
249+
reg.register_late_lint_pass(box arithmetic::Arithmetic::default());
250+
251+
reg.register_lint_group("clippy_restrictions", vec![
252+
arithmetic::FLOAT_ARITHMETIC,
253+
arithmetic::INTEGER_ARITHMETIC,
254+
]);
241255

242256
reg.register_lint_group("clippy_pedantic", vec![
243257
array_indexing::INDEXING_SLICING,

tests/compile-fail/arithmetic.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#![feature(plugin)]
2+
#![plugin(clippy)]
3+
4+
#![deny(integer_arithmetic, float_arithmetic)]
5+
#![allow(unused, shadow_reuse, shadow_unrelated, no_effect)]
6+
fn main() {
7+
let i = 1i32;
8+
1 + i; //~ERROR integer arithmetic detected
9+
i * 2; //~ERROR integer arithmetic detected
10+
1 % //~ERROR integer arithmetic detected
11+
i / 2; // no error, this is part of the expression in the preceding line
12+
i - 2 + 2 - i; //~ERROR integer arithmetic detected
13+
-i; //~ERROR integer arithmetic detected
14+
15+
i & 1; // no wrapping
16+
i | 1;
17+
i ^ 1;
18+
i >> 1;
19+
i << 1;
20+
21+
let f = 1.0f32;
22+
23+
f * 2.0; //~ERROR floating-point arithmetic detected
24+
25+
1.0 + f; //~ERROR floating-point arithmetic detected
26+
f * 2.0; //~ERROR floating-point arithmetic detected
27+
f / 2.0; //~ERROR floating-point arithmetic detected
28+
f - 2.0 * 4.2; //~ERROR floating-point arithmetic detected
29+
-f; //~ERROR floating-point arithmetic detected
30+
}

util/update_lints.py

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,18 @@
2121
" (?P<desc>(?:[^"\\]+|\\.)*) " \s* [})]
2222
''', re.VERBOSE | re.DOTALL)
2323

24+
declare_restriction_lint_re = re.compile(r'''
25+
declare_restriction_lint! \s* [{(] \s*
26+
pub \s+ (?P<name>[A-Z_][A-Z_0-9]*) \s*,\s*
27+
" (?P<desc>(?:[^"\\]+|\\.)*) " \s* [})]
28+
''', re.VERBOSE | re.DOTALL)
29+
2430
nl_escape_re = re.compile(r'\\\n\s*')
2531

2632
wiki_link = 'https://github.com/Manishearth/rust-clippy/wiki'
2733

2834

29-
def collect(lints, deprecated_lints, fn):
35+
def collect(lints, deprecated_lints, restriction_lints, fn):
3036
"""Collect all lints from a file.
3137
3238
Adds entries to the lints list as `(module, name, level, desc)`.
@@ -48,6 +54,14 @@ def collect(lints, deprecated_lints, fn):
4854
match.group('name').lower(),
4955
desc.replace('\\"', '"')))
5056

57+
for match in declare_restriction_lint_re.finditer(code):
58+
# remove \-newline escapes from description string
59+
desc = nl_escape_re.sub('', match.group('desc'))
60+
restriction_lints.append((os.path.splitext(os.path.basename(fn))[0],
61+
match.group('name').lower(),
62+
"allow",
63+
desc.replace('\\"', '"')))
64+
5165

5266
def gen_table(lints, link=None):
5367
"""Write lint table in Markdown format."""
@@ -86,7 +100,6 @@ def gen_deprecated(lints):
86100
for lint in lints:
87101
yield ' store.register_removed("%s", "%s");\n' % (lint[1], lint[2])
88102

89-
90103
def replace_region(fn, region_start, region_end, callback,
91104
replace_start=True, write_back=True):
92105
"""Replace a region in a file delimited by two lines matching regexes.
@@ -128,6 +141,7 @@ def replace_region(fn, region_start, region_end, callback,
128141
def main(print_only=False, check=False):
129142
lints = []
130143
deprecated_lints = []
144+
restriction_lints = []
131145

132146
# check directory
133147
if not os.path.isfile('src/lib.rs'):
@@ -138,22 +152,24 @@ def main(print_only=False, check=False):
138152
for root, _, files in os.walk('src'):
139153
for fn in files:
140154
if fn.endswith('.rs'):
141-
collect(lints, deprecated_lints, os.path.join(root, fn))
155+
collect(lints, deprecated_lints, restriction_lints,
156+
os.path.join(root, fn))
142157

143158
if print_only:
144-
sys.stdout.writelines(gen_table(lints))
159+
sys.stdout.writelines(gen_table(lints + restriction_lints))
145160
return
146161

147162
# replace table in README.md
148163
changed = replace_region(
149164
'README.md', r'^name +\|', '^$',
150-
lambda: gen_table(lints, link=wiki_link),
165+
lambda: gen_table(lints + restriction_lints, link=wiki_link),
151166
write_back=not check)
152167

153168
changed |= replace_region(
154169
'README.md',
155170
r'^There are \d+ lints included in this crate:', "",
156-
lambda: ['There are %d lints included in this crate:\n' % len(lints)],
171+
lambda: ['There are %d lints included in this crate:\n' % (len(lints)
172+
+ len(restriction_lints))],
157173
write_back=not check)
158174

159175
# update the links in the CHANGELOG
@@ -162,13 +178,14 @@ def main(print_only=False, check=False):
162178
"<!-- begin autogenerated links to wiki -->",
163179
"<!-- end autogenerated links to wiki -->",
164180
lambda: ["[`{0}`]: {1}#{0}\n".format(l[1], wiki_link) for l in
165-
sorted(lints + deprecated_lints, key=lambda l: l[1])],
181+
sorted(lints + restriction_lints + deprecated_lints,
182+
key=lambda l: l[1])],
166183
replace_start=False, write_back=not check)
167184

168185
# update the `pub mod` list
169186
changed |= replace_region(
170187
'src/lib.rs', r'begin lints modules', r'end lints modules',
171-
lambda: gen_mods(lints),
188+
lambda: gen_mods(lints + restriction_lints),
172189
replace_start=False, write_back=not check)
173190

174191
# same for "clippy" lint collection
@@ -190,6 +207,12 @@ def main(print_only=False, check=False):
190207
lambda: gen_group(lints, levels=('allow',)),
191208
replace_start=False, write_back=not check)
192209

210+
# same for "clippy_restrictions" lint collection
211+
changed |= replace_region(
212+
'src/lib.rs', r'reg.register_lint_group\("clippy_restrictions"',
213+
r'\]\);', lambda: gen_group(restriction_lints),
214+
replace_start=False, write_back=not check)
215+
193216
if check and changed:
194217
print('Please run util/update_lints.py to regenerate lints lists.')
195218
return 1

0 commit comments

Comments
 (0)