4 use syntax::ast_util::{is_comparison_binop, binop_to_string};
5 use syntax::visit::{FnKind};
6 use rustc::lint::{Context, LintPass, LintArray, Lint, Level};
8 use syntax::codemap::{Span, Spanned};
11 use utils::{match_path, snippet, snippet_block, span_lint, span_help_and_lint, walk_ptrs_ty};
13 /// Handles uncategorized lints
14 /// Currently handles linting of if-let-able matches
15 #[allow(missing_copy_implementations)]
19 declare_lint!(pub SINGLE_MATCH, Warn,
20 "a match statement with a single nontrivial arm (i.e, where the other arm \
21 is `_ => {}`) is used; recommends `if let` instead");
23 impl LintPass for MiscPass {
24 fn get_lints(&self) -> LintArray {
25 lint_array!(SINGLE_MATCH)
28 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
29 if let ExprMatch(ref ex, ref arms, ast::MatchSource::Normal) = expr.node {
30 // check preconditions: only two arms
32 // both of the arms have a single pattern and no guard
33 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
34 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
35 // and the second pattern is a `_` wildcard: this is not strictly necessary,
36 // since the exhaustiveness check will ensure the last one is a catch-all,
37 // but in some cases, an explicit match is preferred to catch situations
38 // when an enum is extended, so we don't consider these cases
39 arms[1].pats[0].node == PatWild(PatWildSingle) &&
40 // finally, we don't want any content in the second arm (unit or empty block)
41 is_unit_expr(&*arms[1].body)
43 let body_code = snippet_block(cx, arms[0].body.span, "..");
44 let body_code = if let ExprBlock(_) = arms[0].body.node {
47 Cow::Owned(format!("{{ {} }}", body_code))
49 span_help_and_lint(cx, SINGLE_MATCH, expr.span,
50 "you seem to be trying to use match for \
51 destructuring a single pattern. Did you mean to \
53 &*format!("try\nif let {} = {} {}",
54 snippet(cx, arms[0].pats[0].span, ".."),
55 snippet(cx, ex.span, ".."),
63 fn is_unit_expr(expr: &Expr) -> bool {
65 ExprTup(ref v) if v.is_empty() => true,
66 ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
72 declare_lint!(pub TOPLEVEL_REF_ARG, Warn,
73 "a function argument is declared `ref` (i.e. `fn foo(ref x: u8)`, but not \
74 `fn foo((ref x, ref y): (u8, u8))`)");
76 #[allow(missing_copy_implementations)]
77 pub struct TopLevelRefPass;
79 impl LintPass for TopLevelRefPass {
80 fn get_lints(&self) -> LintArray {
81 lint_array!(TOPLEVEL_REF_ARG)
84 fn check_fn(&mut self, cx: &Context, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
85 for ref arg in &decl.inputs {
86 if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
90 "`ref` directly on a function argument is ignored. Consider using a reference type instead."
97 declare_lint!(pub CMP_NAN, Deny,
98 "comparisons to NAN (which will always return false, which is probably not intended)");
100 #[derive(Copy,Clone)]
103 impl LintPass for CmpNan {
104 fn get_lints(&self) -> LintArray {
108 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
109 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
110 if is_comparison_binop(cmp.node) {
111 if let &ExprPath(_, ref path) = &left.node {
112 check_nan(cx, path, expr.span);
114 if let &ExprPath(_, ref path) = &right.node {
115 check_nan(cx, path, expr.span);
122 fn check_nan(cx: &Context, path: &Path, span: Span) {
123 path.segments.last().map(|seg| if seg.identifier.name == "NAN" {
124 span_lint(cx, CMP_NAN, span,
125 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
129 declare_lint!(pub FLOAT_CMP, Warn,
130 "using `==` or `!=` on float values (as floating-point operations \
131 usually involve rounding errors, it is always better to check for approximate \
132 equality within small bounds)");
134 #[derive(Copy,Clone)]
137 impl LintPass for FloatCmp {
138 fn get_lints(&self) -> LintArray {
139 lint_array!(FLOAT_CMP)
142 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
143 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
145 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
146 span_lint(cx, FLOAT_CMP, expr.span, &format!(
147 "{}-comparison of f32 or f64 detected. Consider changing this to \
148 `abs({} - {}) < epsilon` for some suitable value of epsilon",
149 binop_to_string(op), snippet(cx, left.span, ".."),
150 snippet(cx, right.span, "..")));
156 fn is_float(cx: &Context, expr: &Expr) -> bool {
157 if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
164 declare_lint!(pub PRECEDENCE, Warn,
165 "expressions where precedence may trip up the unwary reader of the source; \
166 suggests adding parentheses, e.g. `x << 2 + y` will be parsed as `x << (2 + y)`");
168 #[derive(Copy,Clone)]
169 pub struct Precedence;
171 impl LintPass for Precedence {
172 fn get_lints(&self) -> LintArray {
173 lint_array!(PRECEDENCE)
176 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
177 if let ExprBinary(Spanned { node: op, ..}, ref left, ref right) = expr.node {
178 if is_bit_op(op) && (is_arith_expr(left) || is_arith_expr(right)) {
179 span_lint(cx, PRECEDENCE, expr.span,
180 "operator precedence can trip the unwary. Consider adding parentheses \
181 to the subexpression");
187 fn is_arith_expr(expr : &Expr) -> bool {
189 ExprBinary(Spanned { node: op, ..}, _, _) => is_arith_op(op),
194 fn is_bit_op(op : BinOp_) -> bool {
196 BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => true,
201 fn is_arith_op(op : BinOp_) -> bool {
203 BiAdd | BiSub | BiMul | BiDiv | BiRem => true,
208 declare_lint!(pub CMP_OWNED, Warn,
209 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
211 #[derive(Copy,Clone)]
214 impl LintPass for CmpOwned {
215 fn get_lints(&self) -> LintArray {
216 lint_array!(CMP_OWNED)
219 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
220 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
221 if is_comparison_binop(cmp.node) {
222 check_to_owned(cx, left, right.span);
223 check_to_owned(cx, right, left.span)
229 fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
231 &ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
232 let name = ident.name;
233 if name == "to_string" ||
234 name == "to_owned" && is_str_arg(cx, args) {
235 span_lint(cx, CMP_OWNED, expr.span, &format!(
236 "this creates an owned instance just for comparison. \
237 Consider using `{}.as_slice()` to compare without allocation",
238 snippet(cx, other_span, "..")))
241 &ExprCall(ref path, _) => {
242 if let &ExprPath(None, ref path) = &path.node {
243 if match_path(path, &["String", "from_str"]) ||
244 match_path(path, &["String", "from"]) {
245 span_lint(cx, CMP_OWNED, expr.span, &format!(
246 "this creates an owned instance just for comparison. \
247 Consider using `{}.as_slice()` to compare without allocation",
248 snippet(cx, other_span, "..")))
256 fn is_str_arg(cx: &Context, args: &[P<Expr>]) -> bool {
257 args.len() == 1 && if let ty::TyStr =
258 walk_ptrs_ty(cx.tcx.expr_ty(&*args[0])).sty { true } else { false }
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)
271 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
272 if let ExprBinary(ref cmp, _, ref right) = expr.node {
273 if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
274 if is_lit_one(right) {
275 cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
282 fn is_lit_one(expr: &Expr) -> bool {
283 if let ExprLit(ref spanned) = expr.node {
284 if let LitInt(1, _) = spanned.node {