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