3 use rustc_front::hir::*;
5 use rustc_front::util::{is_comparison_binop, binop_to_string};
6 use syntax::codemap::{Span, Spanned};
7 use rustc_front::intravisit::FnKind;
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;
13 use utils::{get_item_name, match_path, snippet, span_lint, walk_ptrs_ty, is_integer_literal};
14 use utils::span_help_and_lint;
16 /// **What it does:** This lint checks for function arguments and let bindings denoted as `ref`. It is `Warn` by default.
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.
20 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The type of `x` is more obvious with the former.
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.
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 `&`.");
30 #[allow(missing_copy_implementations)]
31 pub struct TopLevelRefPass;
33 impl LintPass for TopLevelRefPass {
34 fn get_lints(&self) -> LintArray {
35 lint_array!(TOPLEVEL_REF_ARG)
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
45 for ref arg in &decl.inputs {
46 if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
50 "`ref` directly on a function argument is ignored. Consider using a reference type instead."
55 fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
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
63 let tyopt = if let Some(ref ty) = l.ty {
64 format!(": {:?} ", ty)
68 span_help_and_lint(cx,
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, "_"))
80 /// **What it does:** This lint checks for comparisons to NAN. It is `Deny` by default.
82 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
84 /// **Known problems:** None
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)");
93 impl LintPass for CmpNan {
94 fn get_lints(&self) -> LintArray {
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);
106 if let ExprPath(_, ref path) = right.node {
107 check_nan(cx, path, expr.span);
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");
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.
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).
125 /// **Known problems:** None
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)");
133 #[derive(Copy,Clone)]
136 impl LintPass for FloatCmp {
137 fn get_lints(&self) -> LintArray {
138 lint_array!(FLOAT_CMP)
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 {
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") {
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, "..")));
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
173 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
174 if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
181 /// **What it does:** This lint checks for conversions to owned values just for the sake of a comparison. It is `Warn` by default.
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.
185 /// **Known problems:** None
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()`");
191 #[derive(Copy,Clone)]
194 impl LintPass for CmpOwned {
195 fn get_lints(&self) -> LintArray {
196 lint_array!(CMP_OWNED)
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)
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, "..")
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, "..")
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, "..")));
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));
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 }
254 /// **What it does:** This lint checks for getting the remainder of a division by one. It is `Warn` by default.
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.
258 /// **Known problems:** None
260 /// **Example:** `x % 1`
261 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
263 #[derive(Copy,Clone)]
264 pub struct ModuloOne;
266 impl LintPass for ModuloOne {
267 fn get_lints(&self) -> LintArray {
268 lint_array!(MODULO_ONE)
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");
284 /// **What it does:** This lint checks for patterns in the form `name @ _`.
286 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
288 /// **Known problems:** None
294 /// y @ _ => (), // easier written as `y`,
297 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
299 #[derive(Copy,Clone)]
300 pub struct PatternPass;
302 impl LintPass for PatternPass {
303 fn get_lints(&self) -> LintArray {
304 lint_array!(REDUNDANT_PATTERN)
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));