3 use rustc::hir::intravisit::FnKind;
5 use rustc::middle::const_val::ConstVal;
7 use rustc_const_eval::ConstContext;
8 use rustc_const_math::ConstFloat;
9 use syntax::codemap::{Span, ExpnFormat};
10 use utils::{get_item_name, get_parent_expr, implements_trait, in_macro, is_integer_literal, match_path, snippet,
11 span_lint, span_lint_and_then, walk_ptrs_ty, last_path_segment, iter_input_pats, in_constant,
12 match_trait_method, paths};
13 use utils::sugg::Sugg;
14 use syntax::ast::{LitKind, CRATE_NODE_ID};
16 /// **What it does:** Checks for function arguments and let bindings denoted as `ref`.
18 /// **Why is this bad?** The `ref` declaration makes the function take an owned
19 /// value, but turns the argument into a reference (which means that the value
20 /// is destroyed when exiting the function). This adds not much value: either
21 /// take a reference type, or take an owned value and create references in the
24 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
25 /// type of `x` is more obvious with the former.
27 /// **Known problems:** If the argument is dereferenced within the function,
28 /// removing the `ref` will lead to errors. This can be fixed by removing the
29 /// dereferences, e.g. changing `*x` to `x` within the function.
33 /// fn foo(ref x: u8) -> bool { .. }
38 "an entire binding declared as `ref`, in a function argument or a `let` statement"
41 /// **What it does:** Checks for comparisons to NaN.
43 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
44 /// even itself – so those comparisons are simply wrong.
46 /// **Known problems:** None.
55 "comparisons to NAN, which will always return false, probably not intended"
58 /// **What it does:** Checks for (in-)equality comparisons on floating-point
59 /// values (apart from zero), except in functions called `*eq*` (which probably
60 /// implement equality for a type involving floats).
62 /// **Why is this bad?** Floating point calculations are usually imprecise, so
63 /// asking if two values are *exactly* equal is asking for trouble. For a good
64 /// guide on what to do, see [the floating point
65 /// guide](http://www.floating-point-gui.de/errors/comparison).
67 /// **Known problems:** None.
72 /// y != x // where both are floats
77 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
80 /// **What it does:** Checks for conversions to owned values just for the sake
83 /// **Why is this bad?** The comparison can operate on a reference, so creating
84 /// an owned value effectively throws it away directly afterwards, which is
85 /// needlessly consuming code and heap space.
87 /// **Known problems:** None.
96 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`"
99 /// **What it does:** Checks for getting the remainder of a division by one.
101 /// **Why is this bad?** The result can only ever be zero. No one will write
102 /// such code deliberately, unless trying to win an Underhanded Rust
103 /// Contest. Even for that contest, it's probably a bad idea. Use something more
106 /// **Known problems:** None.
115 "taking a number modulo 1, which always returns 0"
118 /// **What it does:** Checks for patterns in the form `name @ _`.
120 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
122 /// **Known problems:** None.
128 /// y @ _ => (), // easier written as `y`,
132 pub REDUNDANT_PATTERN,
134 "using `name @ _` in a pattern"
137 /// **What it does:** Checks for the use of bindings with a single leading underscore.
139 /// **Why is this bad?** A single leading underscore is usually used to indicate
140 /// that a binding will not be used. Using such a binding breaks this
143 /// **Known problems:** The lint does not work properly with desugaring and
144 /// macro, it has been allowed in the mean time.
149 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
150 /// // We should rename `_x` to `x`
153 pub USED_UNDERSCORE_BINDING,
155 "using a binding which is prefixed with an underscore"
158 /// **What it does:** Checks for the use of short circuit boolean conditions as a
161 /// **Why is this bad?** Using a short circuit boolean condition as a statement may
162 /// hide the fact that the second part is executed or not depending on the outcome of
165 /// **Known problems:** None.
169 /// f() && g(); // We should write `if f() { g(); }`.
172 pub SHORT_CIRCUIT_STATEMENT,
174 "using a short circuit boolean condition as a statement"
177 /// **What it does:** Catch casts from `0` to some pointer type
179 /// **Why is this bad?** This generally means `null` and is better expressed as
180 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
182 /// **Known problems:** None.
192 "using 0 as *{const, mut} T"
195 #[derive(Copy, Clone)]
198 impl LintPass for Pass {
199 fn get_lints(&self) -> LintArray {
200 lint_array!(TOPLEVEL_REF_ARG,
206 USED_UNDERSCORE_BINDING,
207 SHORT_CIRCUIT_STATEMENT,
212 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
215 cx: &LateContext<'a, 'tcx>,
222 if let FnKind::Closure(_) = k {
223 // Does not apply to closures
226 for arg in iter_input_pats(decl, body) {
227 if let PatKind::Binding(BindByRef(_), _, _, _) = arg.pat.node {
231 "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
236 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, s: &'tcx Stmt) {
238 let StmtDecl(ref d, _) = s.node,
239 let DeclLocal(ref l) = d.node,
240 let PatKind::Binding(BindByRef(mt), _, i, None) = l.pat.node,
241 let Some(ref init) = l.init
243 let init = Sugg::hir(cx, init, "..");
244 let (mutopt,initref) = if mt == Mutability::MutMutable {
245 ("mut ", init.mut_addr())
249 let tyopt = if let Some(ref ty) = l.ty {
250 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
254 span_lint_and_then(cx,
257 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
259 db.span_suggestion(s.span,
261 format!("let {name}{tyopt} = {initref};",
262 name=snippet(cx, i.span, "_"),
269 let StmtSemi(ref expr, _) = s.node,
270 let Expr_::ExprBinary(ref binop, ref a, ref b) = expr.node,
271 binop.node == BiAnd || binop.node == BiOr,
272 let Some(sugg) = Sugg::hir_opt(cx, a),
274 span_lint_and_then(cx,
275 SHORT_CIRCUIT_STATEMENT,
277 "boolean short circuit operator in statement may be clearer using an explicit test",
279 let sugg = if binop.node == BiOr { !sugg } else { sugg };
280 db.span_suggestion(s.span, "replace it with",
281 format!("if {} {{ {}; }}", sugg, &snippet(cx, b.span, "..")));
286 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
288 ExprCast(ref e, ref ty) => {
289 check_cast(cx, expr.span, e, ty);
292 ExprBinary(ref cmp, ref left, ref right) => {
294 if op.is_comparison() {
295 if let ExprPath(QPath::Resolved(_, ref path)) = left.node {
296 check_nan(cx, path, expr);
298 if let ExprPath(QPath::Resolved(_, ref path)) = right.node {
299 check_nan(cx, path, expr);
301 check_to_owned(cx, left, right);
302 check_to_owned(cx, right, left);
304 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
305 if is_allowed(cx, left) || is_allowed(cx, right) {
308 if let Some(name) = get_item_name(cx, expr) {
309 let name = name.as_str();
310 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
311 name.ends_with("_eq") {
315 span_lint_and_then(cx, FLOAT_CMP, expr.span, "strict comparison of f32 or f64", |db| {
316 let lhs = Sugg::hir(cx, left, "..");
317 let rhs = Sugg::hir(cx, right, "..");
319 db.span_suggestion(expr.span,
320 "consider comparing them within some error",
321 format!("({}).abs() < error", lhs - rhs));
322 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
324 } else if op == BiRem && is_integer_literal(right, 1) {
325 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
330 if in_attributes_expansion(expr) {
331 // Don't lint things expanded by #[derive(...)], etc
334 let binding = match expr.node {
335 ExprPath(ref qpath) => {
336 let binding = last_path_segment(qpath).name.as_str();
337 if binding.starts_with('_') &&
338 !binding.starts_with("__") &&
339 binding != "_result" && // FIXME: #944
341 // don't lint if the declaration is in a macro
342 non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.id)) {
348 ExprField(_, spanned) => {
349 let name = spanned.node.as_str();
350 if name.starts_with('_') && !name.starts_with("__") {
358 if let Some(binding) = binding {
360 USED_UNDERSCORE_BINDING,
362 &format!("used binding `{}` which is prefixed with an underscore. A leading \
363 underscore signals that a binding will not be used.",
368 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
369 if let PatKind::Binding(_, _, ref ident, Some(ref right)) = pat.node {
370 if right.node == PatKind::Wild {
374 &format!("the `{} @ _` pattern can be written as just `{}`", ident.node, ident.node));
380 fn check_nan(cx: &LateContext, path: &Path, expr: &Expr) {
381 if !in_constant(cx, expr.id) {
382 path.segments.last().map(|seg| if seg.name == "NAN" {
386 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
391 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
392 let res = ConstContext::with_tables(cx.tcx, cx.tables).eval(expr);
393 if let Ok(ConstVal::Float(val)) = res {
394 use std::cmp::Ordering;
396 val @ ConstFloat::F32(_) => {
397 let zero = ConstFloat::F32(0.0);
399 let infinity = ConstFloat::F32(::std::f32::INFINITY);
401 let neg_infinity = ConstFloat::F32(::std::f32::NEG_INFINITY);
403 val.try_cmp(zero) == Ok(Ordering::Equal) || val.try_cmp(infinity) == Ok(Ordering::Equal) ||
404 val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
406 val @ ConstFloat::F64(_) => {
407 let zero = ConstFloat::F64(0.0);
409 let infinity = ConstFloat::F64(::std::f64::INFINITY);
411 let neg_infinity = ConstFloat::F64(::std::f64::NEG_INFINITY);
413 val.try_cmp(zero) == Ok(Ordering::Equal) || val.try_cmp(infinity) == Ok(Ordering::Equal) ||
414 val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
422 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
423 matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).sty, ty::TyFloat(_))
426 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr) {
427 let (arg_ty, snip) = match expr.node {
428 ExprMethodCall(.., ref args) if args.len() == 1 => {
429 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
430 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
435 ExprCall(ref path, ref v) if v.len() == 1 => {
436 if let ExprPath(ref path) = path.node {
437 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
438 (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
449 let other_ty = cx.tables.expr_ty_adjusted(other);
450 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
455 // *arg impls PartialEq<other>
457 .builtin_deref(true, ty::LvaluePreference::NoPreference)
458 .map_or(false, |tam| implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty]))
459 // arg impls PartialEq<*other>
461 .builtin_deref(true, ty::LvaluePreference::NoPreference)
462 .map_or(false, |tam| implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty]))
463 // arg impls PartialEq<other>
464 && !implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty]) {
468 span_lint_and_then(cx,
471 "this creates an owned instance just for comparison",
473 // this is as good as our recursion check can get, we can't prove that the current function is
475 // PartialEq::eq, but we can at least ensure that this code is not part of it
476 let parent_fn = cx.tcx.hir.get_parent(expr.id);
477 let parent_impl = cx.tcx.hir.get_parent(parent_fn);
478 if parent_impl != CRATE_NODE_ID {
479 if let map::NodeItem(item) = cx.tcx.hir.get(parent_impl) {
480 if let ItemImpl(.., Some(ref trait_ref), _, _) = item.node {
481 if trait_ref.path.def.def_id() == partial_eq_trait_id {
482 // we are implementing PartialEq, don't suggest not doing `to_owned`, otherwise we go into
484 db.span_label(expr.span, "try calling implementing the comparison without allocating");
490 db.span_suggestion(expr.span, "try", snip.to_string());
494 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
495 /// of what it means for an expression to be "used".
496 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
497 if let Some(parent) = get_parent_expr(cx, expr) {
499 ExprAssign(_, ref rhs) |
500 ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
501 _ => is_used(cx, parent),
508 /// Test whether an expression is in a macro expansion (e.g. something generated by
509 /// `#[derive(...)`] or the like).
510 fn in_attributes_expansion(expr: &Expr) -> bool {
511 expr.span.ctxt.outer().expn_info().map_or(false, |info| matches!(info.callee.format, ExpnFormat::MacroAttribute(_)))
514 /// Test whether `def` is a variable defined outside a macro.
515 fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
517 def::Def::Local(id) |
518 def::Def::Upvar(id, _, _) => {
519 if let Some(span) = cx.tcx.hir.span_if_local(id) {
529 fn check_cast(cx: &LateContext, span: Span, e: &Expr, ty: &Ty) {
531 let TyPtr(MutTy { mutbl, .. }) = ty.node,
532 let ExprLit(ref lit) = e.node,
533 let LitKind::Int(value, ..) = lit.node,
535 !in_constant(cx, e.id)
537 let msg = match mutbl {
538 Mutability::MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`",
539 Mutability::MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`",
541 span_lint(cx, ZERO_PTR, span, msg);