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;
10 use utils::{get_item_name, match_path, snippet, span_lint, walk_ptrs_ty, is_integer_literal};
11 use utils::span_help_and_lint;
14 declare_lint!(pub TOPLEVEL_REF_ARG, Warn,
15 "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
16 or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
17 references with `&`.");
19 #[allow(missing_copy_implementations)]
20 pub struct TopLevelRefPass;
22 impl LintPass for TopLevelRefPass {
23 fn get_lints(&self) -> LintArray {
24 lint_array!(TOPLEVEL_REF_ARG)
28 impl LateLintPass for TopLevelRefPass {
29 fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
30 if let FnKind::Closure = k {
31 // Does not apply to closures
34 for ref arg in &decl.inputs {
35 if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
39 "`ref` directly on a function argument is ignored. Consider using a reference type instead."
44 fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
47 let StmtDecl(ref d, _) = s.node,
48 let DeclLocal(ref l) = d.node,
49 let PatIdent(BindByRef(_), i, None) = l.pat.node,
50 let Some(ref init) = l.init
52 let tyopt = if let Some(ref ty) = l.ty {
53 format!(": {:?} ", ty)
57 span_help_and_lint(cx,
60 "`ref` on an entire `let` pattern is discouraged, take a reference with & instead",
61 &format!("try `let {} {}= &{};`", snippet(cx, i.span, "_"),
62 tyopt, snippet(cx, init.span, "_"))
69 declare_lint!(pub CMP_NAN, Deny,
70 "comparisons to NAN (which will always return false, which is probably not intended)");
75 impl LintPass for CmpNan {
76 fn get_lints(&self) -> LintArray {
81 impl LateLintPass for CmpNan {
82 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
83 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
84 if is_comparison_binop(cmp.node) {
85 if let &ExprPath(_, ref path) = &left.node {
86 check_nan(cx, path, expr.span);
88 if let &ExprPath(_, ref path) = &right.node {
89 check_nan(cx, path, expr.span);
96 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
97 path.segments.last().map(|seg| if seg.identifier.name == "NAN" {
98 span_lint(cx, CMP_NAN, span,
99 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
103 declare_lint!(pub FLOAT_CMP, Warn,
104 "using `==` or `!=` on float values (as floating-point operations \
105 usually involve rounding errors, it is always better to check for approximate \
106 equality within small bounds)");
108 #[derive(Copy,Clone)]
111 impl LintPass for FloatCmp {
112 fn get_lints(&self) -> LintArray {
113 lint_array!(FLOAT_CMP)
117 impl LateLintPass for FloatCmp {
118 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
119 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
121 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
122 if constant(cx, left).or_else(|| constant(cx, right)).map_or(
123 false, |c| c.0.as_float().map_or(false, |f| f == 0.0)) {
126 if let Some(name) = get_item_name(cx, expr) {
127 if name == "eq" || name == "ne" || name == "is_nan" ||
128 name.as_str().starts_with("eq_") ||
129 name.as_str().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_float(cx: &LateContext, expr: &Expr) -> bool {
144 if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
151 declare_lint!(pub CMP_OWNED, Warn,
152 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
154 #[derive(Copy,Clone)]
157 impl LintPass for CmpOwned {
158 fn get_lints(&self) -> LintArray {
159 lint_array!(CMP_OWNED)
163 impl LateLintPass for CmpOwned {
164 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
165 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
166 if is_comparison_binop(cmp.node) {
167 check_to_owned(cx, left, right.span);
168 check_to_owned(cx, right, left.span)
174 fn check_to_owned(cx: &LateContext, expr: &Expr, other_span: Span) {
176 ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
177 let name = ident.name;
178 if name == "to_string" ||
179 name == "to_owned" && is_str_arg(cx, args) {
180 span_lint(cx, CMP_OWNED, expr.span, &format!(
181 "this creates an owned instance just for comparison. \
182 Consider using `{}.as_slice()` to compare without allocation",
183 snippet(cx, other_span, "..")))
186 ExprCall(ref path, _) => {
187 if let &ExprPath(None, ref path) = &path.node {
188 if match_path(path, &["String", "from_str"]) ||
189 match_path(path, &["String", "from"]) {
190 span_lint(cx, CMP_OWNED, expr.span, &format!(
191 "this creates an owned instance just for comparison. \
192 Consider using `{}.as_slice()` to compare without allocation",
193 snippet(cx, other_span, "..")))
201 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
202 args.len() == 1 && if let ty::TyStr =
203 walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty { true } else { false }
206 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
208 #[derive(Copy,Clone)]
209 pub struct ModuloOne;
211 impl LintPass for ModuloOne {
212 fn get_lints(&self) -> LintArray {
213 lint_array!(MODULO_ONE)
217 impl LateLintPass for ModuloOne {
218 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
219 if let ExprBinary(ref cmp, _, ref right) = expr.node {
220 if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
221 if is_integer_literal(right, 1) {
222 cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
229 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
231 #[derive(Copy,Clone)]
232 pub struct PatternPass;
234 impl LintPass for PatternPass {
235 fn get_lints(&self) -> LintArray {
236 lint_array!(REDUNDANT_PATTERN)
240 impl LateLintPass for PatternPass {
241 fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
242 if let PatIdent(_, ref ident, Some(ref right)) = pat.node {
243 if right.node == PatWild(PatWildSingle) {
244 cx.span_lint(REDUNDANT_PATTERN, pat.span, &format!(
245 "the `{} @ _` pattern can be written as just `{}`",
246 ident.node.name, ident.node.name));