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};
17 /// **What it does:** Checks for function arguments and let bindings denoted as `ref`.
19 /// **Why is this bad?** The `ref` declaration makes the function take an owned
20 /// value, but turns the argument into a reference (which means that the value
21 /// is destroyed when exiting the function). This adds not much value: either
22 /// take a reference type, or take an owned value and create references in the
25 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
26 /// type of `x` is more obvious with the former.
28 /// **Known problems:** If the argument is dereferenced within the function,
29 /// removing the `ref` will lead to errors. This can be fixed by removing the
30 /// dereferences, e.g. changing `*x` to `x` within the function.
34 /// fn foo(ref x: u8) -> bool { .. }
39 "an entire binding declared as `ref`, in a function argument or a `let` statement"
42 /// **What it does:** Checks for comparisons to NaN.
44 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
45 /// even itself – so those comparisons are simply wrong.
47 /// **Known problems:** None.
56 "comparisons to NAN, which will always return false, probably not intended"
59 /// **What it does:** Checks for (in-)equality comparisons on floating-point
60 /// values (apart from zero), except in functions called `*eq*` (which probably
61 /// implement equality for a type involving floats).
63 /// **Why is this bad?** Floating point calculations are usually imprecise, so
64 /// asking if two values are *exactly* equal is asking for trouble. For a good
65 /// guide on what to do, see [the floating point
66 /// guide](http://www.floating-point-gui.de/errors/comparison).
68 /// **Known problems:** None.
73 /// y != x // where both are floats
78 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
81 /// **What it does:** Checks for conversions to owned values just for the sake
84 /// **Why is this bad?** The comparison can operate on a reference, so creating
85 /// an owned value effectively throws it away directly afterwards, which is
86 /// needlessly consuming code and heap space.
88 /// **Known problems:** None.
97 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`"
100 /// **What it does:** Checks for getting the remainder of a division by one.
102 /// **Why is this bad?** The result can only ever be zero. No one will write
103 /// such code deliberately, unless trying to win an Underhanded Rust
104 /// Contest. Even for that contest, it's probably a bad idea. Use something more
107 /// **Known problems:** None.
116 "taking a number modulo 1, which always returns 0"
119 /// **What it does:** Checks for patterns in the form `name @ _`.
121 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
123 /// **Known problems:** None.
129 /// y @ _ => (), // easier written as `y`,
133 pub REDUNDANT_PATTERN,
135 "using `name @ _` in a pattern"
138 /// **What it does:** Checks for the use of bindings with a single leading underscore.
140 /// **Why is this bad?** A single leading underscore is usually used to indicate
141 /// that a binding will not be used. Using such a binding breaks this
144 /// **Known problems:** The lint does not work properly with desugaring and
145 /// macro, it has been allowed in the mean time.
150 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
151 /// // We should rename `_x` to `x`
154 pub USED_UNDERSCORE_BINDING,
156 "using a binding which is prefixed with an underscore"
159 /// **What it does:** Checks for the use of short circuit boolean conditions as a
162 /// **Why is this bad?** Using a short circuit boolean condition as a statement may
163 /// hide the fact that the second part is executed or not depending on the outcome of
166 /// **Known problems:** None.
170 /// f() && g(); // We should write `if f() { g(); }`.
173 pub SHORT_CIRCUIT_STATEMENT,
175 "using a short circuit boolean condition as a statement"
178 /// **What it does:** Catch casts from `0` to some pointer type
180 /// **Why is this bad?** This generally means `null` and is better expressed as
181 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
183 /// **Known problems:** None.
193 "using 0 as *{const, mut} T"
196 #[derive(Copy, Clone)]
199 impl LintPass for Pass {
200 fn get_lints(&self) -> LintArray {
201 lint_array!(TOPLEVEL_REF_ARG,
207 USED_UNDERSCORE_BINDING,
208 SHORT_CIRCUIT_STATEMENT,
213 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
216 cx: &LateContext<'a, 'tcx>,
223 if let FnKind::Closure(_) = k {
224 // Does not apply to closures
227 for arg in iter_input_pats(decl, body) {
229 PatKind::Binding(BindingAnnotation::Ref, _, _, _) |
230 PatKind::Binding(BindingAnnotation::RefMut, _, _, _) => {
234 "`ref` directly on a function argument is ignored. Consider using a reference type \
242 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, s: &'tcx Stmt) {
244 let StmtDecl(ref d, _) = s.node,
245 let DeclLocal(ref l) = d.node,
246 let PatKind::Binding(an, _, i, None) = l.pat.node,
247 let Some(ref init) = l.init
249 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
250 let init = Sugg::hir(cx, init, "..");
251 let (mutopt,initref) = if an == BindingAnnotation::RefMut {
252 ("mut ", init.mut_addr())
256 let tyopt = if let Some(ref ty) = l.ty {
257 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
261 span_lint_and_then(cx,
264 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
266 db.span_suggestion(s.span,
268 format!("let {name}{tyopt} = {initref};",
269 name=snippet(cx, i.span, "_"),
277 let StmtSemi(ref expr, _) = s.node,
278 let Expr_::ExprBinary(ref binop, ref a, ref b) = expr.node,
279 binop.node == BiAnd || binop.node == BiOr,
280 let Some(sugg) = Sugg::hir_opt(cx, a),
282 span_lint_and_then(cx,
283 SHORT_CIRCUIT_STATEMENT,
285 "boolean short circuit operator in statement may be clearer using an explicit test",
287 let sugg = if binop.node == BiOr { !sugg } else { sugg };
288 db.span_suggestion(s.span, "replace it with",
289 format!("if {} {{ {}; }}", sugg, &snippet(cx, b.span, "..")));
294 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
296 ExprCast(ref e, ref ty) => {
297 check_cast(cx, expr.span, e, ty);
300 ExprBinary(ref cmp, ref left, ref right) => {
302 if op.is_comparison() {
303 if let ExprPath(QPath::Resolved(_, ref path)) = left.node {
304 check_nan(cx, path, expr);
306 if let ExprPath(QPath::Resolved(_, ref path)) = right.node {
307 check_nan(cx, path, expr);
309 check_to_owned(cx, left, right);
310 check_to_owned(cx, right, left);
312 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
313 if is_allowed(cx, left) || is_allowed(cx, right) {
316 if let Some(name) = get_item_name(cx, expr) {
317 let name = name.as_str();
318 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
319 name.ends_with("_eq") {
323 span_lint_and_then(cx, FLOAT_CMP, expr.span, "strict comparison of f32 or f64", |db| {
324 let lhs = Sugg::hir(cx, left, "..");
325 let rhs = Sugg::hir(cx, right, "..");
327 db.span_suggestion(expr.span,
328 "consider comparing them within some error",
329 format!("({}).abs() < error", lhs - rhs));
330 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
332 } else if op == BiRem && is_integer_literal(right, 1) {
333 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
338 if in_attributes_expansion(expr) {
339 // Don't lint things expanded by #[derive(...)], etc
342 let binding = match expr.node {
343 ExprPath(ref qpath) => {
344 let binding = last_path_segment(qpath).name.as_str();
345 if binding.starts_with('_') &&
346 !binding.starts_with("__") &&
347 binding != "_result" && // FIXME: #944
349 // don't lint if the declaration is in a macro
350 non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.id)) {
356 ExprField(_, spanned) => {
357 let name = spanned.node.as_str();
358 if name.starts_with('_') && !name.starts_with("__") {
366 if let Some(binding) = binding {
368 USED_UNDERSCORE_BINDING,
370 &format!("used binding `{}` which is prefixed with an underscore. A leading \
371 underscore signals that a binding will not be used.",
376 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
377 if let PatKind::Binding(_, _, ref ident, Some(ref right)) = pat.node {
378 if right.node == PatKind::Wild {
382 &format!("the `{} @ _` pattern can be written as just `{}`", ident.node, ident.node));
388 fn check_nan(cx: &LateContext, path: &Path, expr: &Expr) {
389 if !in_constant(cx, expr.id) {
390 path.segments.last().map(|seg| if seg.name == "NAN" {
394 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
399 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
400 let parent_item = cx.tcx.hir.get_parent(expr.id);
401 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
402 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
403 let res = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr);
404 if let Ok(ConstVal::Float(val)) = res {
405 use std::cmp::Ordering;
407 val @ ConstFloat::F32(_) => {
408 let zero = ConstFloat::F32(0.0);
410 let infinity = ConstFloat::F32(::std::f32::INFINITY);
412 let neg_infinity = ConstFloat::F32(::std::f32::NEG_INFINITY);
414 val.try_cmp(zero) == Ok(Ordering::Equal) || val.try_cmp(infinity) == Ok(Ordering::Equal) ||
415 val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
417 val @ ConstFloat::F64(_) => {
418 let zero = ConstFloat::F64(0.0);
420 let infinity = ConstFloat::F64(::std::f64::INFINITY);
422 let neg_infinity = ConstFloat::F64(::std::f64::NEG_INFINITY);
424 val.try_cmp(zero) == Ok(Ordering::Equal) || val.try_cmp(infinity) == Ok(Ordering::Equal) ||
425 val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
433 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
434 matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).sty, ty::TyFloat(_))
437 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr) {
438 let (arg_ty, snip) = match expr.node {
439 ExprMethodCall(.., ref args) if args.len() == 1 => {
440 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
441 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
446 ExprCall(ref path, ref v) if v.len() == 1 => {
447 if let ExprPath(ref path) = path.node {
448 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
449 (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
460 let other_ty = cx.tables.expr_ty_adjusted(other);
461 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
466 // *arg impls PartialEq<other>
468 .builtin_deref(true, ty::LvaluePreference::NoPreference)
469 .map_or(false, |tam| implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty]))
470 // arg impls PartialEq<*other>
472 .builtin_deref(true, ty::LvaluePreference::NoPreference)
473 .map_or(false, |tam| implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty]))
474 // arg impls PartialEq<other>
475 && !implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty]) {
479 span_lint_and_then(cx,
482 "this creates an owned instance just for comparison",
484 // this is as good as our recursion check can get, we can't prove that the current function is
486 // PartialEq::eq, but we can at least ensure that this code is not part of it
487 let parent_fn = cx.tcx.hir.get_parent(expr.id);
488 let parent_impl = cx.tcx.hir.get_parent(parent_fn);
489 if parent_impl != CRATE_NODE_ID {
490 if let map::NodeItem(item) = cx.tcx.hir.get(parent_impl) {
491 if let ItemImpl(.., Some(ref trait_ref), _, _) = item.node {
492 if trait_ref.path.def.def_id() == partial_eq_trait_id {
493 // we are implementing PartialEq, don't suggest not doing `to_owned`, otherwise we go into
495 db.span_label(expr.span, "try calling implementing the comparison without allocating");
501 db.span_suggestion(expr.span, "try", snip.to_string());
505 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
506 /// of what it means for an expression to be "used".
507 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
508 if let Some(parent) = get_parent_expr(cx, expr) {
510 ExprAssign(_, ref rhs) |
511 ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
512 _ => is_used(cx, parent),
519 /// Test whether an expression is in a macro expansion (e.g. something generated by
520 /// `#[derive(...)`] or the like).
521 fn in_attributes_expansion(expr: &Expr) -> bool {
522 expr.span.ctxt.outer().expn_info().map_or(false, |info| matches!(info.callee.format, ExpnFormat::MacroAttribute(_)))
525 /// Test whether `def` is a variable defined outside a macro.
526 fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
528 def::Def::Local(def_id) |
529 def::Def::Upvar(def_id, _, _) => {
532 .as_local_node_id(def_id)
533 .expect("local variables should be found in the same crate");
534 !in_macro(cx.tcx.hir.span(id))
540 fn check_cast(cx: &LateContext, span: Span, e: &Expr, ty: &Ty) {
542 let TyPtr(MutTy { mutbl, .. }) = ty.node,
543 let ExprLit(ref lit) = e.node,
544 let LitKind::Int(value, ..) = lit.node,
546 !in_constant(cx, e.id)
548 let msg = match mutbl {
549 Mutability::MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`",
550 Mutability::MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`",
552 span_lint(cx, ZERO_PTR, span, msg);