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