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};
12 get_item_name, get_parent_expr, implements_trait, is_integer_literal, match_path, snippet,
13 span_lint, span_lint_and_then, walk_ptrs_ty
16 /// **What it does:** This lint checks for function arguments and let bindings denoted as `ref`.
18 /// **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.
20 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The type of `x` is more obvious with the former.
22 /// **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.
24 /// **Example:** `fn foo(ref x: u8) -> bool { .. }`
26 pub TOPLEVEL_REF_ARG, Warn,
27 "An entire binding was declared as `ref`, in a function argument (`fn foo(ref x: Bar)`), \
28 or a `let` statement (`let ref x = foo()`). In such cases, it is preferred to take \
32 #[allow(missing_copy_implementations)]
33 pub struct TopLevelRefPass;
35 impl LintPass for TopLevelRefPass {
36 fn get_lints(&self) -> LintArray {
37 lint_array!(TOPLEVEL_REF_ARG)
41 impl LateLintPass for TopLevelRefPass {
42 fn check_fn(&mut self, cx: &LateContext, k: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
43 if let FnKind::Closure(_) = k {
44 // Does not apply to closures
47 for ref arg in &decl.inputs {
48 if let PatKind::Binding(BindByRef(_), _, _) = arg.pat.node {
52 "`ref` directly on a function argument is ignored. Consider using a reference type instead.");
56 fn check_stmt(&mut self, cx: &LateContext, s: &Stmt) {
59 let StmtDecl(ref d, _) = s.node,
60 let DeclLocal(ref l) = d.node,
61 let PatKind::Binding(BindByRef(_), i, None) = l.pat.node,
62 let Some(ref init) = l.init
64 let tyopt = if let Some(ref ty) = l.ty {
65 format!(": {}", snippet(cx, ty.span, "_"))
69 span_lint_and_then(cx,
72 "`ref` on an entire `let` pattern is discouraged, take a reference with & instead",
74 db.span_suggestion(s.span,
76 format!("let {}{} = &{};",
77 snippet(cx, i.span, "_"),
79 snippet(cx, init.span, "_")));
87 /// **What it does:** This lint checks for comparisons to NAN.
89 /// **Why is this bad?** NAN does not compare meaningfully to anything – not even itself – so those comparisons are simply wrong.
91 /// **Known problems:** None
93 /// **Example:** `x == NAN`
94 declare_lint!(pub CMP_NAN, Deny,
95 "comparisons to NAN (which will always return false, which is probably not intended)");
100 impl LintPass for CmpNan {
101 fn get_lints(&self) -> LintArray {
106 impl LateLintPass for CmpNan {
107 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
108 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
109 if cmp.node.is_comparison() {
110 if let ExprPath(_, ref path) = left.node {
111 check_nan(cx, path, expr.span);
113 if let ExprPath(_, ref path) = right.node {
114 check_nan(cx, path, expr.span);
121 fn check_nan(cx: &LateContext, path: &Path, span: Span) {
122 path.segments.last().map(|seg| {
123 if seg.name.as_str() == "NAN" {
127 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead");
132 /// **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).
134 /// **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).
136 /// **Known problems:** None
138 /// **Example:** `y == 1.23f64`
139 declare_lint!(pub FLOAT_CMP, Warn,
140 "using `==` or `!=` on float values (as floating-point operations \
141 usually involve rounding errors, it is always better to check for approximate \
142 equality within small bounds)");
144 #[derive(Copy,Clone)]
147 impl LintPass for FloatCmp {
148 fn get_lints(&self) -> LintArray {
149 lint_array!(FLOAT_CMP)
153 impl LateLintPass for FloatCmp {
154 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
155 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
157 if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
158 if is_allowed(cx, left) || is_allowed(cx, right) {
161 if let Some(name) = get_item_name(cx, expr) {
162 let name = name.as_str();
163 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") ||
164 name.ends_with("_eq") {
171 &format!("{}-comparison of f32 or f64 detected. Consider changing this to `({} - {}).abs() < \
172 epsilon` for some suitable value of epsilon. \
173 std::f32::EPSILON and std::f64::EPSILON are available.",
175 snippet(cx, left.span, ".."),
176 snippet(cx, right.span, "..")));
182 fn is_allowed(cx: &LateContext, expr: &Expr) -> bool {
183 let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
184 if let Ok(ConstVal::Float(val)) = res {
185 val == 0.0 || val == ::std::f64::INFINITY || val == ::std::f64::NEG_INFINITY
191 fn is_float(cx: &LateContext, expr: &Expr) -> bool {
192 matches!(walk_ptrs_ty(cx.tcx.expr_ty(expr)).sty, ty::TyFloat(_))
195 /// **What it does:** This lint checks for conversions to owned values just for the sake of a comparison.
197 /// **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.
199 /// **Known problems:** None
201 /// **Example:** `x.to_owned() == y`
202 declare_lint!(pub CMP_OWNED, Warn,
203 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`");
205 #[derive(Copy,Clone)]
208 impl LintPass for CmpOwned {
209 fn get_lints(&self) -> LintArray {
210 lint_array!(CMP_OWNED)
214 impl LateLintPass for CmpOwned {
215 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
216 if let ExprBinary(ref cmp, ref left, ref right) = expr.node {
217 if cmp.node.is_comparison() {
218 check_to_owned(cx, left, right, true, cmp.span);
219 check_to_owned(cx, right, left, false, cmp.span)
225 fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr, left: bool, op: Span) {
226 let (arg_ty, snip) = match expr.node {
227 ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) if args.len() == 1 => {
228 if name.as_str() == "to_string" || name.as_str() == "to_owned" && is_str_arg(cx, args) {
229 (cx.tcx.expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
234 ExprCall(ref path, ref v) if v.len() == 1 => {
235 if let ExprPath(None, ref path) = path.node {
236 if match_path(path, &["String", "from_str"]) || match_path(path, &["String", "from"]) {
237 (cx.tcx.expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
248 let other_ty = cx.tcx.expr_ty(other);
249 let partial_eq_trait_id = match cx.tcx.lang_items.eq_trait() {
254 if !implements_trait(cx, arg_ty, partial_eq_trait_id, vec![other_ty]) {
262 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
263 compare without allocation",
265 snippet(cx, op, "=="),
266 snippet(cx, other.span, "..")));
271 &format!("this creates an owned instance just for comparison. Consider using `{} {} {}` to \
272 compare without allocation",
273 snippet(cx, other.span, ".."),
274 snippet(cx, op, "=="),
280 fn is_str_arg(cx: &LateContext, args: &[P<Expr>]) -> bool {
282 matches!(walk_ptrs_ty(cx.tcx.expr_ty(&args[0])).sty, ty::TyStr)
285 /// **What it does:** This lint checks for getting the remainder of a division by one.
287 /// **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.
289 /// **Known problems:** None
291 /// **Example:** `x % 1`
292 declare_lint!(pub MODULO_ONE, Warn, "taking a number modulo 1, which always returns 0");
294 #[derive(Copy,Clone)]
295 pub struct ModuloOne;
297 impl LintPass for ModuloOne {
298 fn get_lints(&self) -> LintArray {
299 lint_array!(MODULO_ONE)
303 impl LateLintPass for ModuloOne {
304 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
305 if let ExprBinary(ref cmp, _, ref right) = expr.node {
306 if let Spanned { node: BinOp_::BiRem, .. } = *cmp {
307 if is_integer_literal(right, 1) {
308 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
315 /// **What it does:** This lint checks for patterns in the form `name @ _`.
317 /// **Why is this bad?** It's almost always more readable to just use direct bindings.
319 /// **Known problems:** None
325 /// y @ _ => (), // easier written as `y`,
328 declare_lint!(pub REDUNDANT_PATTERN, Warn, "using `name @ _` in a pattern");
330 #[derive(Copy,Clone)]
331 pub struct PatternPass;
333 impl LintPass for PatternPass {
334 fn get_lints(&self) -> LintArray {
335 lint_array!(REDUNDANT_PATTERN)
339 impl LateLintPass for PatternPass {
340 fn check_pat(&mut self, cx: &LateContext, pat: &Pat) {
341 if let PatKind::Binding(_, ref ident, Some(ref right)) = pat.node {
342 if right.node == PatKind::Wild {
346 &format!("the `{} @ _` pattern can be written as just `{}`",
355 /// **What it does:** This lint checks for the use of bindings with a single leading underscore
357 /// **Why is this bad?** A single leading underscore is usually used to indicate that a binding
358 /// will not be used. Using such a binding breaks this expectation.
360 /// **Known problems:** The lint does not work properly with desugaring and macro, it has been
361 /// allowed in the mean time.
366 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading underscore.
367 /// // We should rename `_x` to `x`
369 declare_lint!(pub USED_UNDERSCORE_BINDING, Allow,
370 "using a binding which is prefixed with an underscore");
372 #[derive(Copy, Clone)]
373 pub struct UsedUnderscoreBinding;
375 impl LintPass for UsedUnderscoreBinding {
376 fn get_lints(&self) -> LintArray {
377 lint_array!(USED_UNDERSCORE_BINDING)
381 impl LateLintPass for UsedUnderscoreBinding {
382 #[cfg_attr(rustfmt, rustfmt_skip)]
383 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
384 if in_attributes_expansion(cx, expr) {
385 // Don't lint things expanded by #[derive(...)], etc
388 let binding = match expr.node {
389 ExprPath(_, ref path) => {
390 let segment = path.segments
392 .expect("path should always have at least one segment")
394 if segment.as_str().starts_with('_') &&
395 !segment.as_str().starts_with("__") &&
396 segment != segment.unhygienize() && // not in bang macro
398 Some(segment.as_str())
403 ExprField(_, spanned) => {
404 let name = spanned.node.as_str();
405 if name.starts_with('_') && !name.starts_with("__") {
413 if let Some(binding) = binding {
414 if binding != "_result" { // FIXME: #944
416 USED_UNDERSCORE_BINDING,
418 &format!("used binding `{}` which is prefixed with an underscore. A leading \
419 underscore signals that a binding will not be used.", binding));
425 /// Heuristic to see if an expression is used. Should be compatible with `unused_variables`'s idea
426 /// of what it means for an expression to be "used".
427 fn is_used(cx: &LateContext, expr: &Expr) -> bool {
428 if let Some(ref parent) = get_parent_expr(cx, expr) {
430 ExprAssign(_, ref rhs) |
431 ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
432 _ => is_used(cx, parent),
439 /// Test whether an expression is in a macro expansion (e.g. something generated by
440 /// `#[derive(...)`] or the like).
441 fn in_attributes_expansion(cx: &LateContext, expr: &Expr) -> bool {
442 cx.sess().codemap().with_expn_info(expr.span.expn_id, |info_opt| {
443 info_opt.map_or(false, |info| {
444 matches!(info.callee.format, ExpnFormat::MacroAttribute(_))