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