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:** 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
20 /// the heap. So if you `Box` it, you just add another level of indirection
21 /// without any benefit whatsoever.
23 /// **Known problems:** None.
28 /// values: Box<Vec<Foo>>,
34 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
37 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
38 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
40 /// **Why is this bad?** Gankro says:
42 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of pointers and indirection.
43 /// > It wastes memory, it has terrible cache locality, and is all-around slow. `RingBuf`, while
44 /// > "only" amortized for push/pop, should be faster in the general case for almost every possible
45 /// > workload, and isn't even amortized at all if you can predict the capacity you need.
47 /// > `LinkedList`s are only really good if you're doing a lot of merging or splitting of lists.
48 /// > This is because they can just mangle some pointers instead of actually copying the data. Even
49 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf` can still be better
50 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
52 /// **Known problems:** False positives – the instances where using a
53 /// `LinkedList` makes sense are few and far between, but they can still happen.
57 /// let x = LinkedList::new();
62 "usage of LinkedList, usually a vector is faster, or a more specialized data \
63 structure like a VecDeque"
66 impl LintPass for TypePass {
67 fn get_lints(&self) -> LintArray {
68 lint_array!(BOX_VEC, LINKEDLIST)
72 impl LateLintPass for TypePass {
73 fn check_ty(&mut self, cx: &LateContext, ast_ty: &Ty) {
74 if in_macro(cx, ast_ty.span) {
77 if let Some(did) = cx.tcx.def_map.borrow().get(&ast_ty.id) {
78 if let def::Def::Struct(..) = did.full_def() {
79 if Some(did.full_def().def_id()) == cx.tcx.lang_items.owned_box() {
81 let TyPath(_, ref path) = ast_ty.node,
82 let Some(ref last) = path.segments.last(),
83 let PathParameters::AngleBracketedParameters(ref ag) = last.parameters,
84 let Some(ref vec) = ag.types.get(0),
85 let Some(did) = cx.tcx.def_map.borrow().get(&vec.id),
86 let def::Def::Struct(..) = did.full_def(),
87 match_def_path(cx, did.full_def().def_id(), &paths::VEC),
89 span_help_and_lint(cx,
92 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
93 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.");
95 } else if match_def_path(cx, did.full_def().def_id(), &paths::LINKED_LIST) {
96 span_help_and_lint(cx,
99 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
100 "a VecDeque might work");
107 #[allow(missing_copy_implementations)]
110 /// **What it does:** Checks for binding a unit value.
112 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
113 /// binding one is kind of pointless.
115 /// **Known problems:** None.
124 "creating a let binding to a value of unit type, which usually can't be used afterwards"
127 fn check_let_unit(cx: &LateContext, decl: &Decl) {
128 if let DeclLocal(ref local) = decl.node {
129 let bindtype = &cx.tcx.pat_ty(&local.pat).sty;
131 ty::TyTuple(slice) if slice.is_empty() => {
132 if in_external_macro(cx, decl.span) || in_macro(cx, local.pat.span) {
135 if higher::is_from_for_desugar(decl) {
141 &format!("this let-binding has unit value. Consider omitting `let {} =`",
142 snippet(cx, local.pat.span, "..")));
149 impl LintPass for LetPass {
150 fn get_lints(&self) -> LintArray {
151 lint_array!(LET_UNIT_VALUE)
155 impl LateLintPass for LetPass {
156 fn check_decl(&mut self, cx: &LateContext, decl: &Decl) {
157 check_let_unit(cx, decl)
161 /// **What it does:** Checks for comparisons to unit.
163 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
164 /// clumsily written constant. Mostly this happens when someone accidentally
165 /// adds semicolons at the end of the operands.
167 /// **Known problems:** None.
171 /// if { foo(); } == { bar(); } { baz(); }
175 /// { foo(); bar(); baz(); }
180 "comparing unit values"
183 #[allow(missing_copy_implementations)]
186 impl LintPass for UnitCmp {
187 fn get_lints(&self) -> LintArray {
188 lint_array!(UNIT_CMP)
192 impl LateLintPass for UnitCmp {
193 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
194 if in_macro(cx, expr.span) {
197 if let ExprBinary(ref cmp, ref left, _) = expr.node {
199 if op.is_comparison() {
200 let sty = &cx.tcx.expr_ty(left).sty;
202 ty::TyTuple(slice) if slice.is_empty() => {
203 let result = match op {
204 BiEq | BiLe | BiGe => "true",
210 &format!("{}-comparison of unit values detected. This will always be {}",
223 /// **What it does:** Checks for casts from any numerical to a float type where
224 /// the receiving type cannot store all values from the original type without
225 /// rounding errors. This possible rounding is to be expected, so this lint is
226 /// `Allow` by default.
228 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
229 /// or any 64-bit integer to `f64`.
231 /// **Why is this bad?** It's not bad at all. But in some applications it can be
232 /// helpful to know where precision loss can take place. This lint can help find
233 /// those places in the code.
235 /// **Known problems:** None.
239 /// let x = u64::MAX; x as f64
242 pub CAST_PRECISION_LOSS,
244 "casts that cause loss of precision, e.g `x as f32` where `x: u64`"
247 /// **What it does:** Checks for casts from a signed to an unsigned numerical
248 /// type. In this case, negative values wrap around to large positive values,
249 /// which can be quite surprising in practice. However, as the cast works as
250 /// defined, this lint is `Allow` by default.
252 /// **Why is this bad?** Possibly surprising results. You can activate this lint
253 /// as a one-time check to see where numerical wrapping can arise.
255 /// **Known problems:** None.
260 /// y as u64 // will return 18446744073709551615
265 "casts from signed types to unsigned types, e.g `x as u32` where `x: i32`"
268 /// **What it does:** Checks for on casts between numerical types that may
269 /// truncate large values. This is expected behavior, so the cast is `Allow` by
272 /// **Why is this bad?** In some problem domains, it is good practice to avoid
273 /// truncation. This lint can be activated to help assess where additional
274 /// checks could be beneficial.
276 /// **Known problems:** None.
280 /// fn as_u8(x: u64) -> u8 { x as u8 }
283 pub CAST_POSSIBLE_TRUNCATION,
285 "casts that may cause truncation of the value, e.g `x as u8` where `x: u32`, \
286 or `x as i32` where `x: f32`"
289 /// **What it does:** Checks for casts from an unsigned type to a signed type of
290 /// the same size. Performing such a cast is a 'no-op' for the compiler,
291 /// i.e. nothing is changed at the bit level, and the binary representation of
292 /// the value is reinterpreted. This can cause wrapping if the value is too big
293 /// for the target signed type. However, the cast works as defined, so this lint
294 /// is `Allow` by default.
296 /// **Why is this bad?** While such a cast is not bad in itself, the results can
297 /// be surprising when this is not the intended behavior, as demonstrated by the
300 /// **Known problems:** None.
304 /// u32::MAX as i32 // will yield a value of `-1`
307 pub CAST_POSSIBLE_WRAP,
309 "casts that may cause wrapping around the value, e.g `x as i32` where `x: u32` \
313 /// Returns the size in bits of an integral type.
314 /// Will return 0 if the type is not an int or uint variant
315 fn int_ty_to_nbits(typ: &ty::TyS) -> usize {
316 let n = match typ.sty {
317 ty::TyInt(i) => 4 << (i as usize),
318 ty::TyUint(u) => 4 << (u as usize),
321 // n == 4 is the usize/isize case
323 ::std::mem::size_of::<usize>() * 8
329 fn is_isize_or_usize(typ: &ty::TyS) -> bool {
331 ty::TyInt(IntTy::Is) |
332 ty::TyUint(UintTy::Us) => true,
337 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to_f64: bool) {
338 let mantissa_nbits = if cast_to_f64 {
343 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
344 let arch_dependent_str = "on targets with 64-bit wide pointers ";
345 let from_nbits_str = if arch_dependent {
347 } else if is_isize_or_usize(cast_from) {
348 "32 or 64".to_owned()
350 int_ty_to_nbits(cast_from).to_string()
355 &format!("casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
356 is only {4} bits wide)",
378 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to: &ty::TyS) {
379 let arch_64_suffix = " on targets with 64-bit wide pointers";
380 let arch_32_suffix = " on targets with 32-bit wide pointers";
381 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
382 let (from_nbits, to_nbits) = (int_ty_to_nbits(cast_from), int_ty_to_nbits(cast_to));
383 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) = match (is_isize_or_usize(cast_from),
384 is_isize_or_usize(cast_to)) {
385 (true, true) | (false, false) => {
386 (to_nbits < from_nbits,
388 to_nbits == from_nbits && cast_unsigned_to_signed,
398 to_nbits <= 32 && cast_unsigned_to_signed,
404 cast_unsigned_to_signed,
405 if from_nbits == 64 {
414 CAST_POSSIBLE_TRUNCATION,
416 &format!("casting {} to {} may truncate the value{}",
419 match suffix_truncation {
420 ArchSuffix::_32 => arch_32_suffix,
421 ArchSuffix::_64 => arch_64_suffix,
422 ArchSuffix::None => "",
429 &format!("casting {} to {} may wrap around the value{}",
433 ArchSuffix::_32 => arch_32_suffix,
434 ArchSuffix::_64 => arch_64_suffix,
435 ArchSuffix::None => "",
440 impl LintPass for CastPass {
441 fn get_lints(&self) -> LintArray {
442 lint_array!(CAST_PRECISION_LOSS,
444 CAST_POSSIBLE_TRUNCATION,
449 impl LateLintPass for CastPass {
450 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
451 if let ExprCast(ref ex, _) = expr.node {
452 let (cast_from, cast_to) = (cx.tcx.expr_ty(ex), cx.tcx.expr_ty(expr));
453 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
454 match (cast_from.is_integral(), cast_to.is_integral()) {
456 let from_nbits = int_ty_to_nbits(cast_from);
457 let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
462 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
463 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
468 CAST_POSSIBLE_TRUNCATION,
470 &format!("casting {} to {} may truncate the value", cast_from, cast_to));
471 if !cast_to.is_signed() {
475 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
479 if cast_from.is_signed() && !cast_to.is_signed() {
483 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
485 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
488 if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty,
491 CAST_POSSIBLE_TRUNCATION,
493 "casting f64 to f32 may truncate the value");
502 /// **What it does:** Checks for types used in structs, parameters and `let`
503 /// declarations above a certain complexity threshold.
505 /// **Why is this bad?** Too complex types make the code less readable. Consider
506 /// using a `type` definition to simplify them.
508 /// **Known problems:** None.
512 /// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
517 "usage of very complex types that might be better factored into `type` definitions"
520 #[allow(missing_copy_implementations)]
521 pub struct TypeComplexityPass {
525 impl TypeComplexityPass {
526 pub fn new(threshold: u64) -> Self {
527 TypeComplexityPass { threshold: threshold }
531 impl LintPass for TypeComplexityPass {
532 fn get_lints(&self) -> LintArray {
533 lint_array!(TYPE_COMPLEXITY)
537 impl LateLintPass for TypeComplexityPass {
538 fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
539 self.check_fndecl(cx, decl);
542 fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
543 // enum variants are also struct fields now
544 self.check_type(cx, &field.ty);
547 fn check_item(&mut self, cx: &LateContext, item: &Item) {
549 ItemStatic(ref ty, _, _) |
550 ItemConst(ref ty, _) => self.check_type(cx, ty),
551 // functions, enums, structs, impls and traits are covered
556 fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
558 ConstTraitItem(ref ty, _) |
559 TypeTraitItem(_, Some(ref ty)) => self.check_type(cx, ty),
560 MethodTraitItem(MethodSig { ref decl, .. }, None) => self.check_fndecl(cx, decl),
561 // methods with default impl are covered by check_fn
566 fn check_impl_item(&mut self, cx: &LateContext, item: &ImplItem) {
568 ImplItemKind::Const(ref ty, _) |
569 ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
570 // methods are covered by check_fn
575 fn check_local(&mut self, cx: &LateContext, local: &Local) {
576 if let Some(ref ty) = local.ty {
577 self.check_type(cx, ty);
582 impl TypeComplexityPass {
583 fn check_fndecl(&self, cx: &LateContext, decl: &FnDecl) {
584 for arg in &decl.inputs {
585 self.check_type(cx, &arg.ty);
587 if let Return(ref ty) = decl.output {
588 self.check_type(cx, ty);
592 fn check_type(&self, cx: &LateContext, ty: &Ty) {
593 if in_macro(cx, ty.span) {
597 let mut visitor = TypeComplexityVisitor {
601 visitor.visit_ty(ty);
605 if score > self.threshold {
609 "very complex type used. Consider factoring parts into `type` definitions");
614 /// Walks a type and assigns a complexity score to it.
615 struct TypeComplexityVisitor {
616 /// total complexity score of the type
618 /// current nesting level
622 impl<'v> Visitor<'v> for TypeComplexityVisitor {
623 fn visit_ty(&mut self, ty: &'v Ty) {
624 let (add_score, sub_nest) = match ty.node {
625 // _, &x and *x have only small overhead; don't mess with nesting level
626 TyInfer | TyPtr(..) | TyRptr(..) => (1, 0),
628 // the "normal" components of a type: named types, arrays/tuples
632 TyFixedLengthVec(..) => (10 * self.nest, 1),
634 // "Sum" of trait bounds
635 TyObjectSum(..) => (20 * self.nest, 0),
637 // function types and "for<...>" bring a lot of overhead
639 TyPolyTraitRef(..) => (50 * self.nest, 1),
643 self.score += add_score;
644 self.nest += sub_nest;
646 self.nest -= sub_nest;
650 /// **What it does:** Checks for expressions where a character literal is cast
651 /// to `u8` and suggests using a byte literal instead.
653 /// **Why is this bad?** In general, casting values to smaller types is
654 /// error-prone and should be avoided where possible. In the particular case of
655 /// converting a character literal to u8, it is easy to avoid by just using a
656 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
657 /// than `'a' as u8`.
659 /// **Known problems:** None.
668 "casting a character literal to u8"
671 pub struct CharLitAsU8;
673 impl LintPass for CharLitAsU8 {
674 fn get_lints(&self) -> LintArray {
675 lint_array!(CHAR_LIT_AS_U8)
679 impl LateLintPass for CharLitAsU8 {
680 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
681 use syntax::ast::{LitKind, UintTy};
683 if let ExprCast(ref e, _) = expr.node {
684 if let ExprLit(ref l) = e.node {
685 if let LitKind::Char(_) = l.node {
686 if ty::TyUint(UintTy::U8) == cx.tcx.expr_ty(expr).sty && !in_macro(cx, expr.span) {
687 let msg = "casting character literal to u8. `char`s \
688 are 4 bytes wide in rust, so casting to u8 \
690 let help = format!("Consider using a byte literal \
692 snippet(cx, e.span, "'x'"));
693 span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
701 /// **What it does:** Checks for comparisons where one side of the relation is
702 /// either the minimum or maximum value for its type and warns if it involves a
703 /// case that is always true or always false. Only integer and boolean types are
706 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
707 /// that is is possible for `x` to be less than the minimum. Expressions like
708 /// `max < x` are probably mistakes.
710 /// **Known problems:** None.
715 /// 100 > std::i32::MAX
718 pub ABSURD_EXTREME_COMPARISONS,
720 "a comparison with a maximum or minimum value that is always true or false"
723 pub struct AbsurdExtremeComparisons;
725 impl LintPass for AbsurdExtremeComparisons {
726 fn get_lints(&self) -> LintArray {
727 lint_array!(ABSURD_EXTREME_COMPARISONS)
736 struct ExtremeExpr<'a> {
741 enum AbsurdComparisonResult {
744 InequalityImpossible,
749 fn detect_absurd_comparison<'a>(cx: &LateContext, op: BinOp_, lhs: &'a Expr, rhs: &'a Expr)
750 -> Option<(ExtremeExpr<'a>, AbsurdComparisonResult)> {
751 use types::ExtremeType::*;
752 use types::AbsurdComparisonResult::*;
753 use utils::comparisons::*;
754 type Extr<'a> = ExtremeExpr<'a>;
756 let normalized = normalize_comparison(op, lhs, rhs);
757 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
763 let lx = detect_extreme_expr(cx, normalized_lhs);
764 let rx = detect_extreme_expr(cx, normalized_rhs);
769 (Some(l @ Extr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
770 (_, Some(r @ Extr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
776 (Some(l @ Extr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
777 (Some(l @ Extr { which: Maximum, .. }), _) => (l, InequalityImpossible), //max <= x
778 (_, Some(r @ Extr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
779 (_, Some(r @ Extr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
783 Rel::Ne | Rel::Eq => return None,
787 fn detect_extreme_expr<'a>(cx: &LateContext, expr: &'a Expr) -> Option<ExtremeExpr<'a>> {
788 use rustc::middle::const_val::ConstVal::*;
789 use rustc_const_math::*;
790 use rustc_const_eval::EvalHint::ExprTypeChecked;
791 use rustc_const_eval::*;
792 use types::ExtremeType::*;
794 let ty = &cx.tcx.expr_ty(expr).sty;
797 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
801 let cv = match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
803 Err(_) => return None,
806 let which = match (ty, cv) {
807 (&ty::TyBool, Bool(false)) |
808 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MIN)))) |
809 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MIN)))) |
810 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MIN))) |
811 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MIN))) |
812 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MIN))) |
813 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MIN))) |
814 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MIN)))) |
815 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MIN)))) |
816 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MIN))) |
817 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MIN))) |
818 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MIN))) |
819 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MIN))) => Minimum,
821 (&ty::TyBool, Bool(true)) |
822 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MAX)))) |
823 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MAX)))) |
824 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MAX))) |
825 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MAX))) |
826 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MAX))) |
827 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MAX))) |
828 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MAX)))) |
829 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MAX)))) |
830 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MAX))) |
831 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MAX))) |
832 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MAX))) |
833 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MAX))) => Maximum,
843 impl LateLintPass for AbsurdExtremeComparisons {
844 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
845 use types::ExtremeType::*;
846 use types::AbsurdComparisonResult::*;
848 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
849 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
850 if !in_macro(cx, expr.span) {
851 let msg = "this comparison involving the minimum or maximum element for this \
852 type contains a case that is always true or always false";
854 let conclusion = match result {
855 AlwaysFalse => "this comparison is always false".to_owned(),
856 AlwaysTrue => "this comparison is always true".to_owned(),
857 InequalityImpossible => {
858 format!("the case where the two sides are not equal never occurs, consider using {} == {} \
860 snippet(cx, lhs.span, "lhs"),
861 snippet(cx, rhs.span, "rhs"))
865 let help = format!("because {} is the {} value for this type, {}",
866 snippet(cx, culprit.expr.span, "x"),
867 match culprit.which {
868 Minimum => "minimum",
869 Maximum => "maximum",
873 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
880 /// **What it does:** Checks for comparisons where the relation is always either
881 /// true or false, but where one side has been upcast so that the comparison is
882 /// necessary. Only integer types are checked.
884 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
885 /// will mistakenly imply that it is possible for `x` to be outside the range of
888 /// **Known problems:** https://github.com/Manishearth/rust-clippy/issues/886
892 /// let x : u8 = ...; (x as u32) > 300
895 pub INVALID_UPCAST_COMPARISONS,
897 "a comparison involving an upcast which is always true or false"
900 pub struct InvalidUpcastComparisons;
902 impl LintPass for InvalidUpcastComparisons {
903 fn get_lints(&self) -> LintArray {
904 lint_array!(INVALID_UPCAST_COMPARISONS)
908 #[derive(Copy, Clone, Debug, Eq)]
915 #[allow(cast_sign_loss)]
916 fn cmp_s_u(s: i64, u: u64) -> Ordering {
919 } else if u > (i64::max_value() as u64) {
927 impl PartialEq for FullInt {
928 fn eq(&self, other: &Self) -> bool {
929 self.partial_cmp(other).expect("partial_cmp only returns Some(_)") == Ordering::Equal
933 impl PartialOrd for FullInt {
934 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
935 Some(match (self, other) {
936 (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
937 (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
938 (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
939 (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
943 impl Ord for FullInt {
944 fn cmp(&self, other: &Self) -> Ordering {
945 self.partial_cmp(other).expect("partial_cmp for FullInt can never return None")
950 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
951 use rustc::ty::TypeVariants::{TyInt, TyUint};
952 use syntax::ast::{IntTy, UintTy};
955 if let ExprCast(ref cast_exp, _) = expr.node {
956 match cx.tcx.expr_ty(cast_exp).sty {
959 IntTy::I8 => (FullInt::S(i8::min_value() as i64), FullInt::S(i8::max_value() as i64)),
960 IntTy::I16 => (FullInt::S(i16::min_value() as i64), FullInt::S(i16::max_value() as i64)),
961 IntTy::I32 => (FullInt::S(i32::min_value() as i64), FullInt::S(i32::max_value() as i64)),
962 IntTy::I64 => (FullInt::S(i64::min_value() as i64), FullInt::S(i64::max_value() as i64)),
963 IntTy::Is => (FullInt::S(isize::min_value() as i64), FullInt::S(isize::max_value() as i64)),
968 UintTy::U8 => (FullInt::U(u8::min_value() as u64), FullInt::U(u8::max_value() as u64)),
969 UintTy::U16 => (FullInt::U(u16::min_value() as u64), FullInt::U(u16::max_value() as u64)),
970 UintTy::U32 => (FullInt::U(u32::min_value() as u64), FullInt::U(u32::max_value() as u64)),
971 UintTy::U64 => (FullInt::U(u64::min_value() as u64), FullInt::U(u64::max_value() as u64)),
972 UintTy::Us => (FullInt::U(usize::min_value() as u64), FullInt::U(usize::max_value() as u64)),
982 fn node_as_const_fullint(cx: &LateContext, expr: &Expr) -> Option<FullInt> {
983 use rustc::middle::const_val::ConstVal::*;
984 use rustc_const_eval::EvalHint::ExprTypeChecked;
985 use rustc_const_eval::eval_const_expr_partial;
986 use rustc_const_math::ConstInt;
988 match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
990 if let Integral(const_int) = val {
991 Some(match const_int.erase_type() {
992 ConstInt::InferSigned(x) => FullInt::S(x as i64),
993 ConstInt::Infer(x) => FullInt::U(x as u64),
1004 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
1005 if let ExprCast(ref cast_val, _) = expr.node {
1007 INVALID_UPCAST_COMPARISONS,
1010 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1011 snippet(cx, cast_val.span, "the expression"),
1012 if always { "true" } else { "false" },
1017 fn upcast_comparison_bounds_err(cx: &LateContext, span: &Span, rel: comparisons::Rel,
1018 lhs_bounds: Option<(FullInt, FullInt)>, lhs: &Expr, rhs: &Expr, invert: bool) {
1019 use utils::comparisons::*;
1021 if let Some((lb, ub)) = lhs_bounds {
1022 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1023 if rel == Rel::Eq || rel == Rel::Ne {
1024 if norm_rhs_val < lb || norm_rhs_val > ub {
1025 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1027 } else if match rel {
1042 Rel::Eq | Rel::Ne => unreachable!(),
1044 err_upcast_comparison(cx, span, lhs, true)
1045 } else if match rel {
1060 Rel::Eq | Rel::Ne => unreachable!(),
1062 err_upcast_comparison(cx, span, lhs, false)
1068 impl LateLintPass for InvalidUpcastComparisons {
1069 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
1070 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1072 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1073 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1079 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1080 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1082 upcast_comparison_bounds_err(cx, &expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1083 upcast_comparison_bounds_err(cx, &expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);