]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
Merge pull request #310 from Manishearth/len_zero
[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};
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                 if let Some(name) = get_item_name(cx, expr) {
96                     if name == "eq" || name == "ne" ||
97                             name.as_str().starts_with("eq_") ||
98                             name.as_str().ends_with("_eq") {
99                         return;
100                     }
101                 }
102                 span_lint(cx, FLOAT_CMP, expr.span, &format!(
103                     "{}-comparison of f32 or f64 detected. Consider changing this to \
104                      `abs({} - {}) < epsilon` for some suitable value of epsilon",
105                     binop_to_string(op), snippet(cx, left.span, ".."),
106                     snippet(cx, right.span, "..")));
107             }
108         }
109     }
110 }
111
112 fn is_float(cx: &Context, expr: &Expr) -> bool {
113     if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
114         true
115     } else {
116         false
117     }
118 }
119
120 declare_lint!(pub CMP_OWNED, Warn,
121               "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
122
123 #[derive(Copy,Clone)]
124 pub struct CmpOwned;
125
126 impl LintPass for CmpOwned {
127     fn get_lints(&self) -> LintArray {
128         lint_array!(CMP_OWNED)
129     }
130
131     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
132         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
133             if is_comparison_binop(cmp.node) {
134                 check_to_owned(cx, left, right.span);
135                 check_to_owned(cx, right, left.span)
136             }
137         }
138     }
139 }
140
141 fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
142     match expr.node {
143         ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
144             let name = ident.name;
145             if name == "to_string" ||
146                 name == "to_owned" && is_str_arg(cx, args) {
147                     span_lint(cx, CMP_OWNED, expr.span, &format!(
148                         "this creates an owned instance just for comparison. \
149                          Consider using `{}.as_slice()` to compare without allocation",
150                         snippet(cx, other_span, "..")))
151                 }
152         },
153         ExprCall(ref path, _) => {
154             if let &ExprPath(None, ref path) = &path.node {
155                 if match_path(path, &["String", "from_str"]) ||
156                     match_path(path, &["String", "from"]) {
157                         span_lint(cx, CMP_OWNED, expr.span, &format!(
158                             "this creates an owned instance just for comparison. \
159                              Consider using `{}.as_slice()` to compare without allocation",
160                             snippet(cx, other_span, "..")))
161                     }
162             }
163         },
164         _ => ()
165     }
166 }
167
168 fn is_str_arg(cx: &Context, args: &[P<Expr>]) -> bool {
169     args.len() == 1 && if let ty::TyStr =
170         walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty { true } else { false }
171 }
172
173 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
174
175 #[derive(Copy,Clone)]
176 pub struct ModuloOne;
177
178 impl LintPass for ModuloOne {
179     fn get_lints(&self) -> LintArray {
180         lint_array!(MODULO_ONE)
181     }
182
183     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
184         if let ExprBinary(ref cmp, _, ref right) = expr.node {
185             if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
186                 if is_lit_one(right) {
187                     cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
188                 }
189             }
190         }
191     }
192 }
193
194 fn is_lit_one(expr: &Expr) -> bool {
195     if let ExprLit(ref spanned) = expr.node {
196         if let LitInt(1, _) = spanned.node {
197             return true;
198         }
199     }
200     false
201 }
202
203 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
204
205 #[derive(Copy,Clone)]
206 pub struct PatternPass;
207
208 impl LintPass for PatternPass {
209     fn get_lints(&self) -> LintArray {
210         lint_array!(REDUNDANT_PATTERN)
211     }
212
213     fn check_pat(&mut self, cx: &Context, pat: &Pat) {
214         if let PatIdent(_, ref ident, Some(ref right)) = pat.node {
215             if right.node == PatWild(PatWildSingle) {
216                 cx.span_lint(REDUNDANT_PATTERN, pat.span, &format!(
217                     "the `{} @ _` pattern can be written as just `{}`",
218                     ident.node.name, ident.node.name));
219             }
220         }
221     }
222 }