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