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