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 the argument into a reference (which means that the value is destroyed when exiting the function). This adds not much value: either take a reference type, or take an owned value and create references in the body.
22 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The type of `x` is more obvious with the former.
24 /// **Known problems:** If the argument is dereferenced within the function, removing the `ref` will lead to errors. This can be fixed by removing the dereferences, e.g. changing `*x` to `x` within the function.
26 /// **Example:** `fn foo(ref x: u8) -> bool { .. }`
28 pub TOPLEVEL_REF_ARG, Warn,
29 "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
30 or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
34 #[allow(missing_copy_implementations)]
35 pub struct TopLevelRefPass;
37 impl LintPass for TopLevelRefPass {
38 fn get_lints(&self) -> LintArray {
39 lint_array!(TOPLEVEL_REF_ARG)
43 impl LateLintPass for TopLevelRefPass {
44 fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
45 if let FnKind::Closure(_) = k {
46 // Does not apply to closures
49 for ref arg in &decl.inputs {
50 if let PatKind::Binding(BindByRef(_), _, _) = arg.pat.node {
54 "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
58 fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
60 let StmtDecl(ref d, _) = s.node,
61 let DeclLocal(ref l) = d.node,
62 let PatKind::Binding(BindByRef(mt), i, None) = l.pat.node,
63 let Some(ref init) = l.init
65 let init = Sugg::hir(cx, init, "..");
66 let (mutopt,initref) = if mt == Mutability::MutMutable {
67 ("mut ", init.mut_addr())
71 let tyopt = if let Some(ref ty) = l.ty {
72 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
76 span_lint_and_then(cx,
79 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
81 db.span_suggestion(s.span,
83 format!("let {name}{tyopt} = {initref};",
84 name=snippet(cx, i.span, "_"),
93 /// **What it does:** This lint checks for comparisons to NAN.
95 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
97 /// **Known problems:** None
99 /// **Example:** `x == NAN`
100 declare_lint!(pub CMP_NAN, Deny,
101 "comparisons to NAN (which will always return false, which is probably not intended)");
103 #[derive(Copy,Clone)]
106 impl LintPass for CmpNan {
107 fn get_lints(&self) -> LintArray {
112 impl LateLintPass for CmpNan {
113 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
114 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
115 if cmp.node.is_comparison() {
116 if let ExprPath(_, ref path) = left.node {
117 check_nan(cx, path, expr.span);
119 if let ExprPath(_, ref path) = right.node {
120 check_nan(cx, path, expr.span);
127 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
128 path.segments.last().map(|seg| {
129 if seg.name.as_str() == "NAN" {
133 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
138 /// **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).
140 /// **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).
142 /// **Known problems:** None
144 /// **Example:** `y == 1.23f64`
145 declare_lint!(pub FLOAT_CMP, Warn,
146 "using `==` or `!=` on float values (as floating-point operations \
147 usually involve rounding errors, it is always better to check for approximate \
148 equality within small bounds)");
150 #[derive(Copy,Clone)]
153 impl LintPass for FloatCmp {
154 fn get_lints(&self) -> LintArray {
155 lint_array!(FLOAT_CMP)
159 impl LateLintPass for FloatCmp {
160 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
161 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
163 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
164 if is_allowed(cx, left) || is_allowed(cx, right) {
167 if let Some(name) = get_item_name(cx, expr) {
168 let name = name.as_str();
169 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
170 name.ends_with("_eq") {
174 span_lint_and_then(cx,
177 "strict comparison of f32 or f64",
179 let lhs = Sugg::hir(cx, left, "..");
180 let rhs = Sugg::hir(cx, right, "..");
182 db.span_suggestion(expr.span,
183 "consider comparing them within some error",
184 format!("({}).abs() < error", lhs - rhs));
185 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
192 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
193 let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
194 if let Ok(ConstVal::Float(val)) = res {
195 use std::cmp::Ordering;
197 let zero = ConstFloat::FInfer {
202 let infinity = ConstFloat::FInfer {
203 f32: ::std::f32::INFINITY,
204 f64: ::std::f64::INFINITY,
207 let neg_infinity = ConstFloat::FInfer {
208 f32: ::std::f32::NEG_INFINITY,
209 f64: ::std::f64::NEG_INFINITY,
212 val.try_cmp(zero) == Ok(Ordering::Equal)
213 || val.try_cmp(infinity) == Ok(Ordering::Equal)
214 || val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
220 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
221 matches!(walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty, ty::TyFloat(_))
224 /// **What it does:** This lint checks for conversions to owned values just for the sake of a comparison.
226 /// **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.
228 /// **Known problems:** None
230 /// **Example:** `x.to_owned() == y`
231 declare_lint!(pub CMP_OWNED, Warn,
232 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
234 #[derive(Copy,Clone)]
237 impl LintPass for CmpOwned {
238 fn get_lints(&self) -> LintArray {
239 lint_array!(CMP_OWNED)
243 impl LateLintPass for CmpOwned {
244 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
245 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
246 if cmp.node.is_comparison() {
247 check_to_owned(cx, left, right, true, cmp.span);
248 check_to_owned(cx, right, left, false, cmp.span)
254 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
255 let (arg_ty, snip) = match expr.node {
256 ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) if args.len() == 1 => {
257 if name.as_str() == "to_string" || name.as_str() == "to_owned" && is_str_arg(cx, args) {
258 (cx.tcx.expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
263 ExprCall(ref path, ref v) if v.len() == 1 => {
264 if let ExprPath(None, ref path) = path.node {
265 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
266 (cx.tcx.expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
277 let other_ty = cx.tcx.expr_ty(other);
278 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
283 if !implements_trait(cx, arg_ty, partial_eq_trait_id, vec![other_ty]) {
291 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
292 compare without allocation",
294 snippet(cx, op, "=="),
295 snippet(cx, other.span, "..")));
300 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
301 compare without allocation",
302 snippet(cx, other.span, ".."),
303 snippet(cx, op, "=="),
309 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
311 matches!(walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty, ty::TyStr)
314 /// **What it does:** This lint checks for getting the remainder of a division by one.
316 /// **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.
318 /// **Known problems:** None
320 /// **Example:** `x % 1`
321 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
323 #[derive(Copy,Clone)]
324 pub struct ModuloOne;
326 impl LintPass for ModuloOne {
327 fn get_lints(&self) -> LintArray {
328 lint_array!(MODULO_ONE)
332 impl LateLintPass for ModuloOne {
333 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
334 if let ExprBinary(ref cmp, _, ref right) = expr.node {
335 if let Spanned { node: BinOp_::BiRem, .. } = *cmp {
336 if is_integer_literal(right, 1) {
337 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
344 /// **What it does:** This lint checks for patterns in the form `name @ _`.
346 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
348 /// **Known problems:** None
354 /// y @ _ => (), // easier written as `y`,
357 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
359 #[derive(Copy,Clone)]
360 pub struct PatternPass;
362 impl LintPass for PatternPass {
363 fn get_lints(&self) -> LintArray {
364 lint_array!(REDUNDANT_PATTERN)
368 impl LateLintPass for PatternPass {
369 fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
370 if let PatKind::Binding(_, ref ident, Some(ref right)) = pat.node {
371 if right.node == PatKind::Wild {
375 &format!("the `{} @ _` pattern can be written as just `{}`",
384 /// **What it does:** This lint checks for the use of bindings with a single leading underscore
386 /// **Why is this bad?** A single leading underscore is usually used to indicate that a binding
387 /// will not be used. Using such a binding breaks this expectation.
389 /// **Known problems:** The lint does not work properly with desugaring and macro, it has been
390 /// allowed in the mean time.
395 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
396 /// // We should rename `_x` to `x`
398 declare_lint!(pub USED_UNDERSCORE_BINDING, Allow,
399 "using a binding which is prefixed with an underscore");
401 #[derive(Copy, Clone)]
402 pub struct UsedUnderscoreBinding;
404 impl LintPass for UsedUnderscoreBinding {
405 fn get_lints(&self) -> LintArray {
406 lint_array!(USED_UNDERSCORE_BINDING)
410 impl LateLintPass for UsedUnderscoreBinding {
411 #[cfg_attr(rustfmt, rustfmt_skip)]
412 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
413 if in_attributes_expansion(cx, expr) {
414 // Don't lint things expanded by #[derive(...)], etc
417 let binding = match expr.node {
418 ExprPath(_, ref path) => {
419 let binding = path.segments
421 .expect("path should always have at least one segment")
424 if binding.starts_with('_') &&
425 !binding.starts_with("__") &&
426 binding != "_result" && // FIXME: #944
428 // don't lint if the declaration is in a macro
429 non_macro_local(cx, &cx.tcx.expect_def(expr.id)) {
435 ExprField(_, spanned) => {
436 let name = spanned.node.as_str();
437 if name.starts_with('_') && !name.starts_with("__") {
445 if let Some(binding) = binding {
447 USED_UNDERSCORE_BINDING,
449 &format!("used binding `{}` which is prefixed with an underscore. A leading \
450 underscore signals that a binding will not be used.", binding));
455 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
456 /// of what it means for an expression to be "used".
457 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
458 if let Some(ref parent) = get_parent_expr(cx, expr) {
460 ExprAssign(_, ref rhs) |
461 ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
462 _ => is_used(cx, parent),
469 /// Test whether an expression is in a macro expansion (e.g. something generated by
470 /// `#[derive(...)`] or the like).
471 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
472 cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
473 info_opt.map_or(false, |info| {
474 matches!(info.callee.format, ExpnFormat::MacroAttribute(_))
479 /// Test whether `def` is a variable defined outside a macro.
480 fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
482 def::Def::Local(_, id) | def::Def::Upvar(_, id, _, _) => {
483 if let Some(span) = cx.tcx.map.opt_span(id) {