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