]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
use rustc's eval_const, bail on (negative) infinity
[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};
7 use rustc_front::visit::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, span_lint, walk_ptrs_ty, is_integer_literal};
14 use utils::span_help_and_lint;
15
16 declare_lint!(pub TOPLEVEL_REF_ARG, Warn,
17               "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
18                or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
19                references with `&`.");
20
21 #[allow(missing_copy_implementations)]
22 pub struct TopLevelRefPass;
23
24 impl LintPass for TopLevelRefPass {
25     fn get_lints(&self) -> LintArray {
26         lint_array!(TOPLEVEL_REF_ARG)
27     }
28 }
29
30 impl LateLintPass for TopLevelRefPass {
31     fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
32         if let FnKind::Closure = k {
33             // Does not apply to closures
34             return
35         }
36         for ref arg in &decl.inputs {
37             if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
38                 span_lint(cx,
39                     TOPLEVEL_REF_ARG,
40                     arg.pat.span,
41                     "`ref` directly on a function argument is ignored. Consider using a reference type instead."
42                 );
43             }
44         }
45     }
46     fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
47         if_let_chain! {
48             [
49             let StmtDecl(ref d, _) = s.node,
50             let DeclLocal(ref l) = d.node,
51             let PatIdent(BindByRef(_), i, None) = l.pat.node,
52             let Some(ref init) = l.init
53             ], {
54                 let tyopt = if let Some(ref ty) = l.ty {
55                     format!(": {:?} ", ty)
56                 } else {
57                     "".to_owned()
58                 };
59                 span_help_and_lint(cx,
60                     TOPLEVEL_REF_ARG,
61                     l.pat.span,
62                     "`ref` on an entire `let` pattern is discouraged, take a reference with & instead",
63                     &format!("try `let {} {}= &{};`", snippet(cx, i.span, "_"),
64                              tyopt, snippet(cx, init.span, "_"))
65                 );
66             }
67         };
68     }
69 }
70
71 declare_lint!(pub CMP_NAN, Deny,
72               "comparisons to NAN (which will always return false, which is probably not intended)");
73
74 #[derive(Copy,Clone)]
75 pub struct CmpNan;
76
77 impl LintPass for CmpNan {
78     fn get_lints(&self) -> LintArray {
79         lint_array!(CMP_NAN)
80     }
81 }
82
83 impl LateLintPass for CmpNan {
84     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
85         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
86             if is_comparison_binop(cmp.node) {
87                 if let &ExprPath(_, ref path) = &left.node {
88                     check_nan(cx, path, expr.span);
89                 }
90                 if let &ExprPath(_, ref path) = &right.node {
91                     check_nan(cx, path, expr.span);
92                 }
93             }
94         }
95     }
96 }
97
98 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
99     path.segments.last().map(|seg| if seg.identifier.name.as_str() == "NAN" {
100         span_lint(cx, CMP_NAN, span,
101             "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
102     });
103 }
104
105 declare_lint!(pub FLOAT_CMP, Warn,
106               "using `==` or `!=` on float values (as floating-point operations \
107                usually involve rounding errors, it is always better to check for approximate \
108                equality within small bounds)");
109
110 #[derive(Copy,Clone)]
111 pub struct FloatCmp;
112
113 impl LintPass for FloatCmp {
114     fn get_lints(&self) -> LintArray {
115         lint_array!(FLOAT_CMP)
116     }
117 }
118
119 impl LateLintPass for FloatCmp {
120     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
121         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
122             let op = cmp.node;
123             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
124                 if is_allowed(cx, left) || is_allowed(cx, right) { return; }
125                 if let Some(name) = get_item_name(cx, expr) {
126                     let name = name.as_str();
127                     if name == "eq" || name == "ne" || name == "is_nan" ||
128                             name.starts_with("eq_") ||
129                             name.ends_with("_eq") {
130                         return;
131                     }
132                 }
133                 span_lint(cx, FLOAT_CMP, expr.span, &format!(
134                     "{}-comparison of f32 or f64 detected. Consider changing this to \
135                      `abs({} - {}) < epsilon` for some suitable value of epsilon",
136                     binop_to_string(op), snippet(cx, left.span, ".."),
137                     snippet(cx, right.span, "..")));
138             }
139         }
140     }
141 }
142
143 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
144     let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
145     if let Ok(Float(val)) = res {
146         val == 0.0 || val == ::std::f64::INFINITY || val == ::std::f64::NEG_INFINITY
147     } else { false }
148 }
149
150 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
151     if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
152         true
153     } else {
154         false
155     }
156 }
157
158 declare_lint!(pub CMP_OWNED, Warn,
159               "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
160
161 #[derive(Copy,Clone)]
162 pub struct CmpOwned;
163
164 impl LintPass for CmpOwned {
165     fn get_lints(&self) -> LintArray {
166         lint_array!(CMP_OWNED)
167     }
168 }
169
170 impl LateLintPass for CmpOwned {
171     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
172         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
173             if is_comparison_binop(cmp.node) {
174                 check_to_owned(cx, left, right.span, true, cmp.span);
175                 check_to_owned(cx, right, left.span, false, cmp.span)
176             }
177         }
178     }
179 }
180
181 fn check_to_owned(cx: &LateContext, expr: &Expr, other_span: Span, left: bool, op: Span) {
182     let snip = match expr.node {
183         ExprMethodCall(Spanned{node: ref name, ..}, _, ref args) if args.len() == 1 => {
184             if name.as_str() == "to_string" ||
185                 name.as_str() == "to_owned" && is_str_arg(cx, args) {
186                     snippet(cx, args[0].span, "..")
187                 } else {
188                     return
189                 }
190         },
191         ExprCall(ref path, ref v) if v.len() == 1 => {
192             if let &ExprPath(None, ref path) = &path.node {
193                 if match_path(path, &["String", "from_str"]) ||
194                     match_path(path, &["String", "from"]) {
195                             snippet(cx, v[0].span, "..")
196                     } else {
197                         return
198                     }
199             } else {
200                 return
201             }
202         },
203         _ => return
204     };
205     if left {
206         span_lint(cx, CMP_OWNED, expr.span, &format!(
207         "this creates an owned instance just for comparison. Consider using \
208         `{} {} {}` to compare without allocation", snip,
209         snippet(cx, op, "=="), snippet(cx, other_span, "..")));
210     } else {
211         span_lint(cx, CMP_OWNED, expr.span, &format!(
212         "this creates an owned instance just for comparison. Consider using \
213         `{} {} {}` to compare without allocation",
214         snippet(cx, other_span, ".."), snippet(cx, op, "=="),  snip));
215     }
216
217 }
218
219 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
220     args.len() == 1 && if let ty::TyStr =
221         walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty { true } else { false }
222 }
223
224 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
225
226 #[derive(Copy,Clone)]
227 pub struct ModuloOne;
228
229 impl LintPass for ModuloOne {
230     fn get_lints(&self) -> LintArray {
231         lint_array!(MODULO_ONE)
232     }
233 }
234
235 impl LateLintPass for ModuloOne {
236     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
237         if let ExprBinary(ref cmp, _, ref right) = expr.node {
238             if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
239                 if is_integer_literal(right, 1) {
240                     cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
241                 }
242             }
243         }
244     }
245 }
246
247 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
248
249 #[derive(Copy,Clone)]
250 pub struct PatternPass;
251
252 impl LintPass for PatternPass {
253     fn get_lints(&self) -> LintArray {
254         lint_array!(REDUNDANT_PATTERN)
255     }
256 }
257
258 impl LateLintPass for PatternPass {
259     fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
260         if let PatIdent(_, ref ident, Some(ref right)) = pat.node {
261             if right.node == PatWild {
262                 cx.span_lint(REDUNDANT_PATTERN, pat.span, &format!(
263                     "the `{} @ _` pattern can be written as just `{}`",
264                     ident.node.name, ident.node.name));
265             }
266         }
267     }
268 }