]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
Merge pull request #344 from Manishearth/reflet
[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 == "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                     if name == "eq" || name == "ne" || name == "is_nan" ||
128                             name.as_str().starts_with("eq_") ||
129                             name.as_str().ends_with("_eq") {
130                         return;
131                     }
132                 }
133                 span_lint(cx, FLOAT_CMP, expr.span, &format!(
134                     "{}-comparison of f32 or f64 detected. Consider changing this to \
135                      `abs({} - {}) < epsilon` for some suitable value of epsilon",
136                     binop_to_string(op), snippet(cx, left.span, ".."),
137                     snippet(cx, right.span, "..")));
138             }
139         }
140     }
141 }
142
143 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
144     if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
145         true
146     } else {
147         false
148     }
149 }
150
151 declare_lint!(pub CMP_OWNED, Warn,
152               "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
153
154 #[derive(Copy,Clone)]
155 pub struct CmpOwned;
156
157 impl LintPass for CmpOwned {
158     fn get_lints(&self) -> LintArray {
159         lint_array!(CMP_OWNED)
160     }
161 }
162
163 impl LateLintPass for CmpOwned {
164     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
165         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
166             if is_comparison_binop(cmp.node) {
167                 check_to_owned(cx, left, right.span);
168                 check_to_owned(cx, right, left.span)
169             }
170         }
171     }
172 }
173
174 fn check_to_owned(cx: &LateContext, expr: &Expr, other_span: Span) {
175     match expr.node {
176         ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
177             let name = ident.name;
178             if name == "to_string" ||
179                 name == "to_owned" && is_str_arg(cx, args) {
180                     span_lint(cx, CMP_OWNED, expr.span, &format!(
181                         "this creates an owned instance just for comparison. \
182                          Consider using `{}.as_slice()` to compare without allocation",
183                         snippet(cx, other_span, "..")))
184                 }
185         },
186         ExprCall(ref path, _) => {
187             if let &ExprPath(None, ref path) = &path.node {
188                 if match_path(path, &["String", "from_str"]) ||
189                     match_path(path, &["String", "from"]) {
190                         span_lint(cx, CMP_OWNED, expr.span, &format!(
191                             "this creates an owned instance just for comparison. \
192                              Consider using `{}.as_slice()` to compare without allocation",
193                             snippet(cx, other_span, "..")))
194                     }
195             }
196         },
197         _ => ()
198     }
199 }
200
201 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
202     args.len() == 1 && if let ty::TyStr =
203         walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty { true } else { false }
204 }
205
206 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
207
208 #[derive(Copy,Clone)]
209 pub struct ModuloOne;
210
211 impl LintPass for ModuloOne {
212     fn get_lints(&self) -> LintArray {
213         lint_array!(MODULO_ONE)
214     }
215 }
216
217 impl LateLintPass for ModuloOne {
218     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
219         if let ExprBinary(ref cmp, _, ref right) = expr.node {
220             if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
221                 if is_integer_literal(right, 1) {
222                     cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
223                 }
224             }
225         }
226     }
227 }
228
229 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
230
231 #[derive(Copy,Clone)]
232 pub struct PatternPass;
233
234 impl LintPass for PatternPass {
235     fn get_lints(&self) -> LintArray {
236         lint_array!(REDUNDANT_PATTERN)
237     }
238 }
239
240 impl LateLintPass for PatternPass {
241     fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
242         if let PatIdent(_, ref ident, Some(ref right)) = pat.node {
243             if right.node == PatWild(PatWildSingle) {
244                 cx.span_lint(REDUNDANT_PATTERN, pat.span, &format!(
245                     "the `{} @ _` pattern can be written as just `{}`",
246                     ident.node.name, ident.node.name));
247             }
248         }
249     }
250 }