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