]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
Merge branch 'pr-78'
[rust.git] / src / misc.rs
1 use syntax::ptr::P;
2 use syntax::ast;
3 use syntax::ast::*;
4 use syntax::ast_util::{is_comparison_binop, binop_to_string};
5 use syntax::visit::{FnKind};
6 use rustc::lint::{Context, LintPass, LintArray, Lint, Level};
7 use rustc::middle::ty;
8 use syntax::codemap::{Span, Spanned};
9
10 use utils::{match_path, snippet, span_lint, span_help_and_lint};
11
12 pub fn walk_ty<'t>(ty: ty::Ty<'t>) -> ty::Ty<'t> {
13     match ty.sty {
14         ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => walk_ty(tm.ty),
15         _ => ty
16     }
17 }
18
19 /// Handles uncategorized lints
20 /// Currently handles linting of if-let-able matches
21 #[allow(missing_copy_implementations)]
22 pub struct MiscPass;
23
24
25 declare_lint!(pub SINGLE_MATCH, Warn,
26               "Warn on usage of matches with a single nontrivial arm");
27
28 impl LintPass for MiscPass {
29     fn get_lints(&self) -> LintArray {
30         lint_array!(SINGLE_MATCH)
31     }
32
33     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
34         if let ExprMatch(ref ex, ref arms, ast::MatchSource::Normal) = expr.node {
35             if arms.len() == 2 {
36                 if arms[0].guard.is_none() && arms[1].pats.len() == 1 {
37                     match arms[1].body.node {
38                         ExprTup(ref v) if v.is_empty() && arms[1].guard.is_none() => (),
39                         ExprBlock(ref b) if b.stmts.is_empty() && arms[1].guard.is_none() => (),
40                          _ => return
41                     }
42                     // In some cases, an exhaustive match is preferred to catch situations when
43                     // an enum is extended. So we only consider cases where a `_` wildcard is used
44                     if arms[1].pats[0].node == PatWild(PatWildSingle) &&
45                             arms[0].pats.len() == 1 {
46                         span_help_and_lint(cx, SINGLE_MATCH, expr.span,
47                               "You seem to be trying to use match for \
48                               destructuring a single type. Did you mean to \
49                               use `if let`?",
50                               &*format!("Try if let {} = {} {{ ... }}",
51                                       snippet(cx, arms[0].pats[0].span, ".."),
52                                       snippet(cx, ex.span, ".."))
53                         );
54                     }
55                 }
56             }
57         }
58     }
59 }
60
61
62 declare_lint!(pub STR_TO_STRING, Warn, "Warn when a String could use to_owned() instead of to_string()");
63
64 #[allow(missing_copy_implementations)]
65 pub struct StrToStringPass;
66
67 impl LintPass for StrToStringPass {
68     fn get_lints(&self) -> LintArray {
69         lint_array!(STR_TO_STRING)
70     }
71
72     fn check_expr(&mut self, cx: &Context, expr: &ast::Expr) {
73         match expr.node {
74             ast::ExprMethodCall(ref method, _, ref args)
75                 if method.node.name == "to_string"
76                 && is_str(cx, &*args[0]) => {
77                 span_lint(cx, STR_TO_STRING, expr.span, "str.to_owned() is faster");
78             },
79             _ => ()
80         }
81
82         fn is_str(cx: &Context, expr: &ast::Expr) -> bool {
83             match walk_ty(cx.tcx.expr_ty(expr)).sty {
84                 ty::TyStr => true,
85                 _ => false
86             }
87         }
88     }
89 }
90
91
92 declare_lint!(pub TOPLEVEL_REF_ARG, Warn, "Warn about pattern matches with top-level `ref` bindings");
93
94 #[allow(missing_copy_implementations)]
95 pub struct TopLevelRefPass;
96
97 impl LintPass for TopLevelRefPass {
98     fn get_lints(&self) -> LintArray {
99         lint_array!(TOPLEVEL_REF_ARG)
100     }
101
102     fn check_fn(&mut self, cx: &Context, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
103         for ref arg in decl.inputs.iter() {
104             if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
105                 span_lint(cx,
106                     TOPLEVEL_REF_ARG,
107                     arg.pat.span,
108                     "`ref` directly on a function argument is ignored. Have you considered using a reference type instead?"
109                 );
110             }
111         }
112     }
113 }
114
115 declare_lint!(pub CMP_NAN, Deny, "Deny comparisons to std::f32::NAN or std::f64::NAN");
116
117 #[derive(Copy,Clone)]
118 pub struct CmpNan;
119
120 impl LintPass for CmpNan {
121     fn get_lints(&self) -> LintArray {
122         lint_array!(CMP_NAN)
123     }
124
125     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
126         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
127             if is_comparison_binop(cmp.node) {
128                 if let &ExprPath(_, ref path) = &left.node {
129                     check_nan(cx, path, expr.span);
130                 }
131                 if let &ExprPath(_, ref path) = &right.node {
132                     check_nan(cx, path, expr.span);
133                 }
134             }
135         }
136     }
137 }
138
139 fn check_nan(cx: &Context, path: &Path, span: Span) {
140     path.segments.last().map(|seg| if seg.identifier.name == "NAN" {
141         span_lint(cx, CMP_NAN, span,
142                   "Doomed comparison with NAN, use std::{f32,f64}::is_nan instead");
143     });
144 }
145
146 declare_lint!(pub FLOAT_CMP, Warn,
147               "Warn on ==/!= comparison of floaty values");
148
149 #[derive(Copy,Clone)]
150 pub struct FloatCmp;
151
152 impl LintPass for FloatCmp {
153     fn get_lints(&self) -> LintArray {
154         lint_array!(FLOAT_CMP)
155     }
156
157     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
158         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
159             let op = cmp.node;
160             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
161                 span_lint(cx, FLOAT_CMP, expr.span, &format!(
162                     "{}-Comparison of f32 or f64 detected. You may want to change this to 'abs({} - {}) < epsilon' for some suitable value of epsilon",
163                     binop_to_string(op), snippet(cx, left.span, ".."),
164                     snippet(cx, right.span, "..")));
165             }
166         }
167     }
168 }
169
170 fn is_float(cx: &Context, expr: &Expr) -> bool {
171     if let ty::TyFloat(_) = walk_ty(cx.tcx.expr_ty(expr)).sty {
172         true
173     } else {
174         false
175     }
176 }
177
178 declare_lint!(pub PRECEDENCE, Warn,
179               "Warn on mixing bit ops with integer arithmetic without parenthesis");
180
181 #[derive(Copy,Clone)]
182 pub struct Precedence;
183
184 impl LintPass for Precedence {
185     fn get_lints(&self) -> LintArray {
186         lint_array!(PRECEDENCE)
187     }
188
189     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
190         if let ExprBinary(Spanned { node: op, ..}, ref left, ref right) = expr.node {
191             if is_bit_op(op) && (is_arith_expr(left) || is_arith_expr(right)) {
192                 span_lint(cx, PRECEDENCE, expr.span,
193                     "Operator precedence can trip the unwary. Consider adding parenthesis to the subexpression.");
194             }
195         }
196     }
197 }
198
199 fn is_arith_expr(expr : &Expr) -> bool {
200     match expr.node {
201         ExprBinary(Spanned { node: op, ..}, _, _) => is_arith_op(op),
202         _ => false
203     }
204 }
205
206 fn is_bit_op(op : BinOp_) -> bool {
207     match op {
208         BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => true,
209         _ => false
210     }
211 }
212
213 fn is_arith_op(op : BinOp_) -> bool {
214     match op {
215         BiAdd | BiSub | BiMul | BiDiv | BiRem => true,
216         _ => false
217     }
218 }
219
220 declare_lint!(pub CMP_OWNED, Warn,
221               "Warn on creating an owned string just for comparison");
222
223 #[derive(Copy,Clone)]
224 pub struct CmpOwned;
225
226 impl LintPass for CmpOwned {
227     fn get_lints(&self) -> LintArray {
228         lint_array!(CMP_OWNED)
229     }
230
231     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
232         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
233             if is_comparison_binop(cmp.node) {
234                 check_to_owned(cx, left, right.span);
235                 check_to_owned(cx, right, left.span)
236             }
237         }
238     }
239 }
240
241 fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
242     match &expr.node {
243         &ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
244             let name = ident.name;
245             if name == "to_string" ||
246                 name == "to_owned" && is_str_arg(cx, args) {
247                     span_lint(cx, CMP_OWNED, expr.span, &format!(
248                         "this creates an owned instance just for comparison. \
249                          Consider using {}.as_slice() to compare without allocation",
250                         snippet(cx, other_span, "..")))
251                 }
252         },
253         &ExprCall(ref path, _) => {
254             if let &ExprPath(None, ref path) = &path.node {
255                 if match_path(path, &["String", "from_str"]) ||
256                     match_path(path, &["String", "from"]) {
257                         span_lint(cx, CMP_OWNED, expr.span, &format!(
258                             "this creates an owned instance just for comparison. \
259                              Consider using {}.as_slice() to compare without allocation",
260                             snippet(cx, other_span, "..")))
261                     }
262             }
263         },
264         _ => ()
265     }
266 }
267
268 fn is_str_arg(cx: &Context, args: &[P<Expr>]) -> bool {
269     args.len() == 1 && if let ty::TyStr =
270         walk_ty(cx.tcx.expr_ty(&*args[0])).sty { true } else { false }
271 }
272
273 declare_lint!(pub NEEDLESS_RETURN, Warn,
274               "Warn on using a return statement where an expression would be enough");
275
276 #[derive(Copy,Clone)]
277 pub struct NeedlessReturn;
278
279 impl NeedlessReturn {
280     // Check the final stmt or expr in a block for unnecessary return.
281     fn check_block_return(&mut self, cx: &Context, block: &Block) {
282         if let Some(ref expr) = block.expr {
283             self.check_final_expr(cx, expr);
284         } else if let Some(stmt) = block.stmts.last() {
285             if let StmtSemi(ref expr, _) = stmt.node {
286                 if let ExprRet(Some(ref inner)) = expr.node {
287                     self.emit_lint(cx, (expr.span, inner.span));
288                 }
289             }
290         }
291     }
292
293     // Check a the final expression in a block if it's a return.
294     fn check_final_expr(&mut self, cx: &Context, expr: &Expr) {
295         match expr.node {
296             // simple return is always "bad"
297             ExprRet(Some(ref inner)) => {
298                 self.emit_lint(cx, (expr.span, inner.span));
299             }
300             // a whole block? check it!
301             ExprBlock(ref block) => {
302                 self.check_block_return(cx, block);
303             }
304             // an if/if let expr, check both exprs
305             // note, if without else is going to be a type checking error anyways
306             // (except for unit type functions) so we don't match it
307             ExprIf(_, ref ifblock, Some(ref elsexpr)) |
308             ExprIfLet(_, _, ref ifblock, Some(ref elsexpr)) => {
309                 self.check_block_return(cx, ifblock);
310                 self.check_final_expr(cx, elsexpr);
311             }
312             // a match expr, check all arms
313             ExprMatch(_, ref arms, _) => {
314                 for arm in arms {
315                     self.check_final_expr(cx, &*arm.body);
316                 }
317             }
318             _ => { }
319         }
320     }
321
322     fn emit_lint(&mut self, cx: &Context, spans: (Span, Span)) {
323         span_lint(cx, NEEDLESS_RETURN, spans.0, &format!(
324             "unneeded return statement. Consider using {} \
325              without the trailing semicolon",
326             snippet(cx, spans.1, "..")))
327     }
328 }
329
330 impl LintPass for NeedlessReturn {
331     fn get_lints(&self) -> LintArray {
332         lint_array!(NEEDLESS_RETURN)
333     }
334
335     fn check_fn(&mut self, cx: &Context, _: FnKind, _: &FnDecl,
336                 block: &Block, _: Span, _: ast::NodeId) {
337         self.check_block_return(cx, block);
338     }
339 }
340
341
342 declare_lint!(pub MODULO_ONE, Warn, "Warn on expressions that include % 1, which is always 0");
343
344 #[derive(Copy,Clone)]
345 pub struct ModuloOne;
346
347 impl LintPass for ModuloOne {
348     fn get_lints(&self) -> LintArray {
349         lint_array!(MODULO_ONE)
350     }
351
352     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
353         if let ExprBinary(ref cmp, _, ref right) = expr.node {
354             if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
355                 if is_lit_one(right) {
356                     cx.span_lint(MODULO_ONE, expr.span, "Any number modulo 1 will be 0");
357                 }
358             }
359         }
360     }
361 }
362
363 fn is_lit_one(expr: &Expr) -> bool {
364     if let ExprLit(ref spanned) = expr.node {
365         if let LitInt(1, _) = spanned.node {
366             return true;
367         }
368     }
369     false
370 }