]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
Merge
[rust.git] / src / misc.rs
1 use syntax::ptr::P;
2 use syntax::ast;
3 use syntax::ast::*;
4 use syntax::ast_util::{is_comparison_binop, binop_to_string};
5 use syntax::visit::{FnKind};
6 use rustc::lint::{Context, LintPass, LintArray, Lint, Level};
7 use rustc::middle::ty;
8 use syntax::codemap::{Span, Spanned};
9
10 use utils::{match_path, snippet, span_lint, span_help_and_lint, walk_ptrs_ty};
11
12 /// Handles uncategorized lints
13 /// Currently handles linting of if-let-able matches
14 #[allow(missing_copy_implementations)]
15 pub struct MiscPass;
16
17
18 declare_lint!(pub SINGLE_MATCH, Warn,
19               "Warn on usage of matches with a single nontrivial arm");
20
21 impl LintPass for MiscPass {
22     fn get_lints(&self) -> LintArray {
23         lint_array!(SINGLE_MATCH)
24     }
25
26     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
27         if let ExprMatch(ref ex, ref arms, ast::MatchSource::Normal) = expr.node {
28             if arms.len() == 2 {
29                 if arms[0].guard.is_none() && arms[1].pats.len() == 1 {
30                     match arms[1].body.node {
31                         ExprTup(ref v) if v.is_empty() && arms[1].guard.is_none() => (),
32                         ExprBlock(ref b) if b.stmts.is_empty() && arms[1].guard.is_none() => (),
33                          _ => return
34                     }
35                     // In some cases, an exhaustive match is preferred to catch situations when
36                     // an enum is extended. So we only consider cases where a `_` wildcard is used
37                     if arms[1].pats[0].node == PatWild(PatWildSingle) &&
38                             arms[0].pats.len() == 1 {
39                         let body_code = snippet(cx, arms[0].body.span, "..");
40                         let suggestion = if let ExprBlock(_) = arms[0].body.node {
41                             body_code.into_owned()
42                         } else {
43                             format!("{{ {} }}", body_code)
44                         };
45                         span_help_and_lint(cx, SINGLE_MATCH, expr.span,
46                               "you seem to be trying to use match for \
47                               destructuring a single pattern. Did you mean to \
48                               use `if let`?",
49                               &*format!("try\nif let {} = {} {}",
50                                         snippet(cx, arms[0].pats[0].span, ".."),
51                                         snippet(cx, ex.span, ".."),
52                                         suggestion)
53                         );
54                     }
55                 }
56             }
57         }
58     }
59 }
60
61
62 declare_lint!(pub TOPLEVEL_REF_ARG, Warn, "Warn about pattern matches with top-level `ref` bindings");
63
64 #[allow(missing_copy_implementations)]
65 pub struct TopLevelRefPass;
66
67 impl LintPass for TopLevelRefPass {
68     fn get_lints(&self) -> LintArray {
69         lint_array!(TOPLEVEL_REF_ARG)
70     }
71
72     fn check_fn(&mut self, cx: &Context, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
73         for ref arg in decl.inputs.iter() {
74             if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
75                 span_lint(cx,
76                     TOPLEVEL_REF_ARG,
77                     arg.pat.span,
78                     "`ref` directly on a function argument is ignored. Consider using a reference type instead."
79                 );
80             }
81         }
82     }
83 }
84
85 declare_lint!(pub CMP_NAN, Deny, "Deny comparisons to std::f32::NAN or std::f64::NAN");
86
87 #[derive(Copy,Clone)]
88 pub struct CmpNan;
89
90 impl LintPass for CmpNan {
91     fn get_lints(&self) -> LintArray {
92         lint_array!(CMP_NAN)
93     }
94
95     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
96         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
97             if is_comparison_binop(cmp.node) {
98                 if let &ExprPath(_, ref path) = &left.node {
99                     check_nan(cx, path, expr.span);
100                 }
101                 if let &ExprPath(_, ref path) = &right.node {
102                     check_nan(cx, path, expr.span);
103                 }
104             }
105         }
106     }
107 }
108
109 fn check_nan(cx: &Context, path: &Path, span: Span) {
110     path.segments.last().map(|seg| if seg.identifier.name == "NAN" {
111         span_lint(cx, CMP_NAN, span,
112                   "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
113     });
114 }
115
116 declare_lint!(pub FLOAT_CMP, Warn,
117               "Warn on ==/!= comparison of floaty values");
118
119 #[derive(Copy,Clone)]
120 pub struct FloatCmp;
121
122 impl LintPass for FloatCmp {
123     fn get_lints(&self) -> LintArray {
124         lint_array!(FLOAT_CMP)
125     }
126
127     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
128         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
129             let op = cmp.node;
130             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
131                 span_lint(cx, FLOAT_CMP, expr.span, &format!(
132                     "{}-comparison of f32 or f64 detected. Consider changing this to \
133                      `abs({} - {}) < epsilon` for some suitable value of epsilon",
134                     binop_to_string(op), snippet(cx, left.span, ".."),
135                     snippet(cx, right.span, "..")));
136             }
137         }
138     }
139 }
140
141 fn is_float(cx: &Context, expr: &Expr) -> bool {
142     if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
143         true
144     } else {
145         false
146     }
147 }
148
149 declare_lint!(pub PRECEDENCE, Warn,
150               "Warn on mixing bit ops with integer arithmetic without parentheses");
151
152 #[derive(Copy,Clone)]
153 pub struct Precedence;
154
155 impl LintPass for Precedence {
156     fn get_lints(&self) -> LintArray {
157         lint_array!(PRECEDENCE)
158     }
159
160     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
161         if let ExprBinary(Spanned { node: op, ..}, ref left, ref right) = expr.node {
162             if is_bit_op(op) && (is_arith_expr(left) || is_arith_expr(right)) {
163                 span_lint(cx, PRECEDENCE, expr.span,
164                     "operator precedence can trip the unwary. Consider adding parentheses \
165                      to the subexpression");
166             }
167         }
168     }
169 }
170
171 fn is_arith_expr(expr : &Expr) -> bool {
172     match expr.node {
173         ExprBinary(Spanned { node: op, ..}, _, _) => is_arith_op(op),
174         _ => false
175     }
176 }
177
178 fn is_bit_op(op : BinOp_) -> bool {
179     match op {
180         BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => true,
181         _ => false
182     }
183 }
184
185 fn is_arith_op(op : BinOp_) -> bool {
186     match op {
187         BiAdd | BiSub | BiMul | BiDiv | BiRem => true,
188         _ => false
189     }
190 }
191
192 declare_lint!(pub CMP_OWNED, Warn,
193               "Warn on creating an owned string just for comparison");
194
195 #[derive(Copy,Clone)]
196 pub struct CmpOwned;
197
198 impl LintPass for CmpOwned {
199     fn get_lints(&self) -> LintArray {
200         lint_array!(CMP_OWNED)
201     }
202
203     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
204         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
205             if is_comparison_binop(cmp.node) {
206                 check_to_owned(cx, left, right.span);
207                 check_to_owned(cx, right, left.span)
208             }
209         }
210     }
211 }
212
213 fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
214     match &expr.node {
215         &ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
216             let name = ident.name;
217             if name == "to_string" ||
218                 name == "to_owned" && is_str_arg(cx, args) {
219                     span_lint(cx, CMP_OWNED, expr.span, &format!(
220                         "this creates an owned instance just for comparison. \
221                          Consider using `{}.as_slice()` to compare without allocation",
222                         snippet(cx, other_span, "..")))
223                 }
224         },
225         &ExprCall(ref path, _) => {
226             if let &ExprPath(None, ref path) = &path.node {
227                 if match_path(path, &["String", "from_str"]) ||
228                     match_path(path, &["String", "from"]) {
229                         span_lint(cx, CMP_OWNED, expr.span, &format!(
230                             "this creates an owned instance just for comparison. \
231                              Consider using `{}.as_slice()` to compare without allocation",
232                             snippet(cx, other_span, "..")))
233                     }
234             }
235         },
236         _ => ()
237     }
238 }
239
240 fn is_str_arg(cx: &Context, args: &[P<Expr>]) -> bool {
241     args.len() == 1 && if let ty::TyStr =
242         walk_ptrs_ty(cx.tcx.expr_ty(&*args[0])).sty { true } else { false }
243 }
244
245 declare_lint!(pub MODULO_ONE, Warn, "Warn on expressions that include % 1, which is always 0");
246
247 #[derive(Copy,Clone)]
248 pub struct ModuloOne;
249
250 impl LintPass for ModuloOne {
251     fn get_lints(&self) -> LintArray {
252         lint_array!(MODULO_ONE)
253     }
254
255     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
256         if let ExprBinary(ref cmp, _, ref right) = expr.node {
257             if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
258                 if is_lit_one(right) {
259                     cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
260                 }
261             }
262         }
263     }
264 }
265
266 fn is_lit_one(expr: &Expr) -> bool {
267     if let ExprLit(ref spanned) = expr.node {
268         if let LitInt(1, _) = spanned.node {
269             return true;
270         }
271     }
272     false
273 }