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