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