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::visit::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 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 `&`.");
21 #[allow(missing_copy_implementations)]
22 pub struct TopLevelRefPass;
24 impl LintPass for TopLevelRefPass {
25 fn get_lints(&self) -> LintArray {
26 lint_array!(TOPLEVEL_REF_ARG)
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
36 for ref arg in &decl.inputs {
37 if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
41 "`ref` directly on a function argument is ignored. Consider using a reference type instead."
46 fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
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
54 let tyopt = if let Some(ref ty) = l.ty {
55 format!(": {:?} ", ty)
59 span_help_and_lint(cx,
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, "_"))
71 declare_lint!(pub CMP_NAN, Deny,
72 "comparisons to NAN (which will always return false, which is probably not intended)");
77 impl LintPass for CmpNan {
78 fn get_lints(&self) -> LintArray {
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);
90 if let &ExprPath(_, ref path) = &right.node {
91 check_nan(cx, path, expr.span);
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");
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)");
110 #[derive(Copy,Clone)]
113 impl LintPass for FloatCmp {
114 fn get_lints(&self) -> LintArray {
115 lint_array!(FLOAT_CMP)
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 {
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") {
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, "..")));
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
150 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
151 if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
158 declare_lint!(pub CMP_OWNED, Warn,
159 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
161 #[derive(Copy,Clone)]
164 impl LintPass for CmpOwned {
165 fn get_lints(&self) -> LintArray {
166 lint_array!(CMP_OWNED)
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)
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, "..")
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, "..")
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, "..")));
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));
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 }
224 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
226 #[derive(Copy,Clone)]
227 pub struct ModuloOne;
229 impl LintPass for ModuloOne {
230 fn get_lints(&self) -> LintArray {
231 lint_array!(MODULO_ONE)
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");
247 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
249 #[derive(Copy,Clone)]
250 pub struct PatternPass;
252 impl LintPass for PatternPass {
253 fn get_lints(&self) -> LintArray {
254 lint_array!(REDUNDANT_PATTERN)
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));