3 use rustc::hir::intravisit::{FnKind, Visitor, walk_ty};
6 use std::cmp::Ordering;
7 use syntax::ast::{IntTy, UintTy, FloatTy};
8 use syntax::codemap::Span;
9 use utils::{comparisons, higher, in_external_macro, in_macro, match_def_path, snippet,
10 span_help_and_lint, span_lint};
13 /// Handles all the linting of funky types
14 #[allow(missing_copy_implementations)]
17 /// **What it does:** This lint checks for use of `Box<Vec<_>>` anywhere in the code.
19 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on the heap. So if you
20 /// `Box` it, you just add another level of indirection without any benefit whatsoever.
22 /// **Known problems:** None
27 /// values: Box<Vec<Foo>>,
32 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
35 /// **What it does:** This lint checks for usage of any `LinkedList`, suggesting to use a `Vec` or
36 /// a `VecDeque` (formerly called `RingBuf`).
38 /// **Why is this bad?** Gankro says:
40 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of pointers and indirection.
41 /// > It wastes memory, it has terrible cache locality, and is all-around slow. `RingBuf`, while
42 /// > "only" amortized for push/pop, should be faster in the general case for almost every possible
43 /// > workload, and isn't even amortized at all if you can predict the capacity you need.
45 /// > `LinkedList`s are only really good if you're doing a lot of merging or splitting of lists.
46 /// > This is because they can just mangle some pointers instead of actually copying the data. Even
47 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf` can still be better
48 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
50 /// **Known problems:** False positives – the instances where using a `LinkedList` makes sense are
51 /// few and far between, but they can still happen.
55 /// let x = LinkedList::new();
59 "usage of LinkedList, usually a vector is faster, or a more specialized data \
60 structure like a VecDeque"
63 impl LintPass for TypePass {
64 fn get_lints(&self) -> LintArray {
65 lint_array!(BOX_VEC, LINKEDLIST)
69 impl LateLintPass for TypePass {
70 fn check_ty(&mut self, cx: &LateContext, ast_ty: &Ty) {
71 if in_macro(cx, ast_ty.span) {
74 if let Some(did) = cx.tcx.def_map.borrow().get(&ast_ty.id) {
75 if let def::Def::Struct(..) = did.full_def() {
76 if Some(did.full_def().def_id()) == cx.tcx.lang_items.owned_box() {
78 let TyPath(_, ref path) = ast_ty.node,
79 let Some(ref last) = path.segments.last(),
80 let PathParameters::AngleBracketedParameters(ref ag) = last.parameters,
81 let Some(ref vec) = ag.types.get(0),
82 let Some(did) = cx.tcx.def_map.borrow().get(&vec.id),
83 let def::Def::Struct(..) = did.full_def(),
84 match_def_path(cx, did.full_def().def_id(), &paths::VEC),
86 span_help_and_lint(cx,
89 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
90 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.");
92 } else if match_def_path(cx, did.full_def().def_id(), &paths::LINKED_LIST) {
93 span_help_and_lint(cx,
96 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
97 "a VecDeque might work");
104 #[allow(missing_copy_implementations)]
107 /// **What it does:** This lint checks for binding a unit value.
109 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So binding one is kind of pointless.
111 /// **Known problems:** None
113 /// **Example:** `let x = { 1; };`
115 pub LET_UNIT_VALUE, Warn,
116 "creating a let binding to a value of unit type, which usually can't be used afterwards"
119 fn check_let_unit(cx: &LateContext, decl: &Decl) {
120 if let DeclLocal(ref local) = decl.node {
121 let bindtype = &cx.tcx.pat_ty(&local.pat).sty;
122 if *bindtype == ty::TyTuple(&[]) {
123 if in_external_macro(cx, decl.span) || in_macro(cx, local.pat.span) {
126 if higher::is_from_for_desugar(decl) {
132 &format!("this let-binding has unit value. Consider omitting `let {} =`",
133 snippet(cx, local.pat.span, "..")));
138 impl LintPass for LetPass {
139 fn get_lints(&self) -> LintArray {
140 lint_array!(LET_UNIT_VALUE)
144 impl LateLintPass for LetPass {
145 fn check_decl(&mut self, cx: &LateContext, decl: &Decl) {
146 check_let_unit(cx, decl)
150 /// **What it does:** This lint checks for comparisons to unit.
152 /// **Why is this bad?** Unit is always equal to itself, and thus is just a clumsily written constant. Mostly this happens when someone accidentally adds semicolons at the end of the operands.
154 /// **Known problems:** None
156 /// **Example:** `if { foo(); } == { bar(); } { baz(); }` is equal to `{ foo(); bar(); baz(); }`
159 "comparing unit values (which is always `true` or `false`, respectively)"
162 #[allow(missing_copy_implementations)]
165 impl LintPass for UnitCmp {
166 fn get_lints(&self) -> LintArray {
167 lint_array!(UNIT_CMP)
171 impl LateLintPass for UnitCmp {
172 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
173 if in_macro(cx, expr.span) {
176 if let ExprBinary(ref cmp, ref left, _) = expr.node {
178 let sty = &cx.tcx.expr_ty(left).sty;
179 if *sty == ty::TyTuple(&[]) && op.is_comparison() {
180 let result = match op {
181 BiEq | BiLe | BiGe => "true",
187 &format!("{}-comparison of unit values detected. This will always be {}",
197 /// **What it does:** This lint checks for casts from any numerical to a float type where the receiving type cannot store all values from the original type without rounding errors. This possible rounding is to be expected, so this lint is `Allow` by default.
199 /// Basically, this warns on casting any integer with 32 or more bits to `f32` or any 64-bit integer to `f64`.
201 /// **Why is this bad?** It's not bad at all. But in some applications it can be helpful to know where precision loss can take place. This lint can help find those places in the code.
203 /// **Known problems:** None
205 /// **Example:** `let x = u64::MAX; x as f64`
207 pub CAST_PRECISION_LOSS, Allow,
208 "casts that cause loss of precision, e.g `x as f32` where `x: u64`"
211 /// **What it does:** This lint checks for casts from a signed to an unsigned numerical type. In this case, negative values wrap around to large positive values, which can be quite surprising in practice. However, as the cast works as defined, this lint is `Allow` by default.
213 /// **Why is this bad?** Possibly surprising results. You can activate this lint as a one-time check to see where numerical wrapping can arise.
215 /// **Known problems:** None
217 /// **Example:** `let y : i8 = -1; y as u64` will return 18446744073709551615
219 pub CAST_SIGN_LOSS, Allow,
220 "casts from signed types to unsigned types, e.g `x as u32` where `x: i32`"
223 /// **What it does:** This lint checks for on casts between numerical types that may truncate large values. This is expected behavior, so the cast is `Allow` by default.
225 /// **Why is this bad?** In some problem domains, it is good practice to avoid truncation. This lint can be activated to help assess where additional checks could be beneficial.
227 /// **Known problems:** None
229 /// **Example:** `fn as_u8(x: u64) -> u8 { x as u8 }`
231 pub CAST_POSSIBLE_TRUNCATION, Allow,
232 "casts that may cause truncation of the value, e.g `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
235 /// **What it does:** This lint checks for casts from an unsigned type to a signed type of the same size. Performing such a cast is a 'no-op' for the compiler, i.e. nothing is changed at the bit level, and the binary representation of the value is reinterpreted. This can cause wrapping if the value is too big for the target signed type. However, the cast works as defined, so this lint is `Allow` by default.
237 /// **Why is this bad?** While such a cast is not bad in itself, the results can be surprising when this is not the intended behavior, as demonstrated by the example below.
239 /// **Known problems:** None
241 /// **Example:** `u32::MAX as i32` will yield a value of `-1`.
243 pub CAST_POSSIBLE_WRAP, Allow,
244 "casts that may cause wrapping around the value, e.g `x as i32` where `x: u32` and `x > i32::MAX`"
247 /// Returns the size in bits of an integral type.
248 /// Will return 0 if the type is not an int or uint variant
249 fn int_ty_to_nbits(typ: &ty::TyS) -> usize {
250 let n = match typ.sty {
251 ty::TyInt(i) => 4 << (i as usize),
252 ty::TyUint(u) => 4 << (u as usize),
255 // n == 4 is the usize/isize case
257 ::std::mem::size_of::<usize>() * 8
263 fn is_isize_or_usize(typ: &ty::TyS) -> bool {
265 ty::TyInt(IntTy::Is) |
266 ty::TyUint(UintTy::Us) => true,
271 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to_f64: bool) {
272 let mantissa_nbits = if cast_to_f64 {
277 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
278 let arch_dependent_str = "on targets with 64-bit wide pointers ";
279 let from_nbits_str = if arch_dependent {
281 } else if is_isize_or_usize(cast_from) {
282 "32 or 64".to_owned()
284 int_ty_to_nbits(cast_from).to_string()
289 &format!("casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
290 is only {4} bits wide)",
312 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to: &ty::TyS) {
313 let arch_64_suffix = " on targets with 64-bit wide pointers";
314 let arch_32_suffix = " on targets with 32-bit wide pointers";
315 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
316 let (from_nbits, to_nbits) = (int_ty_to_nbits(cast_from), int_ty_to_nbits(cast_to));
317 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) = match (is_isize_or_usize(cast_from),
318 is_isize_or_usize(cast_to)) {
319 (true, true) | (false, false) => {
320 (to_nbits < from_nbits,
322 to_nbits == from_nbits && cast_unsigned_to_signed,
332 to_nbits <= 32 && cast_unsigned_to_signed,
338 cast_unsigned_to_signed,
339 if from_nbits == 64 {
348 CAST_POSSIBLE_TRUNCATION,
350 &format!("casting {} to {} may truncate the value{}",
353 match suffix_truncation {
354 ArchSuffix::_32 => arch_32_suffix,
355 ArchSuffix::_64 => arch_64_suffix,
356 ArchSuffix::None => "",
363 &format!("casting {} to {} may wrap around the value{}",
367 ArchSuffix::_32 => arch_32_suffix,
368 ArchSuffix::_64 => arch_64_suffix,
369 ArchSuffix::None => "",
374 impl LintPass for CastPass {
375 fn get_lints(&self) -> LintArray {
376 lint_array!(CAST_PRECISION_LOSS,
378 CAST_POSSIBLE_TRUNCATION,
383 impl LateLintPass for CastPass {
384 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
385 if let ExprCast(ref ex, _) = expr.node {
386 let (cast_from, cast_to) = (cx.tcx.expr_ty(ex), cx.tcx.expr_ty(expr));
387 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
388 match (cast_from.is_integral(), cast_to.is_integral()) {
390 let from_nbits = int_ty_to_nbits(cast_from);
391 let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
396 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
397 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
402 CAST_POSSIBLE_TRUNCATION,
404 &format!("casting {} to {} may truncate the value", cast_from, cast_to));
405 if !cast_to.is_signed() {
409 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
413 if cast_from.is_signed() && !cast_to.is_signed() {
417 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
419 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
422 if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty,
425 CAST_POSSIBLE_TRUNCATION,
427 "casting f64 to f32 may truncate the value");
436 /// **What it does:** This lint checks for types used in structs, parameters and `let` declarations above a certain complexity threshold.
438 /// **Why is this bad?** Too complex types make the code less readable. Consider using a `type` definition to simplify them.
440 /// **Known problems:** None
442 /// **Example:** `struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }`
444 pub TYPE_COMPLEXITY, Warn,
445 "usage of very complex types; recommends factoring out parts into `type` definitions"
448 #[allow(missing_copy_implementations)]
449 pub struct TypeComplexityPass {
453 impl TypeComplexityPass {
454 pub fn new(threshold: u64) -> Self {
455 TypeComplexityPass { threshold: threshold }
459 impl LintPass for TypeComplexityPass {
460 fn get_lints(&self) -> LintArray {
461 lint_array!(TYPE_COMPLEXITY)
465 impl LateLintPass for TypeComplexityPass {
466 fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
467 self.check_fndecl(cx, decl);
470 fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
471 // enum variants are also struct fields now
472 self.check_type(cx, &field.ty);
475 fn check_item(&mut self, cx: &LateContext, item: &Item) {
477 ItemStatic(ref ty, _, _) |
478 ItemConst(ref ty, _) => self.check_type(cx, ty),
479 // functions, enums, structs, impls and traits are covered
484 fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
486 ConstTraitItem(ref ty, _) |
487 TypeTraitItem(_, Some(ref ty)) => self.check_type(cx, ty),
488 MethodTraitItem(MethodSig { ref decl, .. }, None) => self.check_fndecl(cx, decl),
489 // methods with default impl are covered by check_fn
494 fn check_impl_item(&mut self, cx: &LateContext, item: &ImplItem) {
496 ImplItemKind::Const(ref ty, _) |
497 ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
498 // methods are covered by check_fn
503 fn check_local(&mut self, cx: &LateContext, local: &Local) {
504 if let Some(ref ty) = local.ty {
505 self.check_type(cx, ty);
510 impl TypeComplexityPass {
511 fn check_fndecl(&self, cx: &LateContext, decl: &FnDecl) {
512 for arg in &decl.inputs {
513 self.check_type(cx, &arg.ty);
515 if let Return(ref ty) = decl.output {
516 self.check_type(cx, ty);
520 fn check_type(&self, cx: &LateContext, ty: &Ty) {
521 if in_macro(cx, ty.span) {
525 let mut visitor = TypeComplexityVisitor {
529 visitor.visit_ty(ty);
533 if score > self.threshold {
537 "very complex type used. Consider factoring parts into `type` definitions");
542 /// Walks a type and assigns a complexity score to it.
543 struct TypeComplexityVisitor {
544 /// total complexity score of the type
546 /// current nesting level
550 impl<'v> Visitor<'v> for TypeComplexityVisitor {
551 fn visit_ty(&mut self, ty: &'v Ty) {
552 let (add_score, sub_nest) = match ty.node {
553 // _, &x and *x have only small overhead; don't mess with nesting level
554 TyInfer | TyPtr(..) | TyRptr(..) => (1, 0),
556 // the "normal" components of a type: named types, arrays/tuples
560 TyFixedLengthVec(..) => (10 * self.nest, 1),
562 // "Sum" of trait bounds
563 TyObjectSum(..) => (20 * self.nest, 0),
565 // function types and "for<...>" bring a lot of overhead
567 TyPolyTraitRef(..) => (50 * self.nest, 1),
571 self.score += add_score;
572 self.nest += sub_nest;
574 self.nest -= sub_nest;
578 /// **What it does:** This lint points out expressions where a character literal is casted to `u8` and suggests using a byte literal instead.
580 /// **Why is this bad?** In general, casting values to smaller types is error-prone and should be avoided where possible. In the particular case of converting a character literal to u8, it is easy to avoid by just using a byte literal instead. As an added bonus, `b'a'` is even slightly shorter than `'a' as u8`.
582 /// **Known problems:** None
584 /// **Example:** `'x' as u8`
586 pub CHAR_LIT_AS_U8, Warn,
587 "Casting a character literal to u8"
590 pub struct CharLitAsU8;
592 impl LintPass for CharLitAsU8 {
593 fn get_lints(&self) -> LintArray {
594 lint_array!(CHAR_LIT_AS_U8)
598 impl LateLintPass for CharLitAsU8 {
599 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
600 use syntax::ast::{LitKind, UintTy};
602 if let ExprCast(ref e, _) = expr.node {
603 if let ExprLit(ref l) = e.node {
604 if let LitKind::Char(_) = l.node {
605 if ty::TyUint(UintTy::U8) == cx.tcx.expr_ty(expr).sty && !in_macro(cx, expr.span) {
606 let msg = "casting character literal to u8. `char`s \
607 are 4 bytes wide in rust, so casting to u8 \
609 let help = format!("Consider using a byte literal \
611 snippet(cx, e.span, "'x'"));
612 span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
620 /// **What it does:** This lint checks for comparisons where one side of the relation is either the minimum or maximum value for its type and warns if it involves a case that is always true or always false. Only integer and boolean types are checked.
622 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply that is is possible for `x` to be less than the minimum. Expressions like `max < x` are probably mistakes.
624 /// **Known problems:** None
626 /// **Example:** `vec.len() <= 0`, `100 > std::i32::MAX`
628 pub ABSURD_EXTREME_COMPARISONS, Warn,
629 "a comparison involving a maximum or minimum value involves a case that is always \
630 true or always false"
633 pub struct AbsurdExtremeComparisons;
635 impl LintPass for AbsurdExtremeComparisons {
636 fn get_lints(&self) -> LintArray {
637 lint_array!(ABSURD_EXTREME_COMPARISONS)
646 struct ExtremeExpr<'a> {
651 enum AbsurdComparisonResult {
654 InequalityImpossible,
659 fn detect_absurd_comparison<'a>(cx: &LateContext, op: BinOp_, lhs: &'a Expr, rhs: &'a Expr)
660 -> Option<(ExtremeExpr<'a>, AbsurdComparisonResult)> {
661 use types::ExtremeType::*;
662 use types::AbsurdComparisonResult::*;
663 use utils::comparisons::*;
664 type Extr<'a> = ExtremeExpr<'a>;
666 let normalized = normalize_comparison(op, lhs, rhs);
667 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
673 let lx = detect_extreme_expr(cx, normalized_lhs);
674 let rx = detect_extreme_expr(cx, normalized_rhs);
679 (Some(l @ Extr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
680 (_, Some(r @ Extr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
686 (Some(l @ Extr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
687 (Some(l @ Extr { which: Maximum, .. }), _) => (l, InequalityImpossible), //max <= x
688 (_, Some(r @ Extr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
689 (_, Some(r @ Extr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
693 Rel::Ne | Rel::Eq => return None,
697 fn detect_extreme_expr<'a>(cx: &LateContext, expr: &'a Expr) -> Option<ExtremeExpr<'a>> {
698 use rustc::middle::const_val::ConstVal::*;
699 use rustc_const_math::*;
700 use rustc_const_eval::EvalHint::ExprTypeChecked;
701 use rustc_const_eval::*;
702 use types::ExtremeType::*;
704 let ty = &cx.tcx.expr_ty(expr).sty;
707 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
711 let cv = match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
713 Err(_) => return None,
716 let which = match (ty, cv) {
717 (&ty::TyBool, Bool(false)) |
718 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MIN)))) |
719 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MIN)))) |
720 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MIN))) |
721 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MIN))) |
722 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MIN))) |
723 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MIN))) |
724 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MIN)))) |
725 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MIN)))) |
726 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MIN))) |
727 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MIN))) |
728 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MIN))) |
729 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MIN))) => Minimum,
731 (&ty::TyBool, Bool(true)) |
732 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MAX)))) |
733 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MAX)))) |
734 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MAX))) |
735 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MAX))) |
736 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MAX))) |
737 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MAX))) |
738 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MAX)))) |
739 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MAX)))) |
740 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MAX))) |
741 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MAX))) |
742 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MAX))) |
743 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MAX))) => Maximum,
753 impl LateLintPass for AbsurdExtremeComparisons {
754 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
755 use types::ExtremeType::*;
756 use types::AbsurdComparisonResult::*;
758 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
759 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
760 if !in_macro(cx, expr.span) {
761 let msg = "this comparison involving the minimum or maximum element for this \
762 type contains a case that is always true or always false";
764 let conclusion = match result {
765 AlwaysFalse => "this comparison is always false".to_owned(),
766 AlwaysTrue => "this comparison is always true".to_owned(),
767 InequalityImpossible => {
768 format!("the case where the two sides are not equal never occurs, consider using {} == {} \
770 snippet(cx, lhs.span, "lhs"),
771 snippet(cx, rhs.span, "rhs"))
775 let help = format!("because {} is the {} value for this type, {}",
776 snippet(cx, culprit.expr.span, "x"),
777 match culprit.which {
778 Minimum => "minimum",
779 Maximum => "maximum",
783 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
790 /// **What it does:** This lint checks for comparisons where the relation is always either true or false, but where one side has been upcast so that the comparison is necessary. Only integer types are checked.
792 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300` will mistakenly imply that it is possible for `x` to be outside the range of `u8`.
794 /// **Known problems:** https://github.com/Manishearth/rust-clippy/issues/886
796 /// **Example:** `let x : u8 = ...; (x as u32) > 300`
798 pub INVALID_UPCAST_COMPARISONS, Allow,
799 "a comparison involving an upcast which is always true or false"
802 pub struct InvalidUpcastComparisons;
804 impl LintPass for InvalidUpcastComparisons {
805 fn get_lints(&self) -> LintArray {
806 lint_array!(INVALID_UPCAST_COMPARISONS)
810 #[derive(Copy, Clone, Debug, Eq)]
817 #[allow(cast_sign_loss)]
818 fn cmp_s_u(s: i64, u: u64) -> Ordering {
821 } else if u > (i64::max_value() as u64) {
829 impl PartialEq for FullInt {
830 fn eq(&self, other: &Self) -> bool {
831 self.partial_cmp(other).expect("partial_cmp only returns Some(_)") == Ordering::Equal
835 impl PartialOrd for FullInt {
836 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
837 Some(match (self, other) {
838 (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
839 (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
840 (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
841 (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
845 impl Ord for FullInt {
846 fn cmp(&self, other: &Self) -> Ordering {
847 self.partial_cmp(other).expect("partial_cmp for FullInt can never return None")
852 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
853 use rustc::ty::TypeVariants::{TyInt, TyUint};
854 use syntax::ast::{IntTy, UintTy};
857 if let ExprCast(ref cast_exp, _) = expr.node {
858 match cx.tcx.expr_ty(cast_exp).sty {
861 IntTy::I8 => (FullInt::S(i8::min_value() as i64), FullInt::S(i8::max_value() as i64)),
862 IntTy::I16 => (FullInt::S(i16::min_value() as i64), FullInt::S(i16::max_value() as i64)),
863 IntTy::I32 => (FullInt::S(i32::min_value() as i64), FullInt::S(i32::max_value() as i64)),
864 IntTy::I64 => (FullInt::S(i64::min_value() as i64), FullInt::S(i64::max_value() as i64)),
865 IntTy::Is => (FullInt::S(isize::min_value() as i64), FullInt::S(isize::max_value() as i64)),
870 UintTy::U8 => (FullInt::U(u8::min_value() as u64), FullInt::U(u8::max_value() as u64)),
871 UintTy::U16 => (FullInt::U(u16::min_value() as u64), FullInt::U(u16::max_value() as u64)),
872 UintTy::U32 => (FullInt::U(u32::min_value() as u64), FullInt::U(u32::max_value() as u64)),
873 UintTy::U64 => (FullInt::U(u64::min_value() as u64), FullInt::U(u64::max_value() as u64)),
874 UintTy::Us => (FullInt::U(usize::min_value() as u64), FullInt::U(usize::max_value() as u64)),
884 fn node_as_const_fullint(cx: &LateContext, expr: &Expr) -> Option<FullInt> {
885 use rustc::middle::const_val::ConstVal::*;
886 use rustc_const_eval::EvalHint::ExprTypeChecked;
887 use rustc_const_eval::eval_const_expr_partial;
888 use rustc_const_math::ConstInt;
890 match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
892 if let Integral(const_int) = val {
893 Some(match const_int.erase_type() {
894 ConstInt::InferSigned(x) => FullInt::S(x as i64),
895 ConstInt::Infer(x) => FullInt::U(x as u64),
906 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
907 if let ExprCast(ref cast_val, _) = expr.node {
909 INVALID_UPCAST_COMPARISONS,
912 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
913 snippet(cx, cast_val.span, "the expression"),
914 if always { "true" } else { "false" },
919 fn upcast_comparison_bounds_err(cx: &LateContext, span: &Span, rel: comparisons::Rel,
920 lhs_bounds: Option<(FullInt, FullInt)>, lhs: &Expr, rhs: &Expr, invert: bool) {
921 use utils::comparisons::*;
923 if let Some((lb, ub)) = lhs_bounds {
924 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
925 if rel == Rel::Eq || rel == Rel::Ne {
926 if norm_rhs_val < lb || norm_rhs_val > ub {
927 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
929 } else if match rel {
944 Rel::Eq | Rel::Ne => unreachable!(),
946 err_upcast_comparison(cx, span, lhs, true)
947 } else if match rel {
962 Rel::Eq | Rel::Ne => unreachable!(),
964 err_upcast_comparison(cx, span, lhs, false)
970 impl LateLintPass for InvalidUpcastComparisons {
971 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
972 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
974 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
975 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
981 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
982 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
984 upcast_comparison_bounds_err(cx, &expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
985 upcast_comparison_bounds_err(cx, &expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);