]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc.rs
Merge pull request #962 from Manishearth/fix-doc
[rust.git] / clippy_lints / src / misc.rs
1 use reexport::*;
2 use rustc::hir::*;
3 use rustc::hir::intravisit::FnKind;
4 use rustc::lint::*;
5 use rustc::middle::const_val::ConstVal;
6 use rustc::ty;
7 use rustc_const_eval::EvalHint::ExprTypeChecked;
8 use rustc_const_eval::eval_const_expr_partial;
9 use syntax::codemap::{Span, Spanned, ExpnFormat};
10 use syntax::ptr::P;
11 use utils::{
12     get_item_name, get_parent_expr, implements_trait, is_integer_literal, match_path, snippet,
13     span_lint, span_lint_and_then, walk_ptrs_ty
14 };
15
16 /// **What it does:** This lint checks for function arguments and let bindings denoted as `ref`.
17 ///
18 /// **Why is this bad?** The `ref` declaration makes the function take an owned value, but turns the argument into a reference (which means that the value is destroyed when exiting the function). This adds not much value: either take a reference type, or take an owned value and create references in the body.
19 ///
20 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The type of `x` is more obvious with the former.
21 ///
22 /// **Known problems:** If the argument is dereferenced within the function, removing the `ref` will lead to errors. This can be fixed by removing the dereferences, e.g. changing `*x` to `x` within the function.
23 ///
24 /// **Example:** `fn foo(ref x: u8) -> bool { .. }`
25 declare_lint! {
26     pub TOPLEVEL_REF_ARG, Warn,
27     "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
28      or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
29      references with `&`."
30 }
31
32 #[allow(missing_copy_implementations)]
33 pub struct TopLevelRefPass;
34
35 impl LintPass for TopLevelRefPass {
36     fn get_lints(&self) -> LintArray {
37         lint_array!(TOPLEVEL_REF_ARG)
38     }
39 }
40
41 impl LateLintPass for TopLevelRefPass {
42     fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
43         if let FnKind::Closure(_) = k {
44             // Does not apply to closures
45             return;
46         }
47         for ref arg in &decl.inputs {
48             if let PatKind::Binding(BindByRef(_), _, _) = arg.pat.node {
49                 span_lint(cx,
50                           TOPLEVEL_REF_ARG,
51                           arg.pat.span,
52                           "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
53             }
54         }
55     }
56     fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
57         if_let_chain! {
58             [
59             let StmtDecl(ref d, _) = s.node,
60             let DeclLocal(ref l) = d.node,
61             let PatKind::Binding(BindByRef(_), i, None) = l.pat.node,
62             let Some(ref init) = l.init
63             ], {
64                 let tyopt = if let Some(ref ty) = l.ty {
65                     format!(": {}", snippet(cx, ty.span, "_"))
66                 } else {
67                     "".to_owned()
68                 };
69                 span_lint_and_then(cx,
70                     TOPLEVEL_REF_ARG,
71                     l.pat.span,
72                     "`ref` on an entire `let` pattern is discouraged, take a reference with & instead",
73                     |db| {
74                         db.span_suggestion(s.span,
75                                            "try",
76                                            format!("let {}{} = &{};",
77                                                    snippet(cx, i.span, "_"),
78                                                    tyopt,
79                                                    snippet(cx, init.span, "_")));
80                     }
81                 );
82             }
83         };
84     }
85 }
86
87 /// **What it does:** This lint checks for comparisons to NAN.
88 ///
89 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
90 ///
91 /// **Known problems:** None
92 ///
93 /// **Example:** `x == NAN`
94 declare_lint!(pub CMP_NAN, Deny,
95               "comparisons to NAN (which will always return false, which is probably not intended)");
96
97 #[derive(Copy,Clone)]
98 pub struct CmpNan;
99
100 impl LintPass for CmpNan {
101     fn get_lints(&self) -> LintArray {
102         lint_array!(CMP_NAN)
103     }
104 }
105
106 impl LateLintPass for CmpNan {
107     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
108         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
109             if cmp.node.is_comparison() {
110                 if let ExprPath(_, ref path) = left.node {
111                     check_nan(cx, path, expr.span);
112                 }
113                 if let ExprPath(_, ref path) = right.node {
114                     check_nan(cx, path, expr.span);
115                 }
116             }
117         }
118     }
119 }
120
121 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
122     path.segments.last().map(|seg| {
123         if seg.name.as_str() == "NAN" {
124             span_lint(cx,
125                       CMP_NAN,
126                       span,
127                       "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
128         }
129     });
130 }
131
132 /// **What it does:** This lint checks for (in-)equality comparisons on floating-point values (apart from zero), except in functions called `*eq*` (which probably implement equality for a type involving floats).
133 ///
134 /// **Why is this bad?** Floating point calculations are usually imprecise, so asking if two values are *exactly* equal is asking for trouble. For a good guide on what to do, see [the floating point guide](http://www.floating-point-gui.de/errors/comparison).
135 ///
136 /// **Known problems:** None
137 ///
138 /// **Example:** `y == 1.23f64`
139 declare_lint!(pub FLOAT_CMP, Warn,
140               "using `==` or `!=` on float values (as floating-point operations \
141                usually involve rounding errors, it is always better to check for approximate \
142                equality within small bounds)");
143
144 #[derive(Copy,Clone)]
145 pub struct FloatCmp;
146
147 impl LintPass for FloatCmp {
148     fn get_lints(&self) -> LintArray {
149         lint_array!(FLOAT_CMP)
150     }
151 }
152
153 impl LateLintPass for FloatCmp {
154     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
155         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
156             let op = cmp.node;
157             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
158                 if is_allowed(cx, left) || is_allowed(cx, right) {
159                     return;
160                 }
161                 if let Some(name) = get_item_name(cx, expr) {
162                     let name = name.as_str();
163                     if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
164                        name.ends_with("_eq") {
165                         return;
166                     }
167                 }
168                 span_lint(cx,
169                           FLOAT_CMP,
170                           expr.span,
171                           &format!("{}-comparison of f32 or f64 detected. Consider changing this to `({} - {}).abs() < \
172                                     epsilon` for some suitable value of epsilon. \
173                                     std::f32::EPSILON and std::f64::EPSILON are available.",
174                                    op.as_str(),
175                                    snippet(cx, left.span, ".."),
176                                    snippet(cx, right.span, "..")));
177             }
178         }
179     }
180 }
181
182 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
183     let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
184     if let Ok(ConstVal::Float(val)) = res {
185         val == 0.0 || val == ::std::f64::INFINITY || val == ::std::f64::NEG_INFINITY
186     } else {
187         false
188     }
189 }
190
191 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
192     if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
193         true
194     } else {
195         false
196     }
197 }
198
199 /// **What it does:** This lint checks for conversions to owned values just for the sake of a comparison.
200 ///
201 /// **Why is this bad?** The comparison can operate on a reference, so creating an owned value effectively throws it away directly afterwards, which is needlessly consuming code and heap space.
202 ///
203 /// **Known problems:** None
204 ///
205 /// **Example:** `x.to_owned() == y`
206 declare_lint!(pub CMP_OWNED, Warn,
207               "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
208
209 #[derive(Copy,Clone)]
210 pub struct CmpOwned;
211
212 impl LintPass for CmpOwned {
213     fn get_lints(&self) -> LintArray {
214         lint_array!(CMP_OWNED)
215     }
216 }
217
218 impl LateLintPass for CmpOwned {
219     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
220         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
221             if cmp.node.is_comparison() {
222                 check_to_owned(cx, left, right, true, cmp.span);
223                 check_to_owned(cx, right, left, false, cmp.span)
224             }
225         }
226     }
227 }
228
229 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
230     let (arg_ty, snip) = match expr.node {
231         ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) if args.len() == 1 => {
232             if name.as_str() == "to_string" || name.as_str() == "to_owned" && is_str_arg(cx, args) {
233                 (cx.tcx.expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
234             } else {
235                 return;
236             }
237         }
238         ExprCall(ref path, ref v) if v.len() == 1 => {
239             if let ExprPath(None, ref path) = path.node {
240                 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
241                     (cx.tcx.expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
242                 } else {
243                     return;
244                 }
245             } else {
246                 return;
247             }
248         }
249         _ => return,
250     };
251
252     let other_ty = cx.tcx.expr_ty(other);
253     let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
254         Some(id) => id,
255         None => return,
256     };
257
258     if !implements_trait(cx, arg_ty, partial_eq_trait_id, vec![other_ty]) {
259         return;
260     }
261
262     if left {
263         span_lint(cx,
264                   CMP_OWNED,
265                   expr.span,
266                   &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
267                             compare without allocation",
268                            snip,
269                            snippet(cx, op, "=="),
270                            snippet(cx, other.span, "..")));
271     } else {
272         span_lint(cx,
273                   CMP_OWNED,
274                   expr.span,
275                   &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
276                             compare without allocation",
277                            snippet(cx, other.span, ".."),
278                            snippet(cx, op, "=="),
279                            snip));
280     }
281
282 }
283
284 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
285     args.len() == 1 &&
286     if let ty::TyStr = walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty {
287         true
288     } else {
289         false
290     }
291 }
292
293 /// **What it does:** This lint checks for getting the remainder of a division by one.
294 ///
295 /// **Why is this bad?** The result can only ever be zero. No one will write such code deliberately, unless trying to win an Underhanded Rust Contest. Even for that contest, it's probably a bad idea. Use something more underhanded.
296 ///
297 /// **Known problems:** None
298 ///
299 /// **Example:** `x % 1`
300 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
301
302 #[derive(Copy,Clone)]
303 pub struct ModuloOne;
304
305 impl LintPass for ModuloOne {
306     fn get_lints(&self) -> LintArray {
307         lint_array!(MODULO_ONE)
308     }
309 }
310
311 impl LateLintPass for ModuloOne {
312     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
313         if let ExprBinary(ref cmp, _, ref right) = expr.node {
314             if let Spanned { node: BinOp_::BiRem, .. } = *cmp {
315                 if is_integer_literal(right, 1) {
316                     span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
317                 }
318             }
319         }
320     }
321 }
322
323 /// **What it does:** This lint checks for patterns in the form `name @ _`.
324 ///
325 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
326 ///
327 /// **Known problems:** None
328 ///
329 /// **Example**:
330 /// ```
331 /// match v {
332 ///     Some(x) => (),
333 ///     y @ _   => (), // easier written as `y`,
334 /// }
335 /// ```
336 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
337
338 #[derive(Copy,Clone)]
339 pub struct PatternPass;
340
341 impl LintPass for PatternPass {
342     fn get_lints(&self) -> LintArray {
343         lint_array!(REDUNDANT_PATTERN)
344     }
345 }
346
347 impl LateLintPass for PatternPass {
348     fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
349         if let PatKind::Binding(_, ref ident, Some(ref right)) = pat.node {
350             if right.node == PatKind::Wild {
351                 span_lint(cx,
352                           REDUNDANT_PATTERN,
353                           pat.span,
354                           &format!("the `{} @ _` pattern can be written as just `{}`",
355                                    ident.node,
356                                    ident.node));
357             }
358         }
359     }
360 }
361
362
363 /// **What it does:** This lint checks for the use of bindings with a single leading underscore
364 ///
365 /// **Why is this bad?** A single leading underscore is usually used to indicate that a binding
366 /// will not be used. Using such a binding breaks this expectation.
367 ///
368 /// **Known problems:** The lint does not work properly with desugaring and macro, it has been
369 /// allowed in the mean time.
370 ///
371 /// **Example**:
372 /// ```
373 /// let _x = 0;
374 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
375 ///                 // We should rename `_x` to `x`
376 /// ```
377 declare_lint!(pub USED_UNDERSCORE_BINDING, Allow,
378               "using a binding which is prefixed with an underscore");
379
380 #[derive(Copy, Clone)]
381 pub struct UsedUnderscoreBinding;
382
383 impl LintPass for UsedUnderscoreBinding {
384     fn get_lints(&self) -> LintArray {
385         lint_array!(USED_UNDERSCORE_BINDING)
386     }
387 }
388
389 impl LateLintPass for UsedUnderscoreBinding {
390     #[cfg_attr(rustfmt, rustfmt_skip)]
391     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
392         if in_attributes_expansion(cx, expr) {
393             // Don't lint things expanded by #[derive(...)], etc
394             return;
395         }
396         let binding = match expr.node {
397             ExprPath(_, ref path) => {
398                 let segment = path.segments
399                                 .last()
400                                 .expect("path should always have at least one segment")
401                                 .name;
402                 if segment.as_str().starts_with('_') &&
403                    !segment.as_str().starts_with("__") &&
404                    segment != segment.unhygienize() && // not in bang macro
405                    is_used(cx, expr) {
406                     Some(segment.as_str())
407                 } else {
408                     None
409                 }
410             }
411             ExprField(_, spanned) => {
412                 let name = spanned.node.as_str();
413                 if name.starts_with('_') && !name.starts_with("__") {
414                     Some(name)
415                 } else {
416                     None
417                 }
418             }
419             _ => None,
420         };
421         if let Some(binding) = binding {
422             if binding != "_result" { // FIXME: #944
423                 span_lint(cx,
424                           USED_UNDERSCORE_BINDING,
425                           expr.span,
426                           &format!("used binding `{}` which is prefixed with an underscore. A leading \
427                                     underscore signals that a binding will not be used.", binding));
428             }
429         }
430     }
431 }
432
433 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
434 /// of what it means for an expression to be "used".
435 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
436     if let Some(ref parent) = get_parent_expr(cx, expr) {
437         match parent.node {
438             ExprAssign(_, ref rhs) |
439             ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
440             _ => is_used(cx, parent),
441         }
442     } else {
443         true
444     }
445 }
446
447 /// Test whether an expression is in a macro expansion (e.g. something generated by
448 /// `#[derive(...)`] or the like).
449 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
450     cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
451         info_opt.map_or(false, |info| {
452             match info.callee.format {
453                 ExpnFormat::MacroAttribute(_) => true,
454                 _ => false,
455             }
456         })
457     })
458 }