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(_), i, None) = l.pat.node,
63 let Some(ref init) = l.init
65 let tyopt = if let Some(ref ty) = l.ty {
66 format!(": {}", snippet(cx, ty.span, "_"))
70 span_lint_and_then(cx,
73 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
75 let init = Sugg::hir(cx, init, "..");
76 db.span_suggestion(s.span,
78 format!("let {}{} = {};",
79 snippet(cx, i.span, "_"),
88 /// **What it does:** This lint checks for comparisons to NAN.
90 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
92 /// **Known problems:** None
94 /// **Example:** `x == NAN`
95 declare_lint!(pub CMP_NAN, Deny,
96 "comparisons to NAN (which will always return false, which is probably not intended)");
101 impl LintPass for CmpNan {
102 fn get_lints(&self) -> LintArray {
107 impl LateLintPass for CmpNan {
108 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
109 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
110 if cmp.node.is_comparison() {
111 if let ExprPath(_, ref path) = left.node {
112 check_nan(cx, path, expr.span);
114 if let ExprPath(_, ref path) = right.node {
115 check_nan(cx, path, expr.span);
122 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
123 path.segments.last().map(|seg| {
124 if seg.name.as_str() == "NAN" {
128 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
133 /// **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).
135 /// **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).
137 /// **Known problems:** None
139 /// **Example:** `y == 1.23f64`
140 declare_lint!(pub FLOAT_CMP, Warn,
141 "using `==` or `!=` on float values (as floating-point operations \
142 usually involve rounding errors, it is always better to check for approximate \
143 equality within small bounds)");
145 #[derive(Copy,Clone)]
148 impl LintPass for FloatCmp {
149 fn get_lints(&self) -> LintArray {
150 lint_array!(FLOAT_CMP)
154 impl LateLintPass for FloatCmp {
155 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
156 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
158 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
159 if is_allowed(cx, left) || is_allowed(cx, right) {
162 if let Some(name) = get_item_name(cx, expr) {
163 let name = name.as_str();
164 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
165 name.ends_with("_eq") {
169 span_lint_and_then(cx,
172 "strict comparison of f32 or f64",
174 let lhs = Sugg::hir(cx, left, "..");
175 let rhs = Sugg::hir(cx, right, "..");
177 db.span_suggestion(expr.span,
178 "consider comparing them within some error",
179 format!("({}).abs() < error", lhs - rhs));
180 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
187 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
188 let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
189 if let Ok(ConstVal::Float(val)) = res {
190 use std::cmp::Ordering;
192 let zero = ConstFloat::FInfer {
197 let infinity = ConstFloat::FInfer {
198 f32: ::std::f32::INFINITY,
199 f64: ::std::f64::INFINITY,
202 let neg_infinity = ConstFloat::FInfer {
203 f32: ::std::f32::NEG_INFINITY,
204 f64: ::std::f64::NEG_INFINITY,
207 val.try_cmp(zero) == Ok(Ordering::Equal)
208 || val.try_cmp(infinity) == Ok(Ordering::Equal)
209 || val.try_cmp(neg_infinity) == Ok(Ordering::Equal)
215 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
216 matches!(walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty, ty::TyFloat(_))
219 /// **What it does:** This lint checks for conversions to owned values just for the sake of a comparison.
221 /// **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.
223 /// **Known problems:** None
225 /// **Example:** `x.to_owned() == y`
226 declare_lint!(pub CMP_OWNED, Warn,
227 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
229 #[derive(Copy,Clone)]
232 impl LintPass for CmpOwned {
233 fn get_lints(&self) -> LintArray {
234 lint_array!(CMP_OWNED)
238 impl LateLintPass for CmpOwned {
239 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
240 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
241 if cmp.node.is_comparison() {
242 check_to_owned(cx, left, right, true, cmp.span);
243 check_to_owned(cx, right, left, false, cmp.span)
249 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
250 let (arg_ty, snip) = match expr.node {
251 ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) if args.len() == 1 => {
252 if name.as_str() == "to_string" || name.as_str() == "to_owned" && is_str_arg(cx, args) {
253 (cx.tcx.expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
258 ExprCall(ref path, ref v) if v.len() == 1 => {
259 if let ExprPath(None, ref path) = path.node {
260 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
261 (cx.tcx.expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
272 let other_ty = cx.tcx.expr_ty(other);
273 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
278 if !implements_trait(cx, arg_ty, partial_eq_trait_id, vec![other_ty]) {
286 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
287 compare without allocation",
289 snippet(cx, op, "=="),
290 snippet(cx, other.span, "..")));
295 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
296 compare without allocation",
297 snippet(cx, other.span, ".."),
298 snippet(cx, op, "=="),
304 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
306 matches!(walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty, ty::TyStr)
309 /// **What it does:** This lint checks for getting the remainder of a division by one.
311 /// **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.
313 /// **Known problems:** None
315 /// **Example:** `x % 1`
316 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
318 #[derive(Copy,Clone)]
319 pub struct ModuloOne;
321 impl LintPass for ModuloOne {
322 fn get_lints(&self) -> LintArray {
323 lint_array!(MODULO_ONE)
327 impl LateLintPass for ModuloOne {
328 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
329 if let ExprBinary(ref cmp, _, ref right) = expr.node {
330 if let Spanned { node: BinOp_::BiRem, .. } = *cmp {
331 if is_integer_literal(right, 1) {
332 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
339 /// **What it does:** This lint checks for patterns in the form `name @ _`.
341 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
343 /// **Known problems:** None
349 /// y @ _ => (), // easier written as `y`,
352 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
354 #[derive(Copy,Clone)]
355 pub struct PatternPass;
357 impl LintPass for PatternPass {
358 fn get_lints(&self) -> LintArray {
359 lint_array!(REDUNDANT_PATTERN)
363 impl LateLintPass for PatternPass {
364 fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
365 if let PatKind::Binding(_, ref ident, Some(ref right)) = pat.node {
366 if right.node == PatKind::Wild {
370 &format!("the `{} @ _` pattern can be written as just `{}`",
379 /// **What it does:** This lint checks for the use of bindings with a single leading underscore
381 /// **Why is this bad?** A single leading underscore is usually used to indicate that a binding
382 /// will not be used. Using such a binding breaks this expectation.
384 /// **Known problems:** The lint does not work properly with desugaring and macro, it has been
385 /// allowed in the mean time.
390 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
391 /// // We should rename `_x` to `x`
393 declare_lint!(pub USED_UNDERSCORE_BINDING, Allow,
394 "using a binding which is prefixed with an underscore");
396 #[derive(Copy, Clone)]
397 pub struct UsedUnderscoreBinding;
399 impl LintPass for UsedUnderscoreBinding {
400 fn get_lints(&self) -> LintArray {
401 lint_array!(USED_UNDERSCORE_BINDING)
405 impl LateLintPass for UsedUnderscoreBinding {
406 #[cfg_attr(rustfmt, rustfmt_skip)]
407 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
408 if in_attributes_expansion(cx, expr) {
409 // Don't lint things expanded by #[derive(...)], etc
412 let binding = match expr.node {
413 ExprPath(_, ref path) => {
414 let binding = path.segments
416 .expect("path should always have at least one segment")
419 if binding.starts_with('_') &&
420 !binding.starts_with("__") &&
421 binding != "_result" && // FIXME: #944
423 // don't lint if the declaration is in a macro
424 non_macro_local(cx, &cx.tcx.expect_def(expr.id)) {
430 ExprField(_, spanned) => {
431 let name = spanned.node.as_str();
432 if name.starts_with('_') && !name.starts_with("__") {
440 if let Some(binding) = binding {
442 USED_UNDERSCORE_BINDING,
444 &format!("used binding `{}` which is prefixed with an underscore. A leading \
445 underscore signals that a binding will not be used.", binding));
450 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
451 /// of what it means for an expression to be "used".
452 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
453 if let Some(ref parent) = get_parent_expr(cx, expr) {
455 ExprAssign(_, ref rhs) |
456 ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
457 _ => is_used(cx, parent),
464 /// Test whether an expression is in a macro expansion (e.g. something generated by
465 /// `#[derive(...)`] or the like).
466 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
467 cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
468 info_opt.map_or(false, |info| {
469 matches!(info.callee.format, ExpnFormat::MacroAttribute(_))
474 /// Test whether `def` is a variable defined outside a macro.
475 fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
477 def::Def::Local(_, id) | def::Def::Upvar(_, id, _, _) => {
478 if let Some(span) = cx.tcx.map.opt_span(id) {