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