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