]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
make float_cmp check for zero
[rust.git] / src / misc.rs
1 use rustc::lint::*;
2 use syntax::ptr::P;
3 use syntax::ast;
4 use syntax::ast::*;
5 use syntax::ast_util::{is_comparison_binop, binop_to_string};
6 use syntax::codemap::{Span, Spanned};
7 use syntax::visit::FnKind;
8 use rustc::middle::ty;
9 use std::borrow::Cow;
10
11 use utils::{match_path, snippet, snippet_block, span_lint, span_help_and_lint, walk_ptrs_ty};
12 use consts::constant;
13
14 /// Handles uncategorized lints
15 /// Currently handles linting of if-let-able matches
16 #[allow(missing_copy_implementations)]
17 pub struct MiscPass;
18
19
20 declare_lint!(pub SINGLE_MATCH, Warn,
21               "a match statement with a single nontrivial arm (i.e, where the other arm \
22                is `_ => {}`) is used; recommends `if let` instead");
23
24 impl LintPass for MiscPass {
25     fn get_lints(&self) -> LintArray {
26         lint_array!(SINGLE_MATCH)
27     }
28
29     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
30         if let ExprMatch(ref ex, ref arms, ast::MatchSource::Normal) = expr.node {
31             // check preconditions: only two arms
32             if arms.len() == 2 &&
33                 // both of the arms have a single pattern and no guard
34                 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
35                 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
36                 // and the second pattern is a `_` wildcard: this is not strictly necessary,
37                 // since the exhaustiveness check will ensure the last one is a catch-all,
38                 // but in some cases, an explicit match is preferred to catch situations
39                 // when an enum is extended, so we don't consider these cases
40                 arms[1].pats[0].node == PatWild(PatWildSingle) &&
41                 // finally, we don't want any content in the second arm (unit or empty block)
42                 is_unit_expr(&*arms[1].body)
43             {
44                 let body_code = snippet_block(cx, arms[0].body.span, "..");
45                 let body_code = if let ExprBlock(_) = arms[0].body.node {
46                     body_code
47                 } else {
48                     Cow::Owned(format!("{{ {} }}", body_code))
49                 };
50                 span_help_and_lint(cx, SINGLE_MATCH, expr.span,
51                       "you seem to be trying to use match for \
52                       destructuring a single pattern. Did you mean to \
53                       use `if let`?",
54                       &*format!("try\nif let {} = {} {}",
55                                 snippet(cx, arms[0].pats[0].span, ".."),
56                                 snippet(cx, ex.span, ".."),
57                                 body_code)
58                 );
59             }
60         }
61     }
62 }
63
64 fn is_unit_expr(expr: &Expr) -> bool {
65     match expr.node {
66         ExprTup(ref v) if v.is_empty() => true,
67         ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
68         _ => false,
69     }
70 }
71
72
73 declare_lint!(pub TOPLEVEL_REF_ARG, Warn,
74               "a function argument is declared `ref` (i.e. `fn foo(ref x: u8)`, but not \
75                `fn foo((ref x, ref y): (u8, u8))`)");
76
77 #[allow(missing_copy_implementations)]
78 pub struct TopLevelRefPass;
79
80 impl LintPass for TopLevelRefPass {
81     fn get_lints(&self) -> LintArray {
82         lint_array!(TOPLEVEL_REF_ARG)
83     }
84
85     fn check_fn(&mut self, cx: &Context, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
86         if let FnKind::FkFnBlock = k {
87             // Does not apply to closures
88             return
89         }
90         for ref arg in &decl.inputs {
91             if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
92                 span_lint(cx,
93                     TOPLEVEL_REF_ARG,
94                     arg.pat.span,
95                     "`ref` directly on a function argument is ignored. Consider using a reference type instead."
96                 );
97             }
98         }
99     }
100 }
101
102 declare_lint!(pub CMP_NAN, Deny,
103               "comparisons to NAN (which will always return false, which is probably not intended)");
104
105 #[derive(Copy,Clone)]
106 pub struct CmpNan;
107
108 impl LintPass for CmpNan {
109     fn get_lints(&self) -> LintArray {
110         lint_array!(CMP_NAN)
111     }
112
113     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
114         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
115             if is_comparison_binop(cmp.node) {
116                 if let &ExprPath(_, ref path) = &left.node {
117                     check_nan(cx, path, expr.span);
118                 }
119                 if let &ExprPath(_, ref path) = &right.node {
120                     check_nan(cx, path, expr.span);
121                 }
122             }
123         }
124     }
125 }
126
127 fn check_nan(cx: &Context, path: &Path, span: Span) {
128     path.segments.last().map(|seg| if seg.identifier.name == "NAN" {
129         span_lint(cx, CMP_NAN, span,
130                   "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
131     });
132 }
133
134 declare_lint!(pub FLOAT_CMP, Warn,
135               "using `==` or `!=` on float values (as floating-point operations \
136                usually involve rounding errors, it is always better to check for approximate \
137                equality within small bounds)");
138
139 #[derive(Copy,Clone)]
140 pub struct FloatCmp;
141
142 impl LintPass for FloatCmp {
143     fn get_lints(&self) -> LintArray {
144         lint_array!(FLOAT_CMP)
145     }
146
147     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
148         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
149             let op = cmp.node;
150             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
151                 if constant(cx, left).or_else(|| constant(cx, right)).map_or(
152                         false, |c| c.as_float().map_or(false, |f| f == 0.0)) {
153                     return;
154                 }
155                 span_lint(cx, FLOAT_CMP, expr.span, &format!(
156                     "{}-comparison of f32 or f64 detected. Consider changing this to \
157                      `abs({} - {}) < epsilon` for some suitable value of epsilon",
158                     binop_to_string(op), snippet(cx, left.span, ".."),
159                     snippet(cx, right.span, "..")));
160             }
161         }
162     }
163 }
164
165 fn is_float(cx: &Context, expr: &Expr) -> bool {
166     if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
167         true
168     } else {
169         false
170     }
171 }
172
173 declare_lint!(pub PRECEDENCE, Warn,
174               "expressions where precedence may trip up the unwary reader of the source; \
175                suggests adding parentheses, e.g. `x << 2 + y` will be parsed as `x << (2 + y)`");
176
177 #[derive(Copy,Clone)]
178 pub struct Precedence;
179
180 impl LintPass for Precedence {
181     fn get_lints(&self) -> LintArray {
182         lint_array!(PRECEDENCE)
183     }
184
185     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
186         if let ExprBinary(Spanned { node: op, ..}, ref left, ref right) = expr.node {
187             if is_bit_op(op) && (is_arith_expr(left) || is_arith_expr(right)) {
188                 span_lint(cx, PRECEDENCE, expr.span,
189                     "operator precedence can trip the unwary. Consider adding parentheses \
190                      to the subexpression");
191             }
192         }
193     }
194 }
195
196 fn is_arith_expr(expr : &Expr) -> bool {
197     match expr.node {
198         ExprBinary(Spanned { node: op, ..}, _, _) => is_arith_op(op),
199         _ => false
200     }
201 }
202
203 fn is_bit_op(op : BinOp_) -> bool {
204     match op {
205         BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => true,
206         _ => false
207     }
208 }
209
210 fn is_arith_op(op : BinOp_) -> bool {
211     match op {
212         BiAdd | BiSub | BiMul | BiDiv | BiRem => true,
213         _ => false
214     }
215 }
216
217 declare_lint!(pub CMP_OWNED, Warn,
218               "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
219
220 #[derive(Copy,Clone)]
221 pub struct CmpOwned;
222
223 impl LintPass for CmpOwned {
224     fn get_lints(&self) -> LintArray {
225         lint_array!(CMP_OWNED)
226     }
227
228     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
229         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
230             if is_comparison_binop(cmp.node) {
231                 check_to_owned(cx, left, right.span);
232                 check_to_owned(cx, right, left.span)
233             }
234         }
235     }
236 }
237
238 fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
239     match &expr.node {
240         &ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
241             let name = ident.name;
242             if name == "to_string" ||
243                 name == "to_owned" && is_str_arg(cx, args) {
244                     span_lint(cx, CMP_OWNED, expr.span, &format!(
245                         "this creates an owned instance just for comparison. \
246                          Consider using `{}.as_slice()` to compare without allocation",
247                         snippet(cx, other_span, "..")))
248                 }
249         },
250         &ExprCall(ref path, _) => {
251             if let &ExprPath(None, ref path) = &path.node {
252                 if match_path(path, &["String", "from_str"]) ||
253                     match_path(path, &["String", "from"]) {
254                         span_lint(cx, CMP_OWNED, expr.span, &format!(
255                             "this creates an owned instance just for comparison. \
256                              Consider using `{}.as_slice()` to compare without allocation",
257                             snippet(cx, other_span, "..")))
258                     }
259             }
260         },
261         _ => ()
262     }
263 }
264
265 fn is_str_arg(cx: &Context, args: &[P<Expr>]) -> bool {
266     args.len() == 1 && if let ty::TyStr =
267         walk_ptrs_ty(cx.tcx.expr_ty(&*args[0])).sty { true } else { false }
268 }
269
270 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
271
272 #[derive(Copy,Clone)]
273 pub struct ModuloOne;
274
275 impl LintPass for ModuloOne {
276     fn get_lints(&self) -> LintArray {
277         lint_array!(MODULO_ONE)
278     }
279
280     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
281         if let ExprBinary(ref cmp, _, ref right) = expr.node {
282             if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
283                 if is_lit_one(right) {
284                     cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
285                 }
286             }
287         }
288     }
289 }
290
291 fn is_lit_one(expr: &Expr) -> bool {
292     if let ExprLit(ref spanned) = expr.node {
293         if let LitInt(1, _) = spanned.node {
294             return true;
295         }
296     }
297     false
298 }