]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
Merged #366
[rust.git] / src / misc.rs
1 use rustc::lint::*;
2 use syntax::ptr::P;
3 use rustc_front::hir::*;
4 use reexport::*;
5 use rustc_front::util::{is_comparison_binop, binop_to_string};
6 use syntax::codemap::{Span, Spanned};
7 use rustc_front::visit::FnKind;
8 use rustc::middle::ty;
9
10 use utils::{get_item_name, match_path, snippet, span_lint, walk_ptrs_ty, is_integer_literal};
11 use utils::span_help_and_lint;
12 use consts::constant;
13
14 declare_lint!(pub TOPLEVEL_REF_ARG, Warn,
15               "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
16                or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
17                references with `&`.");
18
19 #[allow(missing_copy_implementations)]
20 pub struct TopLevelRefPass;
21
22 impl LintPass for TopLevelRefPass {
23     fn get_lints(&self) -> LintArray {
24         lint_array!(TOPLEVEL_REF_ARG)
25     }
26 }
27
28 impl LateLintPass for TopLevelRefPass {
29     fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
30         if let FnKind::Closure = k {
31             // Does not apply to closures
32             return
33         }
34         for ref arg in &decl.inputs {
35             if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
36                 span_lint(cx,
37                     TOPLEVEL_REF_ARG,
38                     arg.pat.span,
39                     "`ref` directly on a function argument is ignored. Consider using a reference type instead."
40                 );
41             }
42         }
43     }
44     fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
45         if_let_chain! {
46             [
47             let StmtDecl(ref d, _) = s.node,
48             let DeclLocal(ref l) = d.node,
49             let PatIdent(BindByRef(_), i, None) = l.pat.node,
50             let Some(ref init) = l.init
51             ], {
52                 let tyopt = if let Some(ref ty) = l.ty {
53                     format!(": {:?} ", ty)
54                 } else {
55                     "".to_owned()
56                 };
57                 span_help_and_lint(cx,
58                     TOPLEVEL_REF_ARG,
59                     l.pat.span,
60                     "`ref` on an entire `let` pattern is discouraged, take a reference with & instead",
61                     &format!("try `let {} {}= &{};`", snippet(cx, i.span, "_"),
62                              tyopt, snippet(cx, init.span, "_"))
63                 );
64             }
65         };
66     }
67 }
68
69 declare_lint!(pub CMP_NAN, Deny,
70               "comparisons to NAN (which will always return false, which is probably not intended)");
71
72 #[derive(Copy,Clone)]
73 pub struct CmpNan;
74
75 impl LintPass for CmpNan {
76     fn get_lints(&self) -> LintArray {
77         lint_array!(CMP_NAN)
78     }
79 }
80
81 impl LateLintPass for CmpNan {
82     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
83         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
84             if is_comparison_binop(cmp.node) {
85                 if let &ExprPath(_, ref path) = &left.node {
86                     check_nan(cx, path, expr.span);
87                 }
88                 if let &ExprPath(_, ref path) = &right.node {
89                     check_nan(cx, path, expr.span);
90                 }
91             }
92         }
93     }
94 }
95
96 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
97     path.segments.last().map(|seg| if seg.identifier.name.as_str() == "NAN" {
98         span_lint(cx, CMP_NAN, span,
99             "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
100     });
101 }
102
103 declare_lint!(pub FLOAT_CMP, Warn,
104               "using `==` or `!=` on float values (as floating-point operations \
105                usually involve rounding errors, it is always better to check for approximate \
106                equality within small bounds)");
107
108 #[derive(Copy,Clone)]
109 pub struct FloatCmp;
110
111 impl LintPass for FloatCmp {
112     fn get_lints(&self) -> LintArray {
113         lint_array!(FLOAT_CMP)
114     }
115 }
116
117 impl LateLintPass for FloatCmp {
118     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
119         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
120             let op = cmp.node;
121             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
122                 if constant(cx, left).or_else(|| constant(cx, right)).map_or(
123                         false, |c| c.0.as_float().map_or(false, |f| f == 0.0)) {
124                     return;
125                 }
126                 if let Some(name) = get_item_name(cx, expr) {
127                     let name = name.as_str();
128                     if name == "eq" || name == "ne" || name == "is_nan" ||
129                             name.starts_with("eq_") ||
130                             name.ends_with("_eq") {
131                         return;
132                     }
133                 }
134                 span_lint(cx, FLOAT_CMP, expr.span, &format!(
135                     "{}-comparison of f32 or f64 detected. Consider changing this to \
136                      `abs({} - {}) < epsilon` for some suitable value of epsilon",
137                     binop_to_string(op), snippet(cx, left.span, ".."),
138                     snippet(cx, right.span, "..")));
139             }
140         }
141     }
142 }
143
144 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
145     if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
146         true
147     } else {
148         false
149     }
150 }
151
152 declare_lint!(pub CMP_OWNED, Warn,
153               "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
154
155 #[derive(Copy,Clone)]
156 pub struct CmpOwned;
157
158 impl LintPass for CmpOwned {
159     fn get_lints(&self) -> LintArray {
160         lint_array!(CMP_OWNED)
161     }
162 }
163
164 impl LateLintPass for CmpOwned {
165     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
166         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
167             if is_comparison_binop(cmp.node) {
168                 check_to_owned(cx, left, right.span, true, cmp.span);
169                 check_to_owned(cx, right, left.span, false, cmp.span)
170             }
171         }
172     }
173 }
174
175 fn check_to_owned(cx: &LateContext, expr: &Expr, other_span: Span, left: bool, op: Span) {
176     let snip = match expr.node {
177         ExprMethodCall(Spanned{node: ref name, ..}, _, ref args) if args.len() == 1 => {
178             if name.as_str() == "to_string" ||
179                 name.as_str() == "to_owned" && is_str_arg(cx, args) {
180                     snippet(cx, args[0].span, "..")
181                 } else {
182                     return
183                 }
184         },
185         ExprCall(ref path, ref v) if v.len() == 1 => {
186             if let &ExprPath(None, ref path) = &path.node {
187                 if match_path(path, &["String", "from_str"]) ||
188                     match_path(path, &["String", "from"]) {
189                             snippet(cx, v[0].span, "..")
190                     } else {
191                         return
192                     }
193             } else {
194                 return
195             }
196         },
197         _ => return
198     };
199     if left {
200         span_lint(cx, CMP_OWNED, expr.span, &format!(
201         "this creates an owned instance just for comparison. Consider using \
202         `{} {} {}` to compare without allocation", snip,
203         snippet(cx, op, "=="), snippet(cx, other_span, "..")));
204     } else {
205         span_lint(cx, CMP_OWNED, expr.span, &format!(
206         "this creates an owned instance just for comparison. Consider using \
207         `{} {} {}` to compare without allocation",
208         snippet(cx, other_span, ".."), snippet(cx, op, "=="),  snip));
209     }
210
211 }
212
213 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
214     args.len() == 1 && if let ty::TyStr =
215         walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty { true } else { false }
216 }
217
218 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
219
220 #[derive(Copy,Clone)]
221 pub struct ModuloOne;
222
223 impl LintPass for ModuloOne {
224     fn get_lints(&self) -> LintArray {
225         lint_array!(MODULO_ONE)
226     }
227 }
228
229 impl LateLintPass for ModuloOne {
230     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
231         if let ExprBinary(ref cmp, _, ref right) = expr.node {
232             if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
233                 if is_integer_literal(right, 1) {
234                     cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
235                 }
236             }
237         }
238     }
239 }
240
241 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
242
243 #[derive(Copy,Clone)]
244 pub struct PatternPass;
245
246 impl LintPass for PatternPass {
247     fn get_lints(&self) -> LintArray {
248         lint_array!(REDUNDANT_PATTERN)
249     }
250 }
251
252 impl LateLintPass for PatternPass {
253     fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
254         if let PatIdent(_, ref ident, Some(ref right)) = pat.node {
255             if right.node == PatWild(PatWildSingle) {
256                 cx.span_lint(REDUNDANT_PATTERN, pat.span, &format!(
257                     "the `{} @ _` pattern can be written as just `{}`",
258                     ident.node.name, ident.node.name));
259             }
260         }
261     }
262 }