3 use rustc::middle::const_eval::ConstVal::Float;
4 use rustc::middle::const_eval::EvalHint::ExprTypeChecked;
5 use rustc::middle::const_eval::eval_const_expr_partial;
7 use rustc_front::hir::*;
8 use rustc_front::intravisit::FnKind;
9 use rustc_front::util::{is_comparison_binop, binop_to_string};
10 use syntax::codemap::{Span, Spanned, ExpnFormat};
12 use utils::{get_item_name, match_path, snippet, get_parent_expr, span_lint};
13 use utils::{span_lint_and_then, walk_ptrs_ty, is_integer_literal, implements_trait};
15 /// **What it does:** This lint checks for function arguments and let bindings denoted as `ref`.
17 /// **Why is this bad?** The `ref` declaration makes the function take an owned value, but turns the argument into a reference (which means that the value is destroyed when exiting the function). This adds not much value: either take a reference type, or take an owned value and create references in the body.
19 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The type of `x` is more obvious with the former.
21 /// **Known problems:** If the argument is dereferenced within the function, removing the `ref` will lead to errors. This can be fixed by removing the dereferences, e.g. changing `*x` to `x` within the function.
23 /// **Example:** `fn foo(ref x: u8) -> bool { .. }`
25 pub TOPLEVEL_REF_ARG, Warn,
26 "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
27 or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
31 #[allow(missing_copy_implementations)]
32 pub struct TopLevelRefPass;
34 impl LintPass for TopLevelRefPass {
35 fn get_lints(&self) -> LintArray {
36 lint_array!(TOPLEVEL_REF_ARG)
40 impl LateLintPass for TopLevelRefPass {
41 fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
42 if let FnKind::Closure = k {
43 // Does not apply to closures
46 for ref arg in &decl.inputs {
47 if let PatKind::Ident(BindByRef(_), _, _) = arg.pat.node {
51 "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
55 fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
58 let StmtDecl(ref d, _) = s.node,
59 let DeclLocal(ref l) = d.node,
60 let PatKind::Ident(BindByRef(_), i, None) = l.pat.node,
61 let Some(ref init) = l.init
63 let tyopt = if let Some(ref ty) = l.ty {
64 format!(": {}", snippet(cx, ty.span, "_"))
68 span_lint_and_then(cx,
71 "`ref` on an entire `let` pattern is discouraged, take a reference with & instead",
73 db.span_suggestion(s.span,
75 format!("let {}{} = &{};",
76 snippet(cx, i.span, "_"),
78 snippet(cx, init.span, "_")));
86 /// **What it does:** This lint checks for comparisons to NAN.
88 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
90 /// **Known problems:** None
92 /// **Example:** `x == NAN`
93 declare_lint!(pub CMP_NAN, Deny,
94 "comparisons to NAN (which will always return false, which is probably not intended)");
99 impl LintPass for CmpNan {
100 fn get_lints(&self) -> LintArray {
105 impl LateLintPass for CmpNan {
106 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
107 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
108 if is_comparison_binop(cmp.node) {
109 if let ExprPath(_, ref path) = left.node {
110 check_nan(cx, path, expr.span);
112 if let ExprPath(_, ref path) = right.node {
113 check_nan(cx, path, expr.span);
120 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
121 path.segments.last().map(|seg| {
122 if seg.identifier.name.as_str() == "NAN" {
126 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
131 /// **What it does:** This lint checks for (in-)equality comparisons on floating-point values (apart from zero), except in functions called `*eq*` (which probably implement equality for a type involving floats).
133 /// **Why is this bad?** Floating point calculations are usually imprecise, so asking if two values are *exactly* equal is asking for trouble. For a good guide on what to do, see [the floating point guide](http://www.floating-point-gui.de/errors/comparison).
135 /// **Known problems:** None
137 /// **Example:** `y == 1.23f64`
138 declare_lint!(pub FLOAT_CMP, Warn,
139 "using `==` or `!=` on float values (as floating-point operations \
140 usually involve rounding errors, it is always better to check for approximate \
141 equality within small bounds)");
143 #[derive(Copy,Clone)]
146 impl LintPass for FloatCmp {
147 fn get_lints(&self) -> LintArray {
148 lint_array!(FLOAT_CMP)
152 impl LateLintPass for FloatCmp {
153 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
154 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
156 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
157 if is_allowed(cx, left) || is_allowed(cx, right) {
160 if let Some(name) = get_item_name(cx, expr) {
161 let name = name.as_str();
162 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
163 name.ends_with("_eq") {
170 &format!("{}-comparison of f32 or f64 detected. Consider changing this to `abs({} - {}) < \
171 epsilon` for some suitable value of epsilon",
173 snippet(cx, left.span, ".."),
174 snippet(cx, right.span, "..")));
180 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
181 let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
182 if let Ok(Float(val)) = res {
183 val == 0.0 || val == ::std::f64::INFINITY || val == ::std::f64::NEG_INFINITY
189 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
190 if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
197 /// **What it does:** This lint checks for conversions to owned values just for the sake of a comparison.
199 /// **Why is this bad?** The comparison can operate on a reference, so creating an owned value effectively throws it away directly afterwards, which is needlessly consuming code and heap space.
201 /// **Known problems:** None
203 /// **Example:** `x.to_owned() == y`
204 declare_lint!(pub CMP_OWNED, Warn,
205 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
207 #[derive(Copy,Clone)]
210 impl LintPass for CmpOwned {
211 fn get_lints(&self) -> LintArray {
212 lint_array!(CMP_OWNED)
216 impl LateLintPass for CmpOwned {
217 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
218 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
219 if is_comparison_binop(cmp.node) {
220 check_to_owned(cx, left, right, true, cmp.span);
221 check_to_owned(cx, right, left, false, cmp.span)
227 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
228 let (arg_ty, snip) = match expr.node {
229 ExprMethodCall(Spanned{node: ref name, ..}, _, ref args) if args.len() == 1 => {
230 if name.as_str() == "to_string" || name.as_str() == "to_owned" && is_str_arg(cx, args) {
231 (cx.tcx.expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
236 ExprCall(ref path, ref v) if v.len() == 1 => {
237 if let ExprPath(None, ref path) = path.node {
238 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
239 (cx.tcx.expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
250 let other_ty = cx.tcx.expr_ty(other);
251 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
256 if !implements_trait(cx, arg_ty, partial_eq_trait_id, Some(vec![other_ty])) {
264 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
265 compare without allocation",
267 snippet(cx, op, "=="),
268 snippet(cx, other.span, "..")));
273 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
274 compare without allocation",
275 snippet(cx, other.span, ".."),
276 snippet(cx, op, "=="),
282 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
284 if let ty::TyStr = walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty {
291 /// **What it does:** This lint checks for getting the remainder of a division by one.
293 /// **Why is this bad?** The result can only ever be zero. No one will write such code deliberately, unless trying to win an Underhanded Rust Contest. Even for that contest, it's probably a bad idea. Use something more underhanded.
295 /// **Known problems:** None
297 /// **Example:** `x % 1`
298 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
300 #[derive(Copy,Clone)]
301 pub struct ModuloOne;
303 impl LintPass for ModuloOne {
304 fn get_lints(&self) -> LintArray {
305 lint_array!(MODULO_ONE)
309 impl LateLintPass for ModuloOne {
310 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
311 if let ExprBinary(ref cmp, _, ref right) = expr.node {
312 if let Spanned {node: BinOp_::BiRem, ..} = *cmp {
313 if is_integer_literal(right, 1) {
314 cx.span_lint(MODULO_ONE, expr.span, "any number modulo 1 will be 0");
321 /// **What it does:** This lint checks for patterns in the form `name @ _`.
323 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
325 /// **Known problems:** None
331 /// y @ _ => (), // easier written as `y`,
334 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
336 #[derive(Copy,Clone)]
337 pub struct PatternPass;
339 impl LintPass for PatternPass {
340 fn get_lints(&self) -> LintArray {
341 lint_array!(REDUNDANT_PATTERN)
345 impl LateLintPass for PatternPass {
346 fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
347 if let PatKind::Ident(_, ref ident, Some(ref right)) = pat.node {
348 if right.node == PatKind::Wild {
349 cx.span_lint(REDUNDANT_PATTERN,
351 &format!("the `{} @ _` pattern can be written as just `{}`",
360 /// **What it does:** This lint checks for the use of bindings with a single leading underscore
362 /// **Why is this bad?** A single leading underscore is usually used to indicate that a binding
363 /// will not be used. Using such a binding breaks this expectation.
365 /// **Known problems:** None
370 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
371 /// // We should rename `_x` to `x`
373 declare_lint!(pub USED_UNDERSCORE_BINDING, Warn,
374 "using a binding which is prefixed with an underscore");
376 #[derive(Copy, Clone)]
377 pub struct UsedUnderscoreBinding;
379 impl LintPass for UsedUnderscoreBinding {
380 fn get_lints(&self) -> LintArray {
381 lint_array!(USED_UNDERSCORE_BINDING)
385 impl LateLintPass for UsedUnderscoreBinding {
386 #[cfg_attr(rustfmt, rustfmt_skip)]
387 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
388 if in_attributes_expansion(cx, expr) {
389 // Don't lint things expanded by #[derive(...)], etc
392 let needs_lint = match expr.node {
393 ExprPath(_, ref path) => {
394 let ident = path.segments
396 .expect("path should always have at least one segment")
398 ident.name.as_str().starts_with('_') &&
399 !ident.name.as_str().starts_with("__") &&
400 ident.name != ident.unhygienic_name &&
401 is_used(cx, expr) // not in bang macro
403 ExprField(_, spanned) => {
404 let name = spanned.node.as_str();
405 name.starts_with('_') && !name.starts_with("__")
410 cx.span_lint(USED_UNDERSCORE_BINDING,
412 "used binding which is prefixed with an underscore. A leading underscore signals that a \
413 binding will not be used.");
418 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
419 /// of what it means for an expression to be "used".
420 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
421 if let Some(ref parent) = get_parent_expr(cx, expr) {
423 ExprAssign(_, ref rhs) | ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
424 _ => is_used(cx, &parent),
431 /// Test whether an expression is in a macro expansion (e.g. something generated by #[derive(...)]
433 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
434 cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
435 info_opt.map_or(false, |info| {
436 match info.callee.format {
437 ExpnFormat::MacroAttribute(_) => true,