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, in_external_macro, in_macro, is_from_for_desugar, 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 `Box` it, you just add another level of indirection without any benefit whatsoever.
21 /// **Known problems:** None
23 /// **Example:** `struct X { values: Box<Vec<Foo>> }`
26 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
29 /// **What it does:** This lint checks for usage of any `LinkedList`, suggesting to use a `Vec` or a `VecDeque` (formerly called `RingBuf`).
31 /// **Why is this bad?** Gankro says:
33 /// >The TL;DR of `LinkedList` is that it's built on a massive amount of pointers and indirection. It wastes memory, it has terrible cache locality, and is all-around slow. `RingBuf`, while "only" amortized for push/pop, should be faster in the general case for almost every possible workload, and isn't even amortized at all if you can predict the capacity you need.
35 /// > `LinkedList`s are only really good if you're doing a lot of merging or splitting of lists. This is because they can just mangle some pointers instead of actually copying the data. Even if you're doing a lot of insertion in the middle of the list, `RingBuf` can still be better because of how expensive it is to seek to the middle of a `LinkedList`.
37 /// **Known problems:** False positives – the instances where using a `LinkedList` makes sense are few and far between, but they can still happen.
39 /// **Example:** `let x = LinkedList::new();`
42 "usage of LinkedList, usually a vector is faster, or a more specialized data \
43 structure like a VecDeque"
46 impl LintPass for TypePass {
47 fn get_lints(&self) -> LintArray {
48 lint_array!(BOX_VEC, LINKEDLIST)
52 impl LateLintPass for TypePass {
53 fn check_ty(&mut self, cx: &LateContext, ast_ty: &Ty) {
54 if in_macro(cx, ast_ty.span) {
57 if let Some(did) = cx.tcx.def_map.borrow().get(&ast_ty.id) {
58 if let def::Def::Struct(..) = did.full_def() {
59 if Some(did.def_id()) == cx.tcx.lang_items.owned_box() {
62 let TyPath(_, ref path) = ast_ty.node,
63 let Some(ref last) = path.segments.last(),
64 let PathParameters::AngleBracketedParameters(ref ag) = last.parameters,
65 let Some(ref vec) = ag.types.get(0),
66 let Some(did) = cx.tcx.def_map.borrow().get(&vec.id),
67 let def::Def::Struct(..) = did.full_def(),
68 match_def_path(cx, did.def_id(), &paths::VEC),
71 span_help_and_lint(cx,
74 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
75 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.");
78 } else if match_def_path(cx, did.def_id(), &paths::LINKED_LIST) {
79 span_help_and_lint(cx,
82 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
83 "a VecDeque might work");
90 #[allow(missing_copy_implementations)]
93 /// **What it does:** This lint checks for binding a unit value.
95 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So binding one is kind of pointless.
97 /// **Known problems:** None
99 /// **Example:** `let x = { 1; };`
101 pub LET_UNIT_VALUE, Warn,
102 "creating a let binding to a value of unit type, which usually can't be used afterwards"
105 fn check_let_unit(cx: &LateContext, decl: &Decl) {
106 if let DeclLocal(ref local) = decl.node {
107 let bindtype = &cx.tcx.pat_ty(&local.pat).sty;
108 if *bindtype == ty::TyTuple(&[]) {
109 if in_external_macro(cx, decl.span) || in_macro(cx, local.pat.span) {
112 if is_from_for_desugar(decl) {
118 &format!("this let-binding has unit value. Consider omitting `let {} =`",
119 snippet(cx, local.pat.span, "..")));
124 impl LintPass for LetPass {
125 fn get_lints(&self) -> LintArray {
126 lint_array!(LET_UNIT_VALUE)
130 impl LateLintPass for LetPass {
131 fn check_decl(&mut self, cx: &LateContext, decl: &Decl) {
132 check_let_unit(cx, decl)
136 /// **What it does:** This lint checks for comparisons to unit.
138 /// **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.
140 /// **Known problems:** None
142 /// **Example:** `if { foo(); } == { bar(); } { baz(); }` is equal to `{ foo(); bar(); baz(); }`
145 "comparing unit values (which is always `true` or `false`, respectively)"
148 #[allow(missing_copy_implementations)]
151 impl LintPass for UnitCmp {
152 fn get_lints(&self) -> LintArray {
153 lint_array!(UNIT_CMP)
157 impl LateLintPass for UnitCmp {
158 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
159 if in_macro(cx, expr.span) {
162 if let ExprBinary(ref cmp, ref left, _) = expr.node {
164 let sty = &cx.tcx.expr_ty(left).sty;
165 if *sty == ty::TyTuple(&[]) && op.is_comparison() {
166 let result = match op {
167 BiEq | BiLe | BiGe => "true",
173 &format!("{}-comparison of unit values detected. This will always be {}",
183 /// **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.
185 /// Basically, this warns on casting any integer with 32 or more bits to `f32` or any 64-bit integer to `f64`.
187 /// **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.
189 /// **Known problems:** None
191 /// **Example:** `let x = u64::MAX; x as f64`
193 pub CAST_PRECISION_LOSS, Allow,
194 "casts that cause loss of precision, e.g `x as f32` where `x: u64`"
197 /// **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.
199 /// **Why is this bad?** Possibly surprising results. You can activate this lint as a one-time check to see where numerical wrapping can arise.
201 /// **Known problems:** None
203 /// **Example:** `let y : i8 = -1; y as u64` will return 18446744073709551615
205 pub CAST_SIGN_LOSS, Allow,
206 "casts from signed types to unsigned types, e.g `x as u32` where `x: i32`"
209 /// **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.
211 /// **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.
213 /// **Known problems:** None
215 /// **Example:** `fn as_u8(x: u64) -> u8 { x as u8 }`
217 pub CAST_POSSIBLE_TRUNCATION, Allow,
218 "casts that may cause truncation of the value, e.g `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
221 /// **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.
223 /// **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.
225 /// **Known problems:** None
227 /// **Example:** `u32::MAX as i32` will yield a value of `-1`.
229 pub CAST_POSSIBLE_WRAP, Allow,
230 "casts that may cause wrapping around the value, e.g `x as i32` where `x: u32` and `x > i32::MAX`"
233 /// Returns the size in bits of an integral type.
234 /// Will return 0 if the type is not an int or uint variant
235 fn int_ty_to_nbits(typ: &ty::TyS) -> usize {
236 let n = match typ.sty {
237 ty::TyInt(i) => 4 << (i as usize),
238 ty::TyUint(u) => 4 << (u as usize),
241 // n == 4 is the usize/isize case
243 ::std::mem::size_of::<usize>() * 8
249 fn is_isize_or_usize(typ: &ty::TyS) -> bool {
251 ty::TyInt(IntTy::Is) |
252 ty::TyUint(UintTy::Us) => true,
257 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to_f64: bool) {
258 let mantissa_nbits = if cast_to_f64 {
263 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
264 let arch_dependent_str = "on targets with 64-bit wide pointers ";
265 let from_nbits_str = if arch_dependent {
267 } else if is_isize_or_usize(cast_from) {
268 "32 or 64".to_owned()
270 int_ty_to_nbits(cast_from).to_string()
275 &format!("casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
276 is only {4} bits wide)",
298 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to: &ty::TyS) {
299 let arch_64_suffix = " on targets with 64-bit wide pointers";
300 let arch_32_suffix = " on targets with 32-bit wide pointers";
301 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
302 let (from_nbits, to_nbits) = (int_ty_to_nbits(cast_from), int_ty_to_nbits(cast_to));
303 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) = match (is_isize_or_usize(cast_from),
304 is_isize_or_usize(cast_to)) {
305 (true, true) | (false, false) => {
306 (to_nbits < from_nbits,
308 to_nbits == from_nbits && cast_unsigned_to_signed,
318 to_nbits <= 32 && cast_unsigned_to_signed,
324 cast_unsigned_to_signed,
325 if from_nbits == 64 {
334 CAST_POSSIBLE_TRUNCATION,
336 &format!("casting {} to {} may truncate the value{}",
339 match suffix_truncation {
340 ArchSuffix::_32 => arch_32_suffix,
341 ArchSuffix::_64 => arch_64_suffix,
342 ArchSuffix::None => "",
349 &format!("casting {} to {} may wrap around the value{}",
353 ArchSuffix::_32 => arch_32_suffix,
354 ArchSuffix::_64 => arch_64_suffix,
355 ArchSuffix::None => "",
360 impl LintPass for CastPass {
361 fn get_lints(&self) -> LintArray {
362 lint_array!(CAST_PRECISION_LOSS,
364 CAST_POSSIBLE_TRUNCATION,
369 impl LateLintPass for CastPass {
370 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
371 if let ExprCast(ref ex, _) = expr.node {
372 let (cast_from, cast_to) = (cx.tcx.expr_ty(ex), cx.tcx.expr_ty(expr));
373 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
374 match (cast_from.is_integral(), cast_to.is_integral()) {
376 let from_nbits = int_ty_to_nbits(cast_from);
377 let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
382 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
383 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
388 CAST_POSSIBLE_TRUNCATION,
390 &format!("casting {} to {} may truncate the value", cast_from, cast_to));
391 if !cast_to.is_signed() {
395 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
399 if cast_from.is_signed() && !cast_to.is_signed() {
403 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
405 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
408 if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty,
411 CAST_POSSIBLE_TRUNCATION,
413 "casting f64 to f32 may truncate the value");
422 /// **What it does:** This lint checks for types used in structs, parameters and `let` declarations above a certain complexity threshold.
424 /// **Why is this bad?** Too complex types make the code less readable. Consider using a `type` definition to simplify them.
426 /// **Known problems:** None
428 /// **Example:** `struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }`
430 pub TYPE_COMPLEXITY, Warn,
431 "usage of very complex types; recommends factoring out parts into `type` definitions"
434 #[allow(missing_copy_implementations)]
435 pub struct TypeComplexityPass {
439 impl TypeComplexityPass {
440 pub fn new(threshold: u64) -> Self {
441 TypeComplexityPass { threshold: threshold }
445 impl LintPass for TypeComplexityPass {
446 fn get_lints(&self) -> LintArray {
447 lint_array!(TYPE_COMPLEXITY)
451 impl LateLintPass for TypeComplexityPass {
452 fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
453 self.check_fndecl(cx, decl);
456 fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
457 // enum variants are also struct fields now
458 self.check_type(cx, &field.ty);
461 fn check_item(&mut self, cx: &LateContext, item: &Item) {
463 ItemStatic(ref ty, _, _) |
464 ItemConst(ref ty, _) => self.check_type(cx, ty),
465 // functions, enums, structs, impls and traits are covered
470 fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
472 ConstTraitItem(ref ty, _) |
473 TypeTraitItem(_, Some(ref ty)) => self.check_type(cx, ty),
474 MethodTraitItem(MethodSig { ref decl, .. }, None) => self.check_fndecl(cx, decl),
475 // methods with default impl are covered by check_fn
480 fn check_impl_item(&mut self, cx: &LateContext, item: &ImplItem) {
482 ImplItemKind::Const(ref ty, _) |
483 ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
484 // methods are covered by check_fn
489 fn check_local(&mut self, cx: &LateContext, local: &Local) {
490 if let Some(ref ty) = local.ty {
491 self.check_type(cx, ty);
496 impl TypeComplexityPass {
497 fn check_fndecl(&self, cx: &LateContext, decl: &FnDecl) {
498 for arg in &decl.inputs {
499 self.check_type(cx, &arg.ty);
501 if let Return(ref ty) = decl.output {
502 self.check_type(cx, ty);
506 fn check_type(&self, cx: &LateContext, ty: &Ty) {
507 if in_macro(cx, ty.span) {
511 let mut visitor = TypeComplexityVisitor {
515 visitor.visit_ty(ty);
519 if score > self.threshold {
523 "very complex type used. Consider factoring parts into `type` definitions");
528 /// Walks a type and assigns a complexity score to it.
529 struct TypeComplexityVisitor {
530 /// total complexity score of the type
532 /// current nesting level
536 impl<'v> Visitor<'v> for TypeComplexityVisitor {
537 fn visit_ty(&mut self, ty: &'v Ty) {
538 let (add_score, sub_nest) = match ty.node {
539 // _, &x and *x have only small overhead; don't mess with nesting level
540 TyInfer | TyPtr(..) | TyRptr(..) => (1, 0),
542 // the "normal" components of a type: named types, arrays/tuples
546 TyFixedLengthVec(..) => (10 * self.nest, 1),
548 // "Sum" of trait bounds
549 TyObjectSum(..) => (20 * self.nest, 0),
551 // function types and "for<...>" bring a lot of overhead
553 TyPolyTraitRef(..) => (50 * self.nest, 1),
557 self.score += add_score;
558 self.nest += sub_nest;
560 self.nest -= sub_nest;
564 /// **What it does:** This lint points out expressions where a character literal is casted to `u8` and suggests using a byte literal instead.
566 /// **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`.
568 /// **Known problems:** None
570 /// **Example:** `'x' as u8`
572 pub CHAR_LIT_AS_U8, Warn,
573 "Casting a character literal to u8"
576 pub struct CharLitAsU8;
578 impl LintPass for CharLitAsU8 {
579 fn get_lints(&self) -> LintArray {
580 lint_array!(CHAR_LIT_AS_U8)
584 impl LateLintPass for CharLitAsU8 {
585 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
586 use syntax::ast::{LitKind, UintTy};
588 if let ExprCast(ref e, _) = expr.node {
589 if let ExprLit(ref l) = e.node {
590 if let LitKind::Char(_) = l.node {
591 if ty::TyUint(UintTy::U8) == cx.tcx.expr_ty(expr).sty && !in_macro(cx, expr.span) {
592 let msg = "casting character literal to u8. `char`s \
593 are 4 bytes wide in rust, so casting to u8 \
595 let help = format!("Consider using a byte literal \
597 snippet(cx, e.span, "'x'"));
598 span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
606 /// **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.
608 /// **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.
610 /// **Known problems:** None
612 /// **Example:** `vec.len() <= 0`, `100 > std::i32::MAX`
614 pub ABSURD_EXTREME_COMPARISONS, Warn,
615 "a comparison involving a maximum or minimum value involves a case that is always \
616 true or always false"
619 pub struct AbsurdExtremeComparisons;
621 impl LintPass for AbsurdExtremeComparisons {
622 fn get_lints(&self) -> LintArray {
623 lint_array!(ABSURD_EXTREME_COMPARISONS)
632 struct ExtremeExpr<'a> {
637 enum AbsurdComparisonResult {
640 InequalityImpossible,
645 fn detect_absurd_comparison<'a>(cx: &LateContext, op: BinOp_, lhs: &'a Expr, rhs: &'a Expr)
646 -> Option<(ExtremeExpr<'a>, AbsurdComparisonResult)> {
647 use types::ExtremeType::*;
648 use types::AbsurdComparisonResult::*;
649 use utils::comparisons::*;
650 type Extr<'a> = ExtremeExpr<'a>;
652 let normalized = normalize_comparison(op, lhs, rhs);
653 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
659 let lx = detect_extreme_expr(cx, normalized_lhs);
660 let rx = detect_extreme_expr(cx, normalized_rhs);
665 (Some(l @ Extr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
666 (_, Some(r @ Extr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
672 (Some(l @ Extr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
673 (Some(l @ Extr { which: Maximum, .. }), _) => (l, InequalityImpossible), //max <= x
674 (_, Some(r @ Extr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
675 (_, Some(r @ Extr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
679 Rel::Ne | Rel::Eq => return None,
683 fn detect_extreme_expr<'a>(cx: &LateContext, expr: &'a Expr) -> Option<ExtremeExpr<'a>> {
684 use rustc::middle::const_val::ConstVal::*;
685 use rustc_const_math::*;
686 use rustc_const_eval::EvalHint::ExprTypeChecked;
687 use rustc_const_eval::*;
688 use types::ExtremeType::*;
690 let ty = &cx.tcx.expr_ty(expr).sty;
693 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
697 let cv = match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
699 Err(_) => return None,
702 let which = match (ty, cv) {
703 (&ty::TyBool, Bool(false)) |
704 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MIN)))) |
705 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MIN)))) |
706 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MIN))) |
707 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MIN))) |
708 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MIN))) |
709 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MIN))) |
710 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MIN)))) |
711 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MIN)))) |
712 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MIN))) |
713 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MIN))) |
714 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MIN))) |
715 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MIN))) => Minimum,
717 (&ty::TyBool, Bool(true)) |
718 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MAX)))) |
719 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MAX)))) |
720 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MAX))) |
721 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MAX))) |
722 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MAX))) |
723 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MAX))) |
724 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MAX)))) |
725 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MAX)))) |
726 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MAX))) |
727 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MAX))) |
728 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MAX))) |
729 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MAX))) => Maximum,
739 impl LateLintPass for AbsurdExtremeComparisons {
740 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
741 use types::ExtremeType::*;
742 use types::AbsurdComparisonResult::*;
744 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
745 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
746 if !in_macro(cx, expr.span) {
747 let msg = "this comparison involving the minimum or maximum element for this \
748 type contains a case that is always true or always false";
750 let conclusion = match result {
751 AlwaysFalse => "this comparison is always false".to_owned(),
752 AlwaysTrue => "this comparison is always true".to_owned(),
753 InequalityImpossible => {
754 format!("the case where the two sides are not equal never occurs, consider using {} == {} \
756 snippet(cx, lhs.span, "lhs"),
757 snippet(cx, rhs.span, "rhs"))
761 let help = format!("because {} is the {} value for this type, {}",
762 snippet(cx, culprit.expr.span, "x"),
763 match culprit.which {
764 Minimum => "minimum",
765 Maximum => "maximum",
769 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
776 /// **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.
778 /// **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`.
780 /// **Known problems:** None
782 /// **Example:** `let x : u8 = ...; (x as u32) > 300`
784 pub INVALID_UPCAST_COMPARISONS, Warn,
785 "a comparison involving an upcast which is always true or false"
788 pub struct InvalidUpcastComparisons;
790 impl LintPass for InvalidUpcastComparisons {
791 fn get_lints(&self) -> LintArray {
792 lint_array!(INVALID_UPCAST_COMPARISONS)
796 #[derive(Copy, Clone, Debug, Eq)]
803 #[allow(cast_sign_loss)]
804 fn cmp_s_u(s: i64, u: u64) -> Ordering {
807 } else if u > (i64::max_value() as u64) {
815 impl PartialEq for FullInt {
816 fn eq(&self, other: &Self) -> bool {
817 self.partial_cmp(other).expect("partial_cmp only returns Some(_)") == Ordering::Equal
821 impl PartialOrd for FullInt {
822 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
823 Some(match (self, other) {
824 (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
825 (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
826 (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
827 (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
831 impl Ord for FullInt {
832 fn cmp(&self, other: &Self) -> Ordering {
833 self.partial_cmp(other).expect("partial_cmp for FullInt can never return None")
838 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
839 use rustc::ty::TypeVariants::{TyInt, TyUint};
840 use syntax::ast::{IntTy, UintTy};
843 if let ExprCast(ref cast_exp, _) = expr.node {
844 match cx.tcx.expr_ty(cast_exp).sty {
847 IntTy::I8 => (FullInt::S(i8::min_value() as i64), FullInt::S(i8::max_value() as i64)),
848 IntTy::I16 => (FullInt::S(i16::min_value() as i64), FullInt::S(i16::max_value() as i64)),
849 IntTy::I32 => (FullInt::S(i32::min_value() as i64), FullInt::S(i32::max_value() as i64)),
850 IntTy::I64 => (FullInt::S(i64::min_value() as i64), FullInt::S(i64::max_value() as i64)),
851 IntTy::Is => (FullInt::S(isize::min_value() as i64), FullInt::S(isize::max_value() as i64)),
856 UintTy::U8 => (FullInt::U(u8::min_value() as u64), FullInt::U(u8::max_value() as u64)),
857 UintTy::U16 => (FullInt::U(u16::min_value() as u64), FullInt::U(u16::max_value() as u64)),
858 UintTy::U32 => (FullInt::U(u32::min_value() as u64), FullInt::U(u32::max_value() as u64)),
859 UintTy::U64 => (FullInt::U(u64::min_value() as u64), FullInt::U(u64::max_value() as u64)),
860 UintTy::Us => (FullInt::U(usize::min_value() as u64), FullInt::U(usize::max_value() as u64)),
870 fn node_as_const_fullint(cx: &LateContext, expr: &Expr) -> Option<FullInt> {
871 use rustc::middle::const_val::ConstVal::*;
872 use rustc_const_eval::EvalHint::ExprTypeChecked;
873 use rustc_const_eval::eval_const_expr_partial;
874 use rustc_const_math::ConstInt;
876 match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
878 if let Integral(const_int) = val {
879 Some(match const_int.erase_type() {
880 ConstInt::InferSigned(x) => FullInt::S(x as i64),
881 ConstInt::Infer(x) => FullInt::U(x as u64),
892 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
893 if let ExprCast(ref cast_val, _) = expr.node {
895 INVALID_UPCAST_COMPARISONS,
898 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
899 snippet(cx, cast_val.span, "the expression"),
900 if always { "true" } else { "false" },
905 fn upcast_comparison_bounds_err(cx: &LateContext, span: &Span, rel: comparisons::Rel,
906 lhs_bounds: Option<(FullInt, FullInt)>, lhs: &Expr, rhs: &Expr, invert: bool) {
907 use utils::comparisons::*;
909 if let Some((lb, ub)) = lhs_bounds {
910 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
911 if rel == Rel::Eq || rel == Rel::Ne {
912 if norm_rhs_val < lb || norm_rhs_val > ub {
913 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
915 } else if match rel {
930 Rel::Eq | Rel::Ne => unreachable!(),
932 err_upcast_comparison(cx, span, lhs, true)
933 } else if match rel {
948 Rel::Eq | Rel::Ne => unreachable!(),
950 err_upcast_comparison(cx, span, lhs, false)
956 impl LateLintPass for InvalidUpcastComparisons {
957 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
958 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
960 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
961 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
967 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
968 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
970 upcast_comparison_bounds_err(cx, &expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
971 upcast_comparison_bounds_err(cx, &expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);