3 use rustc::hir::intravisit::FnKind;
5 use rustc::middle::const_val::ConstVal;
7 use rustc_const_eval::EvalHint::ExprTypeChecked;
8 use rustc_const_eval::eval_const_expr_partial;
9 use rustc_const_math::ConstFloat;
10 use syntax::codemap::{Span, Spanned, ExpnFormat};
13 get_item_name, get_parent_expr, implements_trait, in_macro, is_integer_literal, match_path,
14 snippet, span_lint, span_lint_and_then, walk_ptrs_ty
16 use utils::sugg::Sugg;
18 /// **What it does:** This lint checks for function arguments and let bindings denoted as `ref`.
20 /// **Why is this bad?** The `ref` declaration makes the function take an owned value, but turns
21 /// the argument into a reference (which means that the value is destroyed when exiting the
22 /// function). This adds not much value: either take a reference type, or take an owned value and
23 /// create references in the body.
25 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The type of `x` is more
26 /// obvious with the former.
28 /// **Known problems:** If the argument is dereferenced within the function, removing the `ref`
29 /// will lead to errors. This can be fixed by removing the dereferences, e.g. changing `*x` to `x`
30 /// within the function.
34 /// fn foo(ref x: u8) -> bool { .. }
37 pub TOPLEVEL_REF_ARG, Warn,
38 "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
39 or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
43 #[allow(missing_copy_implementations)]
44 pub struct TopLevelRefPass;
46 impl LintPass for TopLevelRefPass {
47 fn get_lints(&self) -> LintArray {
48 lint_array!(TOPLEVEL_REF_ARG)
52 impl LateLintPass for TopLevelRefPass {
53 fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
54 if let FnKind::Closure(_) = k {
55 // Does not apply to closures
58 for ref arg in &decl.inputs {
59 if let PatKind::Binding(BindByRef(_), _, _) = arg.pat.node {
63 "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
67 fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
69 let StmtDecl(ref d, _) = s.node,
70 let DeclLocal(ref l) = d.node,
71 let PatKind::Binding(BindByRef(mt), i, None) = l.pat.node,
72 let Some(ref init) = l.init
74 let init = Sugg::hir(cx, init, "..");
75 let (mutopt,initref) = if mt == Mutability::MutMutable {
76 ("mut ", init.mut_addr())
80 let tyopt = if let Some(ref ty) = l.ty {
81 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
85 span_lint_and_then(cx,
88 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
90 db.span_suggestion(s.span,
92 format!("let {name}{tyopt} = {initref};",
93 name=snippet(cx, i.span, "_"),
102 /// **What it does:** This lint checks for comparisons to NAN.
104 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
106 /// **Known problems:** None
108 /// **Example:** `x == NAN`
109 declare_lint!(pub CMP_NAN, Deny,
110 "comparisons to NAN (which will always return false, which is probably not intended)");
112 #[derive(Copy,Clone)]
115 impl LintPass for CmpNan {
116 fn get_lints(&self) -> LintArray {
121 impl LateLintPass for CmpNan {
122 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
123 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
124 if cmp.node.is_comparison() {
125 if let ExprPath(_, ref path) = left.node {
126 check_nan(cx, path, expr.span);
128 if let ExprPath(_, ref path) = right.node {
129 check_nan(cx, path, expr.span);
136 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
137 path.segments.last().map(|seg| {
138 if seg.name.as_str() == "NAN" {
142 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
147 /// **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).
149 /// **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).
151 /// **Known problems:** None
153 /// **Example:** `y == 1.23f64`
154 declare_lint!(pub FLOAT_CMP, Warn,
155 "using `==` or `!=` on float values (as floating-point operations \
156 usually involve rounding errors, it is always better to check for approximate \
157 equality within small bounds)");
159 #[derive(Copy,Clone)]
162 impl LintPass for FloatCmp {
163 fn get_lints(&self) -> LintArray {
164 lint_array!(FLOAT_CMP)
168 impl LateLintPass for FloatCmp {
169 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
170 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
172 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
173 if is_allowed(cx, left) || is_allowed(cx, right) {
176 if let Some(name) = get_item_name(cx, expr) {
177 let name = name.as_str();
178 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
179 name.ends_with("_eq") {
183 span_lint_and_then(cx,
186 "strict comparison of f32 or f64",
188 let lhs = Sugg::hir(cx, left, "..");
189 let rhs = Sugg::hir(cx, right, "..");
191 db.span_suggestion(expr.span,
192 "consider comparing them within some error",
193 format!("({}).abs() < error", lhs - rhs));
194 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
201 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
202 let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
203 if let Ok(ConstVal::Float(val)) = res {
204 use std::cmp::Ordering;
206 let zero = ConstFloat::FInfer {
211 let infinity = ConstFloat::FInfer {
212 f32: ::std::f32::INFINITY,
213 f64: ::std::f64::INFINITY,
216 let neg_infinity = ConstFloat::FInfer {
217 f32: ::std::f32::NEG_INFINITY,
218 f64: ::std::f64::NEG_INFINITY,
221 val.try_cmp(zero) == Ok(Ordering::Equal)
222 || val.try_cmp(infinity) == Ok(Ordering::Equal)
223 || val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
229 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
230 matches!(walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty, ty::TyFloat(_))
233 /// **What it does:** This lint checks for conversions to owned values just for the sake of a comparison.
235 /// **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.
237 /// **Known problems:** None
239 /// **Example:** `x.to_owned() == y`
240 declare_lint!(pub CMP_OWNED, Warn,
241 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
243 #[derive(Copy,Clone)]
246 impl LintPass for CmpOwned {
247 fn get_lints(&self) -> LintArray {
248 lint_array!(CMP_OWNED)
252 impl LateLintPass for CmpOwned {
253 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
254 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
255 if cmp.node.is_comparison() {
256 check_to_owned(cx, left, right, true, cmp.span);
257 check_to_owned(cx, right, left, false, cmp.span)
263 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
264 let (arg_ty, snip) = match expr.node {
265 ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) if args.len() == 1 => {
266 if name.as_str() == "to_string" || name.as_str() == "to_owned" && is_str_arg(cx, args) {
267 (cx.tcx.expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
272 ExprCall(ref path, ref v) if v.len() == 1 => {
273 if let ExprPath(None, ref path) = path.node {
274 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
275 (cx.tcx.expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
286 let other_ty = cx.tcx.expr_ty(other);
287 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
292 if !implements_trait(cx, arg_ty, partial_eq_trait_id, vec![other_ty]) {
300 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
301 compare without allocation",
303 snippet(cx, op, "=="),
304 snippet(cx, other.span, "..")));
309 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
310 compare without allocation",
311 snippet(cx, other.span, ".."),
312 snippet(cx, op, "=="),
318 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
320 matches!(walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty, ty::TyStr)
323 /// **What it does:** This lint checks for getting the remainder of a division by one.
325 /// **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.
327 /// **Known problems:** None
329 /// **Example:** `x % 1`
330 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
332 #[derive(Copy,Clone)]
333 pub struct ModuloOne;
335 impl LintPass for ModuloOne {
336 fn get_lints(&self) -> LintArray {
337 lint_array!(MODULO_ONE)
341 impl LateLintPass for ModuloOne {
342 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
343 if let ExprBinary(ref cmp, _, ref right) = expr.node {
344 if let Spanned { node: BinOp_::BiRem, .. } = *cmp {
345 if is_integer_literal(right, 1) {
346 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
353 /// **What it does:** This lint checks for patterns in the form `name @ _`.
355 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
357 /// **Known problems:** None
363 /// y @ _ => (), // easier written as `y`,
366 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
368 #[derive(Copy,Clone)]
369 pub struct PatternPass;
371 impl LintPass for PatternPass {
372 fn get_lints(&self) -> LintArray {
373 lint_array!(REDUNDANT_PATTERN)
377 impl LateLintPass for PatternPass {
378 fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
379 if let PatKind::Binding(_, ref ident, Some(ref right)) = pat.node {
380 if right.node == PatKind::Wild {
384 &format!("the `{} @ _` pattern can be written as just `{}`",
393 /// **What it does:** This lint checks for the use of bindings with a single leading underscore
395 /// **Why is this bad?** A single leading underscore is usually used to indicate that a binding
396 /// will not be used. Using such a binding breaks this expectation.
398 /// **Known problems:** The lint does not work properly with desugaring and macro, it has been
399 /// allowed in the mean time.
404 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
405 /// // We should rename `_x` to `x`
407 declare_lint!(pub USED_UNDERSCORE_BINDING, Allow,
408 "using a binding which is prefixed with an underscore");
410 #[derive(Copy, Clone)]
411 pub struct UsedUnderscoreBinding;
413 impl LintPass for UsedUnderscoreBinding {
414 fn get_lints(&self) -> LintArray {
415 lint_array!(USED_UNDERSCORE_BINDING)
419 impl LateLintPass for UsedUnderscoreBinding {
420 #[cfg_attr(rustfmt, rustfmt_skip)]
421 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
422 if in_attributes_expansion(cx, expr) {
423 // Don't lint things expanded by #[derive(...)], etc
426 let binding = match expr.node {
427 ExprPath(_, ref path) => {
428 let binding = path.segments
430 .expect("path should always have at least one segment")
433 if binding.starts_with('_') &&
434 !binding.starts_with("__") &&
435 binding != "_result" && // FIXME: #944
437 // don't lint if the declaration is in a macro
438 non_macro_local(cx, &cx.tcx.expect_def(expr.id)) {
444 ExprField(_, spanned) => {
445 let name = spanned.node.as_str();
446 if name.starts_with('_') && !name.starts_with("__") {
454 if let Some(binding) = binding {
456 USED_UNDERSCORE_BINDING,
458 &format!("used binding `{}` which is prefixed with an underscore. A leading \
459 underscore signals that a binding will not be used.", binding));
464 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
465 /// of what it means for an expression to be "used".
466 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
467 if let Some(ref parent) = get_parent_expr(cx, expr) {
469 ExprAssign(_, ref rhs) |
470 ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
471 _ => is_used(cx, parent),
478 /// Test whether an expression is in a macro expansion (e.g. something generated by
479 /// `#[derive(...)`] or the like).
480 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
481 cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
482 info_opt.map_or(false, |info| {
483 matches!(info.callee.format, ExpnFormat::MacroAttribute(_))
488 /// Test whether `def` is a variable defined outside a macro.
489 fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
491 def::Def::Local(_, id) | def::Def::Upvar(_, id, _, _) => {
492 if let Some(span) = cx.tcx.map.opt_span(id) {