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