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 syntax::codemap::{Span, Spanned, ExpnFormat};
11 use utils::{get_item_name, match_path, snippet, get_parent_expr, span_lint};
12 use utils::{span_lint_and_then, walk_ptrs_ty, is_integer_literal, implements_trait};
14 /// **What it does:** This lint checks for function arguments and let bindings denoted as `ref`.
16 /// **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.
18 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The type of `x` is more obvious with the former.
20 /// **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.
22 /// **Example:** `fn foo(ref x: u8) -> bool { .. }`
24 pub TOPLEVEL_REF_ARG, Warn,
25 "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
26 or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
30 #[allow(missing_copy_implementations)]
31 pub struct TopLevelRefPass;
33 impl LintPass for TopLevelRefPass {
34 fn get_lints(&self) -> LintArray {
35 lint_array!(TOPLEVEL_REF_ARG)
39 impl LateLintPass for TopLevelRefPass {
40 fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
41 if let FnKind::Closure(_) = k {
42 // Does not apply to closures
45 for ref arg in &decl.inputs {
46 if let PatKind::Ident(BindByRef(_), _, _) = arg.pat.node {
50 "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
54 fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
57 let StmtDecl(ref d, _) = s.node,
58 let DeclLocal(ref l) = d.node,
59 let PatKind::Ident(BindByRef(_), i, None) = l.pat.node,
60 let Some(ref init) = l.init
62 let tyopt = if let Some(ref ty) = l.ty {
63 format!(": {}", snippet(cx, ty.span, "_"))
67 span_lint_and_then(cx,
70 "`ref` on an entire `let` pattern is discouraged, take a reference with & instead",
72 db.span_suggestion(s.span,
74 format!("let {}{} = &{};",
75 snippet(cx, i.span, "_"),
77 snippet(cx, init.span, "_")));
85 /// **What it does:** This lint checks for comparisons to NAN.
87 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
89 /// **Known problems:** None
91 /// **Example:** `x == NAN`
92 declare_lint!(pub CMP_NAN, Deny,
93 "comparisons to NAN (which will always return false, which is probably not intended)");
98 impl LintPass for CmpNan {
99 fn get_lints(&self) -> LintArray {
104 impl LateLintPass for CmpNan {
105 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
106 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
107 if cmp.node.is_comparison() {
108 if let ExprPath(_, ref path) = left.node {
109 check_nan(cx, path, expr.span);
111 if let ExprPath(_, ref path) = right.node {
112 check_nan(cx, path, expr.span);
119 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
120 path.segments.last().map(|seg| {
121 if seg.identifier.name.as_str() == "NAN" {
125 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
130 /// **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).
132 /// **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).
134 /// **Known problems:** None
136 /// **Example:** `y == 1.23f64`
137 declare_lint!(pub FLOAT_CMP, Warn,
138 "using `==` or `!=` on float values (as floating-point operations \
139 usually involve rounding errors, it is always better to check for approximate \
140 equality within small bounds)");
142 #[derive(Copy,Clone)]
145 impl LintPass for FloatCmp {
146 fn get_lints(&self) -> LintArray {
147 lint_array!(FLOAT_CMP)
151 impl LateLintPass for FloatCmp {
152 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
153 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
155 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
156 if is_allowed(cx, left) || is_allowed(cx, right) {
159 if let Some(name) = get_item_name(cx, expr) {
160 let name = name.as_str();
161 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
162 name.ends_with("_eq") {
169 &format!("{}-comparison of f32 or f64 detected. Consider changing this to `({} - {}).abs() < \
170 epsilon` for some suitable value of epsilon. \
171 std::f32::EPSILON and std::f64::EPSILON are available.",
173 snippet(cx, left.span, ".."),
174 snippet(cx, right.span, "..")));
180 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
181 let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
182 if let Ok(ConstVal::Float(val)) = res {
183 val == 0.0 || val == ::std::f64::INFINITY || val == ::std::f64::NEG_INFINITY
189 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
190 if let ty::TyFloat(_) = walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty {
197 /// **What it does:** This lint checks for conversions to owned values just for the sake of a comparison.
199 /// **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.
201 /// **Known problems:** None
203 /// **Example:** `x.to_owned() == y`
204 declare_lint!(pub CMP_OWNED, Warn,
205 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
207 #[derive(Copy,Clone)]
210 impl LintPass for CmpOwned {
211 fn get_lints(&self) -> LintArray {
212 lint_array!(CMP_OWNED)
216 impl LateLintPass for CmpOwned {
217 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
218 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
219 if cmp.node.is_comparison() {
220 check_to_owned(cx, left, right, true, cmp.span);
221 check_to_owned(cx, right, left, false, cmp.span)
227 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
228 let (arg_ty, snip) = match expr.node {
229 ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) if args.len() == 1 => {
230 if name.as_str() == "to_string" || name.as_str() == "to_owned" && is_str_arg(cx, args) {
231 (cx.tcx.expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
236 ExprCall(ref path, ref v) if v.len() == 1 => {
237 if let ExprPath(None, ref path) = path.node {
238 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
239 (cx.tcx.expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
250 let other_ty = cx.tcx.expr_ty(other);
251 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
256 if !implements_trait(cx, arg_ty, partial_eq_trait_id, vec![other_ty]) {
264 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
265 compare without allocation",
267 snippet(cx, op, "=="),
268 snippet(cx, other.span, "..")));
273 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
274 compare without allocation",
275 snippet(cx, other.span, ".."),
276 snippet(cx, op, "=="),
282 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
284 if let ty::TyStr = walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty {
291 /// **What it does:** This lint checks for getting the remainder of a division by one.
293 /// **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.
295 /// **Known problems:** None
297 /// **Example:** `x % 1`
298 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
300 #[derive(Copy,Clone)]
301 pub struct ModuloOne;
303 impl LintPass for ModuloOne {
304 fn get_lints(&self) -> LintArray {
305 lint_array!(MODULO_ONE)
309 impl LateLintPass for ModuloOne {
310 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
311 if let ExprBinary(ref cmp, _, ref right) = expr.node {
312 if let Spanned { node: BinOp_::BiRem, .. } = *cmp {
313 if is_integer_literal(right, 1) {
314 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
321 /// **What it does:** This lint checks for patterns in the form `name @ _`.
323 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
325 /// **Known problems:** None
331 /// y @ _ => (), // easier written as `y`,
334 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
336 #[derive(Copy,Clone)]
337 pub struct PatternPass;
339 impl LintPass for PatternPass {
340 fn get_lints(&self) -> LintArray {
341 lint_array!(REDUNDANT_PATTERN)
345 impl LateLintPass for PatternPass {
346 fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
347 if let PatKind::Ident(_, ref ident, Some(ref right)) = pat.node {
348 if right.node == PatKind::Wild {
352 &format!("the `{} @ _` pattern can be written as just `{}`",
361 /// **What it does:** This lint checks for the use of bindings with a single leading underscore
363 /// **Why is this bad?** A single leading underscore is usually used to indicate that a binding
364 /// will not be used. Using such a binding breaks this expectation.
366 /// **Known problems:** None
371 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
372 /// // We should rename `_x` to `x`
374 declare_lint!(pub USED_UNDERSCORE_BINDING, Warn,
375 "using a binding which is prefixed with an underscore");
377 #[derive(Copy, Clone)]
378 pub struct UsedUnderscoreBinding;
380 impl LintPass for UsedUnderscoreBinding {
381 fn get_lints(&self) -> LintArray {
382 lint_array!(USED_UNDERSCORE_BINDING)
386 impl LateLintPass for UsedUnderscoreBinding {
387 #[cfg_attr(rustfmt, rustfmt_skip)]
388 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
389 if in_attributes_expansion(cx, expr) {
390 // Don't lint things expanded by #[derive(...)], etc
393 let needs_lint = match expr.node {
394 ExprPath(_, ref path) => {
395 let ident = path.segments
397 .expect("path should always have at least one segment")
399 ident.name.as_str().starts_with('_') &&
400 !ident.name.as_str().starts_with("__") &&
401 ident.name != ident.unhygienic_name &&
402 is_used(cx, expr) // not in bang macro
404 ExprField(_, spanned) => {
405 let name = spanned.node.as_str();
406 name.starts_with('_') && !name.starts_with("__")
412 USED_UNDERSCORE_BINDING,
414 "used binding which is prefixed with an underscore. A leading underscore signals that a \
415 binding will not be used.");
420 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
421 /// of what it means for an expression to be "used".
422 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
423 if let Some(ref parent) = get_parent_expr(cx, expr) {
425 ExprAssign(_, ref rhs) |
426 ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
427 _ => is_used(cx, parent),
434 /// Test whether an expression is in a macro expansion (e.g. something generated by #[derive(...)]
436 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
437 cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
438 info_opt.map_or(false, |info| {
439 match info.callee.format {
440 ExpnFormat::MacroAttribute(_) => true,