]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
25747157c0f1677c816092fa899545cb0a42b66f
[rust.git] / 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::{get_item_name, match_path, snippet, get_parent_expr, span_lint};
12 use utils::{span_lint_and_then, walk_ptrs_ty, is_integer_literal, implements_trait};
13
14 /// **What it does:** This lint checks for function arguments and let bindings denoted as `ref`.
15 ///
16 /// **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.
17 ///
18 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The type of `x` is more obvious with the former.
19 ///
20 /// **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.
21 ///
22 /// **Example:** `fn foo(ref x: u8) -> bool { .. }`
23 declare_lint! {
24     pub TOPLEVEL_REF_ARG, Warn,
25     "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
26      or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
27      references with `&`."
28 }
29
30 #[allow(missing_copy_implementations)]
31 pub struct TopLevelRefPass;
32
33 impl LintPass for TopLevelRefPass {
34     fn get_lints(&self) -> LintArray {
35         lint_array!(TOPLEVEL_REF_ARG)
36     }
37 }
38
39 impl LateLintPass for TopLevelRefPass {
40     fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
41         if let FnKind::Closure(_) = k {
42             // Does not apply to closures
43             return;
44         }
45         for ref arg in &decl.inputs {
46             if let PatKind::Ident(BindByRef(_), _, _) = arg.pat.node {
47                 span_lint(cx,
48                           TOPLEVEL_REF_ARG,
49                           arg.pat.span,
50                           "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
51             }
52         }
53     }
54     fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
55         if_let_chain! {
56             [
57             let StmtDecl(ref d, _) = s.node,
58             let DeclLocal(ref l) = d.node,
59             let PatKind::Ident(BindByRef(_), i, None) = l.pat.node,
60             let Some(ref init) = l.init
61             ], {
62                 let tyopt = if let Some(ref ty) = l.ty {
63                     format!(": {}", snippet(cx, ty.span, "_"))
64                 } else {
65                     "".to_owned()
66                 };
67                 span_lint_and_then(cx,
68                     TOPLEVEL_REF_ARG,
69                     l.pat.span,
70                     "`ref` on an entire `let` pattern is discouraged, take a reference with & instead",
71                     |db| {
72                         db.span_suggestion(s.span,
73                                            "try",
74                                            format!("let {}{} = &{};",
75                                                    snippet(cx, i.span, "_"),
76                                                    tyopt,
77                                                    snippet(cx, init.span, "_")));
78                     }
79                 );
80             }
81         };
82     }
83 }
84
85 /// **What it does:** This lint checks for comparisons to NAN.
86 ///
87 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
88 ///
89 /// **Known problems:** None
90 ///
91 /// **Example:** `x == NAN`
92 declare_lint!(pub CMP_NAN, Deny,
93               "comparisons to NAN (which will always return false, which is probably not intended)");
94
95 #[derive(Copy,Clone)]
96 pub struct CmpNan;
97
98 impl LintPass for CmpNan {
99     fn get_lints(&self) -> LintArray {
100         lint_array!(CMP_NAN)
101     }
102 }
103
104 impl LateLintPass for CmpNan {
105     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
106         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
107             if cmp.node.is_comparison() {
108                 if let ExprPath(_, ref path) = left.node {
109                     check_nan(cx, path, expr.span);
110                 }
111                 if let ExprPath(_, ref path) = right.node {
112                     check_nan(cx, path, expr.span);
113                 }
114             }
115         }
116     }
117 }
118
119 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
120     path.segments.last().map(|seg| {
121         if seg.identifier.name.as_str() == "NAN" {
122             span_lint(cx,
123                       CMP_NAN,
124                       span,
125                       "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
126         }
127     });
128 }
129
130 /// **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).
131 ///
132 /// **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).
133 ///
134 /// **Known problems:** None
135 ///
136 /// **Example:** `y == 1.23f64`
137 declare_lint!(pub FLOAT_CMP, Warn,
138               "using `==` or `!=` on float values (as floating-point operations \
139                usually involve rounding errors, it is always better to check for approximate \
140                equality within small bounds)");
141
142 #[derive(Copy,Clone)]
143 pub struct FloatCmp;
144
145 impl LintPass for FloatCmp {
146     fn get_lints(&self) -> LintArray {
147         lint_array!(FLOAT_CMP)
148     }
149 }
150
151 impl LateLintPass for FloatCmp {
152     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
153         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
154             let op = cmp.node;
155             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
156                 if is_allowed(cx, left) || is_allowed(cx, right) {
157                     return;
158                 }
159                 if let Some(name) = get_item_name(cx, expr) {
160                     let name = name.as_str();
161                     if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
162                        name.ends_with("_eq") {
163                         return;
164                     }
165                 }
166                 span_lint(cx,
167                           FLOAT_CMP,
168                           expr.span,
169                           &format!("{}-comparison of f32 or f64 detected. Consider changing this to `({} - {}).abs() < \
170                                     epsilon` for some suitable value of epsilon. \
171                                     std::f32::EPSILON and std::f64::EPSILON are available.",
172                                    op.as_str(),
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(ConstVal::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 cmp.node.is_comparison() {
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, 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                     span_lint(cx, 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                 span_lint(cx,
350                           REDUNDANT_PATTERN,
351                           pat.span,
352                           &format!("the `{} @ _` pattern can be written as just `{}`",
353                                    ident.node.name,
354                                    ident.node.name));
355             }
356         }
357     }
358 }
359
360
361 /// **What it does:** This lint checks for the use of bindings with a single leading underscore
362 ///
363 /// **Why is this bad?** A single leading underscore is usually used to indicate that a binding
364 /// will not be used. Using such a binding breaks this expectation.
365 ///
366 /// **Known problems:** None
367 ///
368 /// **Example**:
369 /// ```
370 /// let _x = 0;
371 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
372 ///                 // We should rename `_x` to `x`
373 /// ```
374 declare_lint!(pub USED_UNDERSCORE_BINDING, Warn,
375               "using a binding which is prefixed with an underscore");
376
377 #[derive(Copy, Clone)]
378 pub struct UsedUnderscoreBinding;
379
380 impl LintPass for UsedUnderscoreBinding {
381     fn get_lints(&self) -> LintArray {
382         lint_array!(USED_UNDERSCORE_BINDING)
383     }
384 }
385
386 impl LateLintPass for UsedUnderscoreBinding {
387     #[cfg_attr(rustfmt, rustfmt_skip)]
388     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
389         if in_attributes_expansion(cx, expr) {
390     // Don't lint things expanded by #[derive(...)], etc
391             return;
392         }
393         let needs_lint = match expr.node {
394             ExprPath(_, ref path) => {
395                 let ident = path.segments
396                                 .last()
397                                 .expect("path should always have at least one segment")
398                                 .identifier;
399                 ident.name.as_str().starts_with('_') &&
400                 !ident.name.as_str().starts_with("__") &&
401                 ident.name != ident.unhygienic_name &&
402                 is_used(cx, expr) // not in bang macro
403             }
404             ExprField(_, spanned) => {
405                 let name = spanned.node.as_str();
406                 name.starts_with('_') && !name.starts_with("__")
407             }
408             _ => false,
409         };
410         if needs_lint {
411             span_lint(cx,
412                       USED_UNDERSCORE_BINDING,
413                       expr.span,
414                       "used binding which is prefixed with an underscore. A leading underscore signals that a \
415                        binding will not be used.");
416         }
417     }
418 }
419
420 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
421 /// of what it means for an expression to be "used".
422 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
423     if let Some(ref parent) = get_parent_expr(cx, expr) {
424         match parent.node {
425             ExprAssign(_, ref rhs) |
426             ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
427             _ => is_used(cx, parent),
428         }
429     } else {
430         true
431     }
432 }
433
434 /// Test whether an expression is in a macro expansion (e.g. something generated by #[derive(...)]
435 /// or the like)
436 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
437     cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
438         info_opt.map_or(false, |info| {
439             match info.callee.format {
440                 ExpnFormat::MacroAttribute(_) => true,
441                 _ => false,
442             }
443         })
444     })
445 }