]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc.rs
Use `span_suggestion` in `FLOAT_CMP`
[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 syntax::ptr::P;
12 use utils::{
13     get_item_name, get_parent_expr, implements_trait, in_macro, is_integer_literal, match_path,
14     snippet, span_lint, span_lint_and_then, walk_ptrs_ty
15 };
16
17 /// **What it does:** This lint 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 value, but turns the argument into a reference (which means that the value is destroyed when exiting the function). This adds not much value: either take a reference type, or take an owned value and create references in the body.
20 ///
21 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The type of `x` is more obvious with the former.
22 ///
23 /// **Known problems:** If the argument is dereferenced within the function, removing the `ref` will lead to errors. This can be fixed by removing the dereferences, e.g. changing `*x` to `x` within the function.
24 ///
25 /// **Example:** `fn foo(ref x: u8) -> bool { .. }`
26 declare_lint! {
27     pub TOPLEVEL_REF_ARG, Warn,
28     "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
29      or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
30      references with `&`."
31 }
32
33 #[allow(missing_copy_implementations)]
34 pub struct TopLevelRefPass;
35
36 impl LintPass for TopLevelRefPass {
37     fn get_lints(&self) -> LintArray {
38         lint_array!(TOPLEVEL_REF_ARG)
39     }
40 }
41
42 impl LateLintPass for TopLevelRefPass {
43     fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
44         if let FnKind::Closure(_) = k {
45             // Does not apply to closures
46             return;
47         }
48         for ref arg in &decl.inputs {
49             if let PatKind::Binding(BindByRef(_), _, _) = arg.pat.node {
50                 span_lint(cx,
51                           TOPLEVEL_REF_ARG,
52                           arg.pat.span,
53                           "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
54             }
55         }
56     }
57     fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
58         if_let_chain! {[
59             let StmtDecl(ref d, _) = s.node,
60             let DeclLocal(ref l) = d.node,
61             let PatKind::Binding(BindByRef(_), i, None) = l.pat.node,
62             let Some(ref init) = l.init
63         ], {
64             let tyopt = if let Some(ref ty) = l.ty {
65                 format!(": {}", snippet(cx, ty.span, "_"))
66             } else {
67                 "".to_owned()
68             };
69             span_lint_and_then(cx,
70                 TOPLEVEL_REF_ARG,
71                 l.pat.span,
72                 "`ref` on an entire `let` pattern is discouraged, take a reference with & instead",
73                 |db| {
74                     db.span_suggestion(s.span,
75                                        "try",
76                                        format!("let {}{} = &{};",
77                                                snippet(cx, i.span, "_"),
78                                                tyopt,
79                                                snippet(cx, init.span, "_")));
80                 }
81             );
82         }}
83     }
84 }
85
86 /// **What it does:** This lint checks for comparisons to NAN.
87 ///
88 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
89 ///
90 /// **Known problems:** None
91 ///
92 /// **Example:** `x == NAN`
93 declare_lint!(pub CMP_NAN, Deny,
94               "comparisons to NAN (which will always return false, which is probably not intended)");
95
96 #[derive(Copy,Clone)]
97 pub struct CmpNan;
98
99 impl LintPass for CmpNan {
100     fn get_lints(&self) -> LintArray {
101         lint_array!(CMP_NAN)
102     }
103 }
104
105 impl LateLintPass for CmpNan {
106     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
107         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
108             if cmp.node.is_comparison() {
109                 if let ExprPath(_, ref path) = left.node {
110                     check_nan(cx, path, expr.span);
111                 }
112                 if let ExprPath(_, ref path) = right.node {
113                     check_nan(cx, path, expr.span);
114                 }
115             }
116         }
117     }
118 }
119
120 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
121     path.segments.last().map(|seg| {
122         if seg.name.as_str() == "NAN" {
123             span_lint(cx,
124                       CMP_NAN,
125                       span,
126                       "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
127         }
128     });
129 }
130
131 /// **What it does:** This lint checks for (in-)equality comparisons on floating-point values (apart from zero), except in functions called `*eq*` (which probably implement equality for a type involving floats).
132 ///
133 /// **Why is this bad?** Floating point calculations are usually imprecise, so asking if two values are *exactly* equal is asking for trouble. For a good guide on what to do, see [the floating point guide](http://www.floating-point-gui.de/errors/comparison).
134 ///
135 /// **Known problems:** None
136 ///
137 /// **Example:** `y == 1.23f64`
138 declare_lint!(pub FLOAT_CMP, Warn,
139               "using `==` or `!=` on float values (as floating-point operations \
140                usually involve rounding errors, it is always better to check for approximate \
141                equality within small bounds)");
142
143 #[derive(Copy,Clone)]
144 pub struct FloatCmp;
145
146 impl LintPass for FloatCmp {
147     fn get_lints(&self) -> LintArray {
148         lint_array!(FLOAT_CMP)
149     }
150 }
151
152 impl LateLintPass for FloatCmp {
153     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
154         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
155             let op = cmp.node;
156             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
157                 if is_allowed(cx, left) || is_allowed(cx, right) {
158                     return;
159                 }
160                 if let Some(name) = get_item_name(cx, expr) {
161                     let name = name.as_str();
162                     if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
163                        name.ends_with("_eq") {
164                         return;
165                     }
166                 }
167                 span_lint_and_then(cx,
168                                    FLOAT_CMP,
169                                    expr.span,
170                                    "strict comparison of f32 or f64",
171                                    |db| {
172                     db.span_suggestion(expr.span,
173                                        "consider comparing them within some error",
174                                        format!("({} - {}).abs() < error",
175                                                snippet(cx, left.span, ".."),
176                                                snippet(cx, right.span, "..")));
177                     db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
178                 });
179             }
180         }
181     }
182 }
183
184 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
185     let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
186     if let Ok(ConstVal::Float(val)) = res {
187         use std::cmp::Ordering;
188
189         let zero = ConstFloat::FInfer {
190             f32: 0.0,
191             f64: 0.0,
192         };
193
194         let infinity = ConstFloat::FInfer {
195             f32: ::std::f32::INFINITY,
196             f64: ::std::f64::INFINITY,
197         };
198
199         let neg_infinity = ConstFloat::FInfer {
200             f32: ::std::f32::NEG_INFINITY,
201             f64: ::std::f64::NEG_INFINITY,
202         };
203
204         val.try_cmp(zero) == Ok(Ordering::Equal)
205             || val.try_cmp(infinity) == Ok(Ordering::Equal)
206             || val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
207     } else {
208         false
209     }
210 }
211
212 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
213     matches!(walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty, ty::TyFloat(_))
214 }
215
216 /// **What it does:** This lint checks for conversions to owned values just for the sake of a comparison.
217 ///
218 /// **Why is this bad?** The comparison can operate on a reference, so creating an owned value effectively throws it away directly afterwards, which is needlessly consuming code and heap space.
219 ///
220 /// **Known problems:** None
221 ///
222 /// **Example:** `x.to_owned() == y`
223 declare_lint!(pub CMP_OWNED, Warn,
224               "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
225
226 #[derive(Copy,Clone)]
227 pub struct CmpOwned;
228
229 impl LintPass for CmpOwned {
230     fn get_lints(&self) -> LintArray {
231         lint_array!(CMP_OWNED)
232     }
233 }
234
235 impl LateLintPass for CmpOwned {
236     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
237         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
238             if cmp.node.is_comparison() {
239                 check_to_owned(cx, left, right, true, cmp.span);
240                 check_to_owned(cx, right, left, false, cmp.span)
241             }
242         }
243     }
244 }
245
246 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
247     let (arg_ty, snip) = match expr.node {
248         ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) if args.len() == 1 => {
249             if name.as_str() == "to_string" || name.as_str() == "to_owned" && is_str_arg(cx, args) {
250                 (cx.tcx.expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
251             } else {
252                 return;
253             }
254         }
255         ExprCall(ref path, ref v) if v.len() == 1 => {
256             if let ExprPath(None, ref path) = path.node {
257                 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
258                     (cx.tcx.expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
259                 } else {
260                     return;
261                 }
262             } else {
263                 return;
264             }
265         }
266         _ => return,
267     };
268
269     let other_ty = cx.tcx.expr_ty(other);
270     let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
271         Some(id) => id,
272         None => return,
273     };
274
275     if !implements_trait(cx, arg_ty, partial_eq_trait_id, vec![other_ty]) {
276         return;
277     }
278
279     if left {
280         span_lint(cx,
281                   CMP_OWNED,
282                   expr.span,
283                   &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
284                             compare without allocation",
285                            snip,
286                            snippet(cx, op, "=="),
287                            snippet(cx, other.span, "..")));
288     } else {
289         span_lint(cx,
290                   CMP_OWNED,
291                   expr.span,
292                   &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
293                             compare without allocation",
294                            snippet(cx, other.span, ".."),
295                            snippet(cx, op, "=="),
296                            snip));
297     }
298
299 }
300
301 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
302     args.len() == 1 &&
303         matches!(walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty, ty::TyStr)
304 }
305
306 /// **What it does:** This lint checks for getting the remainder of a division by one.
307 ///
308 /// **Why is this bad?** The result can only ever be zero. No one will write such code deliberately, unless trying to win an Underhanded Rust Contest. Even for that contest, it's probably a bad idea. Use something more underhanded.
309 ///
310 /// **Known problems:** None
311 ///
312 /// **Example:** `x % 1`
313 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
314
315 #[derive(Copy,Clone)]
316 pub struct ModuloOne;
317
318 impl LintPass for ModuloOne {
319     fn get_lints(&self) -> LintArray {
320         lint_array!(MODULO_ONE)
321     }
322 }
323
324 impl LateLintPass for ModuloOne {
325     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
326         if let ExprBinary(ref cmp, _, ref right) = expr.node {
327             if let Spanned { node: BinOp_::BiRem, .. } = *cmp {
328                 if is_integer_literal(right, 1) {
329                     span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
330                 }
331             }
332         }
333     }
334 }
335
336 /// **What it does:** This lint checks for patterns in the form `name @ _`.
337 ///
338 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
339 ///
340 /// **Known problems:** None
341 ///
342 /// **Example**:
343 /// ```
344 /// match v {
345 ///     Some(x) => (),
346 ///     y @ _   => (), // easier written as `y`,
347 /// }
348 /// ```
349 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
350
351 #[derive(Copy,Clone)]
352 pub struct PatternPass;
353
354 impl LintPass for PatternPass {
355     fn get_lints(&self) -> LintArray {
356         lint_array!(REDUNDANT_PATTERN)
357     }
358 }
359
360 impl LateLintPass for PatternPass {
361     fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
362         if let PatKind::Binding(_, ref ident, Some(ref right)) = pat.node {
363             if right.node == PatKind::Wild {
364                 span_lint(cx,
365                           REDUNDANT_PATTERN,
366                           pat.span,
367                           &format!("the `{} @ _` pattern can be written as just `{}`",
368                                    ident.node,
369                                    ident.node));
370             }
371         }
372     }
373 }
374
375
376 /// **What it does:** This lint checks for the use of bindings with a single leading underscore
377 ///
378 /// **Why is this bad?** A single leading underscore is usually used to indicate that a binding
379 /// will not be used. Using such a binding breaks this expectation.
380 ///
381 /// **Known problems:** The lint does not work properly with desugaring and macro, it has been
382 /// allowed in the mean time.
383 ///
384 /// **Example**:
385 /// ```
386 /// let _x = 0;
387 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
388 ///                 // We should rename `_x` to `x`
389 /// ```
390 declare_lint!(pub USED_UNDERSCORE_BINDING, Allow,
391               "using a binding which is prefixed with an underscore");
392
393 #[derive(Copy, Clone)]
394 pub struct UsedUnderscoreBinding;
395
396 impl LintPass for UsedUnderscoreBinding {
397     fn get_lints(&self) -> LintArray {
398         lint_array!(USED_UNDERSCORE_BINDING)
399     }
400 }
401
402 impl LateLintPass for UsedUnderscoreBinding {
403     #[cfg_attr(rustfmt, rustfmt_skip)]
404     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
405         if in_attributes_expansion(cx, expr) {
406             // Don't lint things expanded by #[derive(...)], etc
407             return;
408         }
409         let binding = match expr.node {
410             ExprPath(_, ref path) => {
411                 let binding = path.segments
412                                 .last()
413                                 .expect("path should always have at least one segment")
414                                 .name
415                                 .as_str();
416                 if binding.starts_with('_') &&
417                    !binding.starts_with("__") &&
418                    binding != "_result" && // FIXME: #944
419                    is_used(cx, expr) &&
420                    // don't lint if the declaration is in a macro
421                    non_macro_local(cx, &cx.tcx.expect_def(expr.id)) {
422                     Some(binding)
423                 } else {
424                     None
425                 }
426             }
427             ExprField(_, spanned) => {
428                 let name = spanned.node.as_str();
429                 if name.starts_with('_') && !name.starts_with("__") {
430                     Some(name)
431                 } else {
432                     None
433                 }
434             }
435             _ => None,
436         };
437         if let Some(binding) = binding {
438             span_lint(cx,
439                       USED_UNDERSCORE_BINDING,
440                       expr.span,
441                       &format!("used binding `{}` which is prefixed with an underscore. A leading \
442                                 underscore signals that a binding will not be used.", binding));
443         }
444     }
445 }
446
447 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
448 /// of what it means for an expression to be "used".
449 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
450     if let Some(ref parent) = get_parent_expr(cx, expr) {
451         match parent.node {
452             ExprAssign(_, ref rhs) |
453             ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
454             _ => is_used(cx, parent),
455         }
456     } else {
457         true
458     }
459 }
460
461 /// Test whether an expression is in a macro expansion (e.g. something generated by
462 /// `#[derive(...)`] or the like).
463 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
464     cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
465         info_opt.map_or(false, |info| {
466             matches!(info.callee.format, ExpnFormat::MacroAttribute(_))
467         })
468     })
469 }
470
471 /// Test whether `def` is a variable defined outside a macro.
472 fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
473     match *def {
474         def::Def::Local(_, id) | def::Def::Upvar(_, id, _, _) => {
475             if let Some(span) = cx.tcx.map.opt_span(id) {
476                 !in_macro(cx, span)
477             } else {
478                 true
479             }
480         }
481         _ => false,
482     }
483 }