]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
rustup to 1.5.0-nightly (7bf4c885f 2015-09-26)
[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);
169                 check_to_owned(cx, right, left.span)
170             }
171         }
172     }
173 }
174
175 fn check_to_owned(cx: &LateContext, expr: &Expr, other_span: Span) {
176     match expr.node {
177         ExprMethodCall(Spanned{node: ref name, ..}, _, ref args) => {
178             if name.as_str() == "to_string" ||
179                 name.as_str() == "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 }