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};
10 use utils::{match_path, snippet, span_lint, span_help_and_lint, walk_ptrs_ty};
12 /// Handles uncategorized lints
13 /// Currently handles linting of if-let-able matches
14 #[allow(missing_copy_implementations)]
18 declare_lint!(pub SINGLE_MATCH, Warn,
19 "Warn on usage of matches with a single nontrivial arm");
21 impl LintPass for MiscPass {
22 fn get_lints(&self) -> LintArray {
23 lint_array!(SINGLE_MATCH)
26 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
27 if let ExprMatch(ref ex, ref arms, ast::MatchSource::Normal) = expr.node {
29 if arms[0].guard.is_none() && arms[1].pats.len() == 1 {
30 match arms[1].body.node {
31 ExprTup(ref v) if v.is_empty() && arms[1].guard.is_none() => (),
32 ExprBlock(ref b) if b.stmts.is_empty() && arms[1].guard.is_none() => (),
35 // In some cases, an exhaustive match is preferred to catch situations when
36 // an enum is extended. So we only consider cases where a `_` wildcard is used
37 if arms[1].pats[0].node == PatWild(PatWildSingle) &&
38 arms[0].pats.len() == 1 {
39 let body_code = snippet(cx, arms[0].body.span, "..");
40 let suggestion = if let ExprBlock(_) = arms[0].body.node {
41 body_code.into_owned()
43 format!("{{ {} }}", body_code)
45 span_help_and_lint(cx, SINGLE_MATCH, expr.span,
46 "you seem to be trying to use match for \
47 destructuring a single pattern. Did you mean to \
49 &*format!("try\nif let {} = {} {}",
50 snippet(cx, arms[0].pats[0].span, ".."),
51 snippet(cx, ex.span, ".."),
62 declare_lint!(pub STR_TO_STRING, Warn, "Warn when a String could use to_owned() instead of to_string()");
64 #[allow(missing_copy_implementations)]
65 pub struct StrToStringPass;
67 impl LintPass for StrToStringPass {
68 fn get_lints(&self) -> LintArray {
69 lint_array!(STR_TO_STRING)
72 fn check_expr(&mut self, cx: &Context, expr: &ast::Expr) {
74 ast::ExprMethodCall(ref method, _, ref args)
75 if method.node.name == "to_string"
76 && is_str(cx, &*args[0]) => {
77 span_lint(cx, STR_TO_STRING, expr.span, "`str.to_owned()` is faster");
82 fn is_str(cx: &Context, expr: &ast::Expr) -> bool {
83 match walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
92 declare_lint!(pub TOPLEVEL_REF_ARG, Warn, "Warn about pattern matches with top-level `ref` bindings");
94 #[allow(missing_copy_implementations)]
95 pub struct TopLevelRefPass;
97 impl LintPass for TopLevelRefPass {
98 fn get_lints(&self) -> LintArray {
99 lint_array!(TOPLEVEL_REF_ARG)
102 fn check_fn(&mut self, cx: &Context, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
103 for ref arg in decl.inputs.iter() {
104 if let PatIdent(BindByRef(_), _, _) = arg.pat.node {
108 "`ref` directly on a function argument is ignored. Consider using a reference type instead."
115 declare_lint!(pub CMP_NAN, Deny, "Deny comparisons to std::f32::NAN or std::f64::NAN");
117 #[derive(Copy,Clone)]
120 impl LintPass for CmpNan {
121 fn get_lints(&self) -> LintArray {
125 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
126 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
127 if is_comparison_binop(cmp.node) {
128 if let &ExprPath(_, ref path) = &left.node {
129 check_nan(cx, path, expr.span);
131 if let &ExprPath(_, ref path) = &right.node {
132 check_nan(cx, path, expr.span);
139 fn check_nan(cx: &Context, path: &Path, span: Span) {
140 path.segments.last().map(|seg| if seg.identifier.name == "NAN" {
141 span_lint(cx, CMP_NAN, span,
142 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
146 declare_lint!(pub FLOAT_CMP, Warn,
147 "Warn on ==/!= comparison of floaty values");
149 #[derive(Copy,Clone)]
152 impl LintPass for FloatCmp {
153 fn get_lints(&self) -> LintArray {
154 lint_array!(FLOAT_CMP)
157 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
158 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
160 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
161 span_lint(cx, FLOAT_CMP, expr.span, &format!(
162 "{}-comparison of f32 or f64 detected. Consider changing this to `abs({} - {}) < epsilon` for some suitable value of epsilon.",
163 binop_to_string(op), snippet(cx, left.span, ".."),
164 snippet(cx, right.span, "..")));
170 fn is_float(cx: &Context, expr: &Expr) -> bool {
171 if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
178 declare_lint!(pub PRECEDENCE, Warn,
179 "Warn on mixing bit ops with integer arithmetic without parenthesis");
181 #[derive(Copy,Clone)]
182 pub struct Precedence;
184 impl LintPass for Precedence {
185 fn get_lints(&self) -> LintArray {
186 lint_array!(PRECEDENCE)
189 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
190 if let ExprBinary(Spanned { node: op, ..}, ref left, ref right) = expr.node {
191 if is_bit_op(op) && (is_arith_expr(left) || is_arith_expr(right)) {
192 span_lint(cx, PRECEDENCE, expr.span,
193 "operator precedence can trip the unwary. Consider adding parenthesis to the subexpression.");
199 fn is_arith_expr(expr : &Expr) -> bool {
201 ExprBinary(Spanned { node: op, ..}, _, _) => is_arith_op(op),
206 fn is_bit_op(op : BinOp_) -> bool {
208 BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => true,
213 fn is_arith_op(op : BinOp_) -> bool {
215 BiAdd | BiSub | BiMul | BiDiv | BiRem => true,
220 declare_lint!(pub CMP_OWNED, Warn,
221 "Warn on creating an owned string just for comparison");
223 #[derive(Copy,Clone)]
226 impl LintPass for CmpOwned {
227 fn get_lints(&self) -> LintArray {
228 lint_array!(CMP_OWNED)
231 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
232 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
233 if is_comparison_binop(cmp.node) {
234 check_to_owned(cx, left, right.span);
235 check_to_owned(cx, right, left.span)
241 fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
243 &ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
244 let name = ident.name;
245 if name == "to_string" ||
246 name == "to_owned" && is_str_arg(cx, args) {
247 span_lint(cx, CMP_OWNED, expr.span, &format!(
248 "this creates an owned instance just for comparison. \
249 Consider using `{}.as_slice()` to compare without allocation.",
250 snippet(cx, other_span, "..")))
253 &ExprCall(ref path, _) => {
254 if let &ExprPath(None, ref path) = &path.node {
255 if match_path(path, &["String", "from_str"]) ||
256 match_path(path, &["String", "from"]) {
257 span_lint(cx, CMP_OWNED, expr.span, &format!(
258 "this creates an owned instance just for comparison. \
259 Consider using `{}.as_slice()` to compare without allocation.",
260 snippet(cx, other_span, "..")))
268 fn is_str_arg(cx: &Context, args: &[P<Expr>]) -> bool {
269 args.len() == 1 && if let ty::TyStr =
270 walk_ptrs_ty(cx.tcx.expr_ty(&*args[0])).sty { true } else { false }
273 declare_lint!(pub MODULO_ONE, Warn, "Warn on expressions that include % 1, which is always 0");
275 #[derive(Copy,Clone)]
276 pub struct ModuloOne;
278 impl LintPass for ModuloOne {
279 fn get_lints(&self) -> LintArray {
280 lint_array!(MODULO_ONE)
283 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
284 if let ExprBinary(ref cmp, _, ref right) = expr.node {
285 if let &Spanned {node: BinOp_::BiRem, ..} = cmp {
286 if is_lit_one(right) {
287 cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
294 fn is_lit_one(expr: &Expr) -> bool {
295 if let ExprLit(ref spanned) = expr.node {
296 if let LitInt(1, _) = spanned.node {