]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc.rs
WIP compiles and doesn't crash (much) but tests are failing
[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::{
12     get_item_name, get_parent_expr, implements_trait, in_macro, is_integer_literal, match_path,
13     snippet, span_lint, span_lint_and_then, walk_ptrs_ty
14 };
15 use utils::sugg::Sugg;
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 #[derive(Copy, Clone)]
160 pub struct Pass;
161
162 impl LintPass for Pass {
163     fn get_lints(&self) -> LintArray {
164         lint_array!(TOPLEVEL_REF_ARG, CMP_NAN, FLOAT_CMP, CMP_OWNED, MODULO_ONE, REDUNDANT_PATTERN,
165                     USED_UNDERSCORE_BINDING)
166     }
167 }
168
169 impl LateLintPass for Pass {
170     fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Expr, _: Span, _: NodeId) {
171         if let FnKind::Closure(_) = k {
172             // Does not apply to closures
173             return;
174         }
175         for arg in &decl.inputs {
176             if let PatKind::Binding(BindByRef(_), _, _, _) = arg.pat.node {
177                 span_lint(cx,
178                           TOPLEVEL_REF_ARG,
179                           arg.pat.span,
180                           "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
181             }
182         }
183     }
184
185     fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
186         if_let_chain! {[
187             let StmtDecl(ref d, _) = s.node,
188             let DeclLocal(ref l) = d.node,
189             let PatKind::Binding(BindByRef(mt), _, i, None) = l.pat.node,
190             let Some(ref init) = l.init
191         ], {
192             let init = Sugg::hir(cx, init, "..");
193             let (mutopt,initref) = if mt == Mutability::MutMutable {
194                 ("mut ", init.mut_addr())
195             } else {
196                 ("", init.addr())
197             };
198             let tyopt = if let Some(ref ty) = l.ty {
199                 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
200             } else {
201                 "".to_owned()
202             };
203             span_lint_and_then(cx,
204                 TOPLEVEL_REF_ARG,
205                 l.pat.span,
206                 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
207                 |db| {
208                     db.span_suggestion(s.span,
209                                        "try",
210                                        format!("let {name}{tyopt} = {initref};",
211                                                name=snippet(cx, i.span, "_"),
212                                                tyopt=tyopt,
213                                                initref=initref));
214                 }
215             );
216         }}
217     }
218
219     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
220         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
221             let op = cmp.node;
222             if op.is_comparison() {
223                 if let ExprPath(QPath::Resolved(_, ref path)) = left.node {
224                     check_nan(cx, path, expr.span);
225                 }
226                 if let ExprPath(QPath::Resolved(_, ref path)) = right.node {
227                     check_nan(cx, path, expr.span);
228                 }
229                 check_to_owned(cx, left, right, true, cmp.span);
230                 check_to_owned(cx, right, left, false, cmp.span)
231             }
232             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
233                 if is_allowed(cx, left) || is_allowed(cx, right) {
234                     return;
235                 }
236                 if let Some(name) = get_item_name(cx, expr) {
237                     let name = &*name.as_str();
238                     if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
239                         name.ends_with("_eq") {
240                         return;
241                     }
242                 }
243                 span_lint_and_then(cx,
244                                    FLOAT_CMP,
245                                    expr.span,
246                                    "strict comparison of f32 or f64",
247                                    |db| {
248                                        let lhs = Sugg::hir(cx, left, "..");
249                                        let rhs = Sugg::hir(cx, right, "..");
250
251                                        db.span_suggestion(expr.span,
252                                                           "consider comparing them within some error",
253                                                           format!("({}).abs() < error", lhs - rhs));
254                                        db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
255                                    });
256             } else if op == BiRem && is_integer_literal(right, 1) {
257                 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
258             }
259         }
260         if in_attributes_expansion(cx, expr) {
261             // Don't lint things expanded by #[derive(...)], etc
262             return;
263         }
264         let binding = match expr.node {
265             ExprPath(ref qpath) => {
266                 if let QPath::Resolved(_, ref path) = *qpath {
267                     let binding = path.segments
268                         .last()
269                         .expect("path should always have at least one segment")
270                         .name
271                         .as_str();
272                     if binding.starts_with('_') &&
273                         !binding.starts_with("__") &&
274                         &*binding != "_result" && // FIXME: #944
275                         is_used(cx, expr) &&
276                         // don't lint if the declaration is in a macro
277                         non_macro_local(cx, &cx.tcx.tables().qpath_def(qpath, expr.id)) {
278                         Some(binding)
279                     } else {
280                         None
281                     }
282                 } else {
283                     None
284                 }
285             }
286             ExprField(_, spanned) => {
287                 let name = spanned.node.as_str();
288                 if name.starts_with('_') && !name.starts_with("__") {
289                     Some(name)
290                 } else {
291                     None
292                 }
293             }
294             _ => None,
295         };
296         if let Some(binding) = binding {
297             span_lint(cx,
298                       USED_UNDERSCORE_BINDING,
299                       expr.span,
300                       &format!("used binding `{}` which is prefixed with an underscore. A leading \
301                                 underscore signals that a binding will not be used.", binding));
302         }
303     }
304
305     fn check_pat(&mut self, cx: &LateContext, pat: &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 `{}`",
312                                    ident.node,
313                                    ident.node));
314             }
315         }
316     }
317 }
318
319 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
320     path.segments.last().map(|seg| {
321         if &*seg.name.as_str() == "NAN" {
322             span_lint(cx,
323                       CMP_NAN,
324                       span,
325                       "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
326         }
327     });
328 }
329
330 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
331     let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
332     if let Ok(ConstVal::Float(val)) = res {
333         use std::cmp::Ordering;
334
335         let zero = ConstFloat::FInfer {
336             f32: 0.0,
337             f64: 0.0,
338         };
339
340         let infinity = ConstFloat::FInfer {
341             f32: ::std::f32::INFINITY,
342             f64: ::std::f64::INFINITY,
343         };
344
345         let neg_infinity = ConstFloat::FInfer {
346             f32: ::std::f32::NEG_INFINITY,
347             f64: ::std::f64::NEG_INFINITY,
348         };
349
350         val.try_cmp(zero) == Ok(Ordering::Equal)
351             || val.try_cmp(infinity) == Ok(Ordering::Equal)
352             || val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
353     } else {
354         false
355     }
356 }
357
358 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
359     matches!(walk_ptrs_ty(cx.tcx.tables().expr_ty(expr)).sty, ty::TyFloat(_))
360 }
361
362 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
363     let (arg_ty, snip) = match expr.node {
364         ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) if args.len() == 1 => {
365             let name = &*name.as_str();
366             if name == "to_string" || name == "to_owned" && is_str_arg(cx, args) {
367                 (cx.tcx.tables().expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
368             } else {
369                 return;
370             }
371         }
372         ExprCall(ref path, ref v) if v.len() == 1 => {
373             if let ExprPath(ref path) = path.node {
374                 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
375                     (cx.tcx.tables().expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
376                 } else {
377                     return;
378                 }
379             } else {
380                 return;
381             }
382         }
383         _ => return,
384     };
385
386     let other_ty = cx.tcx.tables().expr_ty(other);
387     let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
388         Some(id) => id,
389         None => return,
390     };
391
392     if !implements_trait(cx, arg_ty, partial_eq_trait_id, vec![other_ty]) {
393         return;
394     }
395
396     if left {
397         span_lint(cx,
398                   CMP_OWNED,
399                   expr.span,
400                   &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
401                             compare without allocation",
402                            snip,
403                            snippet(cx, op, "=="),
404                            snippet(cx, other.span, "..")));
405     } else {
406         span_lint(cx,
407                   CMP_OWNED,
408                   expr.span,
409                   &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
410                             compare without allocation",
411                            snippet(cx, other.span, ".."),
412                            snippet(cx, op, "=="),
413                            snip));
414     }
415
416 }
417
418 fn is_str_arg(cx: &LateContext, args: &[Expr]) -> bool {
419     args.len() == 1 &&
420         matches!(walk_ptrs_ty(cx.tcx.tables().expr_ty(&args[0])).sty, ty::TyStr)
421 }
422
423 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
424 /// of what it means for an expression to be "used".
425 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
426     if let Some(parent) = get_parent_expr(cx, expr) {
427         match parent.node {
428             ExprAssign(_, ref rhs) |
429             ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
430             _ => is_used(cx, parent),
431         }
432     } else {
433         true
434     }
435 }
436
437 /// Test whether an expression is in a macro expansion (e.g. something generated by
438 /// `#[derive(...)`] or the like).
439 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
440     cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
441         info_opt.map_or(false, |info| {
442             matches!(info.callee.format, ExpnFormat::MacroAttribute(_))
443         })
444     })
445 }
446
447 /// Test whether `def` is a variable defined outside a macro.
448 fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
449     match *def {
450         def::Def::Local(id) | def::Def::Upvar(id, _, _) => {
451             let id = cx.tcx.map.as_local_node_id(id).expect("That DefId should be valid");
452
453             if let Some(span) = cx.tcx.map.opt_span(id) {
454                 !in_macro(cx, span)
455             } else {
456                 true
457             }
458         }
459         _ => false,
460     }
461 }