3 use rustc::hir::intravisit::FnKind;
5 use rustc::middle::const_val::ConstVal;
7 use rustc::ty::subst::Substs;
8 use rustc_const_eval::ConstContext;
9 use rustc_const_math::ConstFloat;
10 use syntax::codemap::{Span, ExpnFormat};
11 use utils::{get_item_name, get_parent_expr, implements_trait, in_macro, is_integer_literal, match_path, snippet,
12 span_lint, span_lint_and_then, walk_ptrs_ty, last_path_segment, iter_input_pats, in_constant,
13 match_trait_method, paths};
14 use utils::sugg::Sugg;
15 use syntax::ast::{LitKind, CRATE_NODE_ID, FloatTy};
17 /// **What it does:** Checks for function arguments and let bindings denoted as
20 /// **Why is this bad?** The `ref` declaration makes the function take an owned
21 /// value, but turns the argument into a reference (which means that the value
22 /// is destroyed when exiting the function). This adds not much value: either
23 /// take a reference type, or take an owned value and create references in the
26 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
27 /// type of `x` is more obvious with the former.
29 /// **Known problems:** If the argument is dereferenced within the function,
30 /// removing the `ref` will lead to errors. This can be fixed by removing the
31 /// dereferences, e.g. changing `*x` to `x` within the function.
35 /// fn foo(ref x: u8) -> bool { .. }
40 "an entire binding declared as `ref`, in a function argument or a `let` statement"
43 /// **What it does:** Checks for comparisons to NaN.
45 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
46 /// even itself – so those comparisons are simply wrong.
48 /// **Known problems:** None.
57 "comparisons to NAN, which will always return false, probably not intended"
60 /// **What it does:** Checks for (in-)equality comparisons on floating-point
61 /// values (apart from zero), except in functions called `*eq*` (which probably
62 /// implement equality for a type involving floats).
64 /// **Why is this bad?** Floating point calculations are usually imprecise, so
65 /// asking if two values are *exactly* equal is asking for trouble. For a good
66 /// guide on what to do, see [the floating point
67 /// guide](http://www.floating-point-gui.de/errors/comparison).
69 /// **Known problems:** None.
74 /// y != x // where both are floats
79 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
82 /// **What it does:** Checks for conversions to owned values just for the sake
85 /// **Why is this bad?** The comparison can operate on a reference, so creating
86 /// an owned value effectively throws it away directly afterwards, which is
87 /// needlessly consuming code and heap space.
89 /// **Known problems:** None.
98 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`"
101 /// **What it does:** Checks for getting the remainder of a division by one.
103 /// **Why is this bad?** The result can only ever be zero. No one will write
104 /// such code deliberately, unless trying to win an Underhanded Rust
105 /// Contest. Even for that contest, it's probably a bad idea. Use something more
108 /// **Known problems:** None.
117 "taking a number modulo 1, which always returns 0"
120 /// **What it does:** Checks for patterns in the form `name @ _`.
122 /// **Why is this bad?** It's almost always more readable to just use direct
125 /// **Known problems:** None.
131 /// y @ _ => (), // easier written as `y`,
135 pub REDUNDANT_PATTERN,
137 "using `name @ _` in a pattern"
140 /// **What it does:** Checks for the use of bindings with a single leading
143 /// **Why is this bad?** A single leading underscore is usually used to indicate
144 /// that a binding will not be used. Using such a binding breaks this
147 /// **Known problems:** The lint does not work properly with desugaring and
148 /// macro, it has been allowed in the mean time.
153 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
155 /// // We should rename `_x` to `x`
158 pub USED_UNDERSCORE_BINDING,
160 "using a binding which is prefixed with an underscore"
163 /// **What it does:** Checks for the use of short circuit boolean conditions as
167 /// **Why is this bad?** Using a short circuit boolean condition as a statement
169 /// hide the fact that the second part is executed or not depending on the
173 /// **Known problems:** None.
177 /// f() && g(); // We should write `if f() { g(); }`.
180 pub SHORT_CIRCUIT_STATEMENT,
182 "using a short circuit boolean condition as a statement"
185 /// **What it does:** Catch casts from `0` to some pointer type
187 /// **Why is this bad?** This generally means `null` and is better expressed as
188 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
190 /// **Known problems:** None.
200 "using 0 as *{const, mut} T"
203 #[derive(Copy, Clone)]
206 impl LintPass for Pass {
207 fn get_lints(&self) -> LintArray {
215 USED_UNDERSCORE_BINDING,
216 SHORT_CIRCUIT_STATEMENT,
222 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
225 cx: &LateContext<'a, 'tcx>,
232 if let FnKind::Closure(_) = k {
233 // Does not apply to closures
236 for arg in iter_input_pats(decl, body) {
238 PatKind::Binding(BindingAnnotation::Ref, _, _, _) |
239 PatKind::Binding(BindingAnnotation::RefMut, _, _, _) => {
244 "`ref` directly on a function argument is ignored. Consider using a reference type \
253 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, s: &'tcx Stmt) {
255 let StmtDecl(ref d, _) = s.node,
256 let DeclLocal(ref l) = d.node,
257 let PatKind::Binding(an, _, i, None) = l.pat.node,
258 let Some(ref init) = l.init
260 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
261 let init = Sugg::hir(cx, init, "..");
262 let (mutopt,initref) = if an == BindingAnnotation::RefMut {
263 ("mut ", init.mut_addr())
267 let tyopt = if let Some(ref ty) = l.ty {
268 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
272 span_lint_and_then(cx,
275 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
277 db.span_suggestion(s.span,
279 format!("let {name}{tyopt} = {initref};",
280 name=snippet(cx, i.span, "_"),
288 let StmtSemi(ref expr, _) = s.node,
289 let Expr_::ExprBinary(ref binop, ref a, ref b) = expr.node,
290 binop.node == BiAnd || binop.node == BiOr,
291 let Some(sugg) = Sugg::hir_opt(cx, a),
293 span_lint_and_then(cx,
294 SHORT_CIRCUIT_STATEMENT,
296 "boolean short circuit operator in statement may be clearer using an explicit test",
298 let sugg = if binop.node == BiOr { !sugg } else { sugg };
299 db.span_suggestion(s.span, "replace it with",
300 format!("if {} {{ {}; }}", sugg, &snippet(cx, b.span, "..")));
305 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
307 ExprCast(ref e, ref ty) => {
308 check_cast(cx, expr.span, e, ty);
311 ExprBinary(ref cmp, ref left, ref right) => {
313 if op.is_comparison() {
314 if let ExprPath(QPath::Resolved(_, ref path)) = left.node {
315 check_nan(cx, path, expr);
317 if let ExprPath(QPath::Resolved(_, ref path)) = right.node {
318 check_nan(cx, path, expr);
320 check_to_owned(cx, left, right);
321 check_to_owned(cx, right, left);
323 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
324 if is_allowed(cx, left) || is_allowed(cx, right) {
327 if let Some(name) = get_item_name(cx, expr) {
328 let name = name.as_str();
329 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
330 name.ends_with("_eq")
335 span_lint_and_then(cx, FLOAT_CMP, expr.span, "strict comparison of f32 or f64", |db| {
336 let lhs = Sugg::hir(cx, left, "..");
337 let rhs = Sugg::hir(cx, right, "..");
341 "consider comparing them within some error",
342 format!("({}).abs() < error", lhs - rhs),
344 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
346 } else if op == BiRem && is_integer_literal(right, 1) {
347 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
352 if in_attributes_expansion(expr) {
353 // Don't lint things expanded by #[derive(...)], etc
356 let binding = match expr.node {
357 ExprPath(ref qpath) => {
358 let binding = last_path_segment(qpath).name.as_str();
359 if binding.starts_with('_') &&
360 !binding.starts_with("__") &&
361 binding != "_result" && // FIXME: #944
363 // don't lint if the declaration is in a macro
364 non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.hir_id))
371 ExprField(_, spanned) => {
372 let name = spanned.node.as_str();
373 if name.starts_with('_') && !name.starts_with("__") {
381 if let Some(binding) = binding {
384 USED_UNDERSCORE_BINDING,
387 "used binding `{}` which is prefixed with an underscore. A leading \
388 underscore signals that a binding will not be used.",
395 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
396 if let PatKind::Binding(_, _, ref ident, Some(ref right)) = pat.node {
397 if right.node == PatKind::Wild {
402 &format!("the `{} @ _` pattern can be written as just `{}`", ident.node, ident.node),
409 fn check_nan(cx: &LateContext, path: &Path, expr: &Expr) {
410 if !in_constant(cx, expr.id) {
411 path.segments.last().map(|seg| if seg.name == "NAN" {
416 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
422 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
423 let parent_item = cx.tcx.hir.get_parent(expr.id);
424 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
425 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
426 let res = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr);
427 if let Ok(ConstVal::Float(val)) = res {
428 use std::cmp::Ordering;
431 let zero = ConstFloat {
433 bits: 0.0_f32.to_bits() as u128,
436 let infinity = ConstFloat {
438 bits: ::std::f32::INFINITY.to_bits() as u128,
441 let neg_infinity = ConstFloat {
443 bits: ::std::f32::NEG_INFINITY.to_bits() as u128,
446 val.try_cmp(zero) == Ok(Ordering::Equal) || val.try_cmp(infinity) == Ok(Ordering::Equal) ||
447 val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
450 let zero = ConstFloat {
452 bits: 0.0_f64.to_bits() as u128,
455 let infinity = ConstFloat {
457 bits: ::std::f64::INFINITY.to_bits() as u128,
460 let neg_infinity = ConstFloat {
462 bits: ::std::f64::NEG_INFINITY.to_bits() as u128,
465 val.try_cmp(zero) == Ok(Ordering::Equal) || val.try_cmp(infinity) == Ok(Ordering::Equal) ||
466 val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
474 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
475 matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).sty, ty::TyFloat(_))
478 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr) {
479 let (arg_ty, snip) = match expr.node {
480 ExprMethodCall(.., ref args) if args.len() == 1 => {
481 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
482 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
487 ExprCall(ref path, ref v) if v.len() == 1 => {
488 if let ExprPath(ref path) = path.node {
489 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
490 (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
501 let other_ty = cx.tables.expr_ty_adjusted(other);
502 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
507 // *arg impls PartialEq<other>
509 .builtin_deref(true, ty::LvaluePreference::NoPreference)
510 .map_or(false, |tam| implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty]))
511 // arg impls PartialEq<*other>
513 .builtin_deref(true, ty::LvaluePreference::NoPreference)
514 .map_or(false, |tam| implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty]))
515 // arg impls PartialEq<other>
516 && !implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty])
525 "this creates an owned instance just for comparison",
527 // this is as good as our recursion check can get, we can't prove that the
528 // current function is
530 // PartialEq::eq, but we can at least ensure that this code is not part of it
531 let parent_fn = cx.tcx.hir.get_parent(expr.id);
532 let parent_impl = cx.tcx.hir.get_parent(parent_fn);
533 if parent_impl != CRATE_NODE_ID {
534 if let map::NodeItem(item) = cx.tcx.hir.get(parent_impl) {
535 if let ItemImpl(.., Some(ref trait_ref), _, _) = item.node {
536 if trait_ref.path.def.def_id() == partial_eq_trait_id {
537 // we are implementing PartialEq, don't suggest not doing `to_owned`, otherwise
540 db.span_label(expr.span, "try calling implementing the comparison without allocating");
546 db.span_suggestion(expr.span, "try", snip.to_string());
551 /// Heuristic to see if an expression is used. Should be compatible with
552 /// `unused_variables`'s idea
553 /// of what it means for an expression to be "used".
554 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
555 if let Some(parent) = get_parent_expr(cx, expr) {
557 ExprAssign(_, ref rhs) |
558 ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
559 _ => is_used(cx, parent),
566 /// Test whether an expression is in a macro expansion (e.g. something
568 /// `#[derive(...)`] or the like).
569 fn in_attributes_expansion(expr: &Expr) -> bool {
570 expr.span.ctxt.outer().expn_info().map_or(
572 |info| matches!(info.callee.format, ExpnFormat::MacroAttribute(_)),
576 /// Test whether `def` is a variable defined outside a macro.
577 fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
579 def::Def::Local(def_id) |
580 def::Def::Upvar(def_id, _, _) => {
581 let id = cx.tcx.hir.as_local_node_id(def_id).expect(
582 "local variables should be found in the same crate",
584 !in_macro(cx.tcx.hir.span(id))
590 fn check_cast(cx: &LateContext, span: Span, e: &Expr, ty: &Ty) {
592 let TyPtr(MutTy { mutbl, .. }) = ty.node,
593 let ExprLit(ref lit) = e.node,
594 let LitKind::Int(value, ..) = lit.node,
596 !in_constant(cx, e.id)
598 let msg = match mutbl {
599 Mutability::MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`",
600 Mutability::MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`",
602 span_lint(cx, ZERO_PTR, span, msg);