]> git.lizzy.rs Git - rust.git/blob - src/misc.rs
add precedence_negative_literal lint
[rust.git] / src / misc.rs
1 use rustc::lint::*;
2 use syntax::ptr::P;
3 use syntax::ast::*;
4 use syntax::ast_util::{is_comparison_binop, binop_to_string};
5 use syntax::codemap::{Span, Spanned};
6 use syntax::visit::FnKind;
7 use rustc::middle::ty;
8
9 use utils::{match_path, snippet, span_lint, walk_ptrs_ty};
10 use consts::constant;
11
12 declare_lint!(pub TOPLEVEL_REF_ARG, Warn,
13               "a function argument is declared `ref` (i.e. `fn foo(ref x: u8)`, but not \
14                `fn foo((ref x, ref y): (u8, u8))`)");
15
16 #[allow(missing_copy_implementations)]
17 pub struct TopLevelRefPass;
18
19 impl LintPass for TopLevelRefPass {
20     fn get_lints(&self) -> LintArray {
21         lint_array!(TOPLEVEL_REF_ARG)
22     }
23
24     fn check_fn(&mut self, cx: &Context, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
25         if let FnKind::FkClosure = k {
26             // Does not apply to closures
27             return
28         }
29         for ref arg in &decl.inputs {
30             if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
31                 span_lint(cx,
32                     TOPLEVEL_REF_ARG,
33                     arg.pat.span,
34                     "`ref` directly on a function argument is ignored. Consider using a reference type instead."
35                 );
36             }
37         }
38     }
39 }
40
41 declare_lint!(pub CMP_NAN, Deny,
42               "comparisons to NAN (which will always return false, which is probably not intended)");
43
44 #[derive(Copy,Clone)]
45 pub struct CmpNan;
46
47 impl LintPass for CmpNan {
48     fn get_lints(&self) -> LintArray {
49         lint_array!(CMP_NAN)
50     }
51
52     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
53         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
54             if is_comparison_binop(cmp.node) {
55                 if let &ExprPath(_, ref path) = &left.node {
56                     check_nan(cx, path, expr.span);
57                 }
58                 if let &ExprPath(_, ref path) = &right.node {
59                     check_nan(cx, path, expr.span);
60                 }
61             }
62         }
63     }
64 }
65
66 fn check_nan(cx: &Context, path: &Path, span: Span) {
67     path.segments.last().map(|seg| if seg.identifier.name == "NAN" {
68         span_lint(cx, CMP_NAN, span,
69             "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
70     });
71 }
72
73 declare_lint!(pub FLOAT_CMP, Warn,
74               "using `==` or `!=` on float values (as floating-point operations \
75                usually involve rounding errors, it is always better to check for approximate \
76                equality within small bounds)");
77
78 #[derive(Copy,Clone)]
79 pub struct FloatCmp;
80
81 impl LintPass for FloatCmp {
82     fn get_lints(&self) -> LintArray {
83         lint_array!(FLOAT_CMP)
84     }
85
86     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
87         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
88             let op = cmp.node;
89             if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
90                 if constant(cx, left).or_else(|| constant(cx, right)).map_or(
91                         false, |c| c.0.as_float().map_or(false, |f| f == 0.0)) {
92                     return;
93                 }
94                 span_lint(cx, FLOAT_CMP, expr.span, &format!(
95                     "{}-comparison of f32 or f64 detected. Consider changing this to \
96                      `abs({} - {}) < epsilon` for some suitable value of epsilon",
97                     binop_to_string(op), snippet(cx, left.span, ".."),
98                     snippet(cx, right.span, "..")));
99             }
100         }
101     }
102 }
103
104 fn is_float(cx: &Context, expr: &Expr) -> bool {
105     if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
106         true
107     } else {
108         false
109     }
110 }
111
112 declare_lint!(pub CMP_OWNED, Warn,
113               "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
114
115 #[derive(Copy,Clone)]
116 pub struct CmpOwned;
117
118 impl LintPass for CmpOwned {
119     fn get_lints(&self) -> LintArray {
120         lint_array!(CMP_OWNED)
121     }
122
123     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
124         if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
125             if is_comparison_binop(cmp.node) {
126                 check_to_owned(cx, left, right.span);
127                 check_to_owned(cx, right, left.span)
128             }
129         }
130     }
131 }
132
133 fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
134     match expr.node {
135         ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
136             let name = ident.name;
137             if name == "to_string" ||
138                 name == "to_owned" && is_str_arg(cx, args) {
139                     span_lint(cx, CMP_OWNED, expr.span, &format!(
140                         "this creates an owned instance just for comparison. \
141                          Consider using `{}.as_slice()` to compare without allocation",
142                         snippet(cx, other_span, "..")))
143                 }
144         },
145         ExprCall(ref path, _) => {
146             if let &ExprPath(None, ref path) = &path.node {
147                 if match_path(path, &["String", "from_str"]) ||
148                     match_path(path, &["String", "from"]) {
149                         span_lint(cx, CMP_OWNED, expr.span, &format!(
150                             "this creates an owned instance just for comparison. \
151                              Consider using `{}.as_slice()` to compare without allocation",
152                             snippet(cx, other_span, "..")))
153                     }
154             }
155         },
156         _ => ()
157     }
158 }
159
160 fn is_str_arg(cx: &Context, args: &[P<Expr>]) -> bool {
161     args.len() == 1 && if let ty::TyStr =
162         walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty { true } else { false }
163 }
164
165 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
166
167 #[derive(Copy,Clone)]
168 pub struct ModuloOne;
169
170 impl LintPass for ModuloOne {
171     fn get_lints(&self) -> LintArray {
172         lint_array!(MODULO_ONE)
173     }
174
175     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
176         if let ExprBinary(ref cmp, _, ref right) = expr.node {
177             if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
178                 if is_lit_one(right) {
179                     cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
180                 }
181             }
182         }
183     }
184 }
185
186 fn is_lit_one(expr: &Expr) -> bool {
187     if let ExprLit(ref spanned) = expr.node {
188         if let LitInt(1, _) = spanned.node {
189             return true;
190         }
191     }
192     false
193 }