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