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