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, Spanned, 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 use utils::sugg::Sugg;
13 use syntax::ast::LitKind;
15 /// **What it does:** Checks for function arguments and let bindings denoted as `ref`.
17 /// **Why is this bad?** The `ref` declaration makes the function take an owned
18 /// value, but turns the argument into a reference (which means that the value
19 /// is destroyed when exiting the function). This adds not much value: either
20 /// take a reference type, or take an owned value and create references in the
23 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
24 /// type of `x` is more obvious with the former.
26 /// **Known problems:** If the argument is dereferenced within the function,
27 /// removing the `ref` will lead to errors. This can be fixed by removing the
28 /// dereferences, e.g. changing `*x` to `x` within the function.
32 /// fn foo(ref x: u8) -> bool { .. }
37 "an entire binding declared as `ref`, in a function argument or a `let` statement"
40 /// **What it does:** Checks for comparisons to NaN.
42 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
43 /// even itself – so those comparisons are simply wrong.
45 /// **Known problems:** None.
54 "comparisons to NAN, which will always return false, probably not intended"
57 /// **What it does:** Checks for (in-)equality comparisons on floating-point
58 /// values (apart from zero), except in functions called `*eq*` (which probably
59 /// implement equality for a type involving floats).
61 /// **Why is this bad?** Floating point calculations are usually imprecise, so
62 /// asking if two values are *exactly* equal is asking for trouble. For a good
63 /// guide on what to do, see [the floating point
64 /// guide](http://www.floating-point-gui.de/errors/comparison).
66 /// **Known problems:** None.
71 /// y != x // where both are floats
76 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
79 /// **What it does:** Checks for conversions to owned values just for the sake
82 /// **Why is this bad?** The comparison can operate on a reference, so creating
83 /// an owned value effectively throws it away directly afterwards, which is
84 /// needlessly consuming code and heap space.
86 /// **Known problems:** None.
95 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`"
98 /// **What it does:** Checks for getting the remainder of a division by one.
100 /// **Why is this bad?** The result can only ever be zero. No one will write
101 /// such code deliberately, unless trying to win an Underhanded Rust
102 /// Contest. Even for that contest, it's probably a bad idea. Use something more
105 /// **Known problems:** None.
114 "taking a number modulo 1, which always returns 0"
117 /// **What it does:** Checks for patterns in the form `name @ _`.
119 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
121 /// **Known problems:** None.
127 /// y @ _ => (), // easier written as `y`,
131 pub REDUNDANT_PATTERN,
133 "using `name @ _` in a pattern"
136 /// **What it does:** Checks for the use of bindings with a single leading underscore.
138 /// **Why is this bad?** A single leading underscore is usually used to indicate
139 /// that a binding will not be used. Using such a binding breaks this
142 /// **Known problems:** The lint does not work properly with desugaring and
143 /// macro, it has been allowed in the mean time.
148 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
149 /// // We should rename `_x` to `x`
152 pub USED_UNDERSCORE_BINDING,
154 "using a binding which is prefixed with an underscore"
157 /// **What it does:** Checks for the use of short circuit boolean conditions as a
160 /// **Why is this bad?** Using a short circuit boolean condition as a statement may
161 /// hide the fact that the second part is executed or not depending on the outcome of
164 /// **Known problems:** None.
168 /// f() && g(); // We should write `if f() { g(); }`.
171 pub SHORT_CIRCUIT_STATEMENT,
173 "using a short circuit boolean condition as a statement"
176 /// **What it does:** Catch casts from `0` to some pointer type
178 /// **Why is this bad?** This generally means `null` and is better expressed as
179 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
181 /// **Known problems:** None.
191 "using 0 as *{const, mut} T"
194 #[derive(Copy, Clone)]
197 impl LintPass for Pass {
198 fn get_lints(&self) -> LintArray {
199 lint_array!(TOPLEVEL_REF_ARG,
205 USED_UNDERSCORE_BINDING,
206 SHORT_CIRCUIT_STATEMENT,
211 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
214 cx: &LateContext<'a, 'tcx>,
221 if let FnKind::Closure(_) = k {
222 // Does not apply to closures
225 for arg in iter_input_pats(decl, body) {
226 if let PatKind::Binding(BindByRef(_), _, _, _) = arg.pat.node {
230 "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
235 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, s: &'tcx Stmt) {
237 let StmtDecl(ref d, _) = s.node,
238 let DeclLocal(ref l) = d.node,
239 let PatKind::Binding(BindByRef(mt), _, i, None) = l.pat.node,
240 let Some(ref init) = l.init
242 let init = Sugg::hir(cx, init, "..");
243 let (mutopt,initref) = if mt == Mutability::MutMutable {
244 ("mut ", init.mut_addr())
248 let tyopt = if let Some(ref ty) = l.ty {
249 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
253 span_lint_and_then(cx,
256 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
258 db.span_suggestion(s.span,
260 format!("let {name}{tyopt} = {initref};",
261 name=snippet(cx, i.span, "_"),
268 let StmtSemi(ref expr, _) = s.node,
269 let Expr_::ExprBinary(ref binop, ref a, ref b) = expr.node,
270 binop.node == BiAnd || binop.node == BiOr,
271 let Some(sugg) = Sugg::hir_opt(cx, a),
273 span_lint_and_then(cx,
274 SHORT_CIRCUIT_STATEMENT,
276 "boolean short circuit operator in statement may be clearer using an explicit test",
278 let sugg = if binop.node == BiOr { !sugg } else { sugg };
279 db.span_suggestion(s.span, "replace it with",
280 format!("if {} {{ {}; }}", sugg, &snippet(cx, b.span, "..")));
285 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
287 ExprCast(ref e, ref ty) => {
288 check_cast(cx, expr.span, e, ty);
291 ExprBinary(ref cmp, ref left, ref right) => {
293 if op.is_comparison() {
294 if let ExprPath(QPath::Resolved(_, ref path)) = left.node {
295 check_nan(cx, path, expr);
297 if let ExprPath(QPath::Resolved(_, ref path)) = right.node {
298 check_nan(cx, path, expr);
300 check_to_owned(cx, left, right, true, cmp.span);
301 check_to_owned(cx, right, left, false, cmp.span)
303 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
304 if is_allowed(cx, left) || is_allowed(cx, right) {
307 if let Some(name) = get_item_name(cx, expr) {
308 let name = name.as_str();
309 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
310 name.ends_with("_eq") {
314 span_lint_and_then(cx, FLOAT_CMP, expr.span, "strict comparison of f32 or f64", |db| {
315 let lhs = Sugg::hir(cx, left, "..");
316 let rhs = Sugg::hir(cx, right, "..");
318 db.span_suggestion(expr.span,
319 "consider comparing them within some error",
320 format!("({}).abs() < error", lhs - rhs));
321 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
323 } else if op == BiRem && is_integer_literal(right, 1) {
324 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
329 if in_attributes_expansion(cx, expr) {
330 // Don't lint things expanded by #[derive(...)], etc
333 let binding = match expr.node {
334 ExprPath(ref qpath) => {
335 let binding = last_path_segment(qpath).name.as_str();
336 if binding.starts_with('_') &&
337 !binding.starts_with("__") &&
338 binding != "_result" && // FIXME: #944
340 // don't lint if the declaration is in a macro
341 non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.id)) {
347 ExprField(_, spanned) => {
348 let name = spanned.node.as_str();
349 if name.starts_with('_') && !name.starts_with("__") {
357 if let Some(binding) = binding {
359 USED_UNDERSCORE_BINDING,
361 &format!("used binding `{}` which is prefixed with an underscore. A leading \
362 underscore signals that a binding will not be used.",
367 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
368 if let PatKind::Binding(_, _, ref ident, Some(ref right)) = pat.node {
369 if right.node == PatKind::Wild {
373 &format!("the `{} @ _` pattern can be written as just `{}`", ident.node, ident.node));
379 fn check_nan(cx: &LateContext, path: &Path, expr: &Expr) {
380 if !in_constant(cx, expr.id) {
381 path.segments.last().map(|seg| if seg.name == "NAN" {
385 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
390 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
391 let res = ConstContext::with_tables(cx.tcx, cx.tables).eval(expr);
392 if let Ok(ConstVal::Float(val)) = res {
393 use std::cmp::Ordering;
395 val @ ConstFloat::F32(_) => {
396 let zero = ConstFloat::F32(0.0);
398 let infinity = ConstFloat::F32(::std::f32::INFINITY);
400 let neg_infinity = ConstFloat::F32(::std::f32::NEG_INFINITY);
402 val.try_cmp(zero) == Ok(Ordering::Equal) || val.try_cmp(infinity) == Ok(Ordering::Equal) ||
403 val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
405 val @ ConstFloat::F64(_) => {
406 let zero = ConstFloat::F64(0.0);
408 let infinity = ConstFloat::F64(::std::f64::INFINITY);
410 let neg_infinity = ConstFloat::F64(::std::f64::NEG_INFINITY);
412 val.try_cmp(zero) == Ok(Ordering::Equal) || val.try_cmp(infinity) == Ok(Ordering::Equal) ||
413 val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
421 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
422 matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).sty, ty::TyFloat(_))
425 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
426 let (arg_ty, snip) = match expr.node {
427 ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) if args.len() == 1 => {
428 let name = name.as_str();
429 if name == "to_string" || name == "to_owned" && is_str_arg(cx, args) {
430 (cx.tables.expr_ty(&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(&v[0]), snippet(cx, v[0].span, ".."))
449 let other_ty = cx.tables.expr_ty(other);
450 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
455 if !implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty], None) {
463 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
464 compare without allocation",
466 snippet(cx, op, "=="),
467 snippet(cx, other.span, "..")));
472 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
473 compare without allocation",
474 snippet(cx, other.span, ".."),
475 snippet(cx, op, "=="),
481 fn is_str_arg(cx: &LateContext, args: &[Expr]) -> bool {
482 args.len() == 1 && matches!(walk_ptrs_ty(cx.tables.expr_ty(&args[0])).sty, ty::TyStr)
485 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
486 /// of what it means for an expression to be "used".
487 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
488 if let Some(parent) = get_parent_expr(cx, expr) {
490 ExprAssign(_, ref rhs) |
491 ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
492 _ => is_used(cx, parent),
499 /// Test whether an expression is in a macro expansion (e.g. something generated by
500 /// `#[derive(...)`] or the like).
501 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
502 expr.span.ctxt.outer().expn_info().map(|info| {
503 matches!(info.callee.format, ExpnFormat::MacroAttribute(_))
507 /// Test whether `def` is a variable defined outside a macro.
508 fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
510 def::Def::Local(id) |
511 def::Def::Upvar(id, _, _) => {
512 if let Some(span) = cx.tcx.hir.span_if_local(id) {
522 fn check_cast(cx: &LateContext, span: Span, e: &Expr, ty: &Ty) {
524 let TyPtr(MutTy { mutbl, .. }) = ty.node,
525 let ExprLit(ref lit) = e.node,
526 let LitKind::Int(value, ..) = lit.node,
528 !in_constant(cx, e.id)
530 let msg = match mutbl {
531 Mutability::MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`",
532 Mutability::MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`",
534 span_lint(cx, ZERO_PTR, span, msg);