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