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