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