4 use rustc::hir::intravisit::{FnKind, Visitor, walk_ty, NestedVisitorMap};
6 use rustc::ty::{self, Ty, TyCtxt};
7 use rustc::ty::subst::Substs;
8 use std::cmp::Ordering;
9 use syntax::ast::{IntTy, UintTy, FloatTy};
10 use syntax::attr::IntType;
11 use syntax::codemap::Span;
12 use utils::{comparisons, higher, in_external_macro, in_macro, match_def_path, snippet, span_help_and_lint, span_lint,
13 span_lint_and_sugg, opt_def_id, last_path_segment, type_size, match_path};
16 /// Handles all the linting of funky types
17 #[allow(missing_copy_implementations)]
20 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
22 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
23 /// the heap. So if you `Box` it, you just add another level of indirection
24 /// without any benefit whatsoever.
26 /// **Known problems:** None.
31 /// values: Box<Vec<Foo>>,
37 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
40 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
41 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
43 /// **Why is this bad?** Gankro says:
45 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
46 /// pointers and indirection.
47 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
49 /// > "only" amortized for push/pop, should be faster in the general case for
50 /// almost every possible
51 /// > workload, and isn't even amortized at all if you can predict the capacity
54 /// > `LinkedList`s are only really good if you're doing a lot of merging or
55 /// splitting of lists.
56 /// > This is because they can just mangle some pointers instead of actually
57 /// copying the data. Even
58 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
59 /// can still be better
60 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
62 /// **Known problems:** False positives – the instances where using a
63 /// `LinkedList` makes sense are few and far between, but they can still happen.
67 /// let x = LinkedList::new();
72 "usage of LinkedList, usually a vector is faster, or a more specialized data \
73 structure like a VecDeque"
76 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
78 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
81 /// **Known problems:** None.
85 /// fn foo(bar: &Box<T>) { ... }
90 "a borrow of a boxed type"
93 impl LintPass for TypePass {
94 fn get_lints(&self) -> LintArray {
95 lint_array!(BOX_VEC, LINKEDLIST, BORROWED_BOX)
99 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypePass {
100 fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Body, _: Span, id: NodeId) {
101 // skip trait implementations, see #605
102 if let Some(map::NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(id)) {
103 if let ItemImpl(_, _, _, _, Some(..), _, _) = item.node {
108 check_fn_decl(cx, decl);
111 fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
112 check_ty(cx, &field.ty, false);
115 fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
117 TraitItemKind::Const(ref ty, _) |
118 TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
119 TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
124 fn check_local(&mut self, cx: &LateContext, local: &Local) {
125 if let Some(ref ty) = local.ty {
126 check_ty(cx, ty, true);
131 fn check_fn_decl(cx: &LateContext, decl: &FnDecl) {
132 for input in &decl.inputs {
133 check_ty(cx, input, false);
136 if let FunctionRetTy::Return(ref ty) = decl.output {
137 check_ty(cx, ty, false);
141 /// Recursively check for `TypePass` lints in the given type. Stop at the first
144 /// The parameter `is_local` distinguishes the context of the type; types from
145 /// local bindings should only be checked for the `BORROWED_BOX` lint.
146 fn check_ty(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool) {
147 if in_macro(ast_ty.span) {
151 TyPath(ref qpath) if !is_local => {
152 let hir_id = cx.tcx.hir.node_to_hir_id(ast_ty.id);
153 let def = cx.tables.qpath_def(qpath, hir_id);
154 if let Some(def_id) = opt_def_id(def) {
155 if Some(def_id) == cx.tcx.lang_items.owned_box() {
156 let last = last_path_segment(qpath);
158 let PathParameters::AngleBracketedParameters(ref ag) = last.parameters,
159 let Some(vec) = ag.types.get(0),
160 let TyPath(ref qpath) = vec.node,
161 let Some(did) = opt_def_id(cx.tables.qpath_def(qpath, cx.tcx.hir.node_to_hir_id(vec.id))),
162 match_def_path(cx.tcx, did, &paths::VEC),
164 span_help_and_lint(cx,
167 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
168 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.");
169 return; // don't recurse into the type
171 } else if match_def_path(cx.tcx, def_id, &paths::LINKED_LIST) {
176 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
177 "a VecDeque might work",
179 return; // don't recurse into the type
183 QPath::Resolved(Some(ref ty), ref p) => {
184 check_ty(cx, ty, is_local);
185 for ty in p.segments.iter().flat_map(|seg| seg.parameters.types()) {
186 check_ty(cx, ty, is_local);
189 QPath::Resolved(None, ref p) => {
190 for ty in p.segments.iter().flat_map(|seg| seg.parameters.types()) {
191 check_ty(cx, ty, is_local);
194 QPath::TypeRelative(ref ty, ref seg) => {
195 check_ty(cx, ty, is_local);
196 for ty in seg.parameters.types() {
197 check_ty(cx, ty, is_local);
202 TyRptr(ref lt, MutTy { ref ty, ref mutbl }) => {
204 TyPath(ref qpath) => {
205 let hir_id = cx.tcx.hir.node_to_hir_id(ty.id);
206 let def = cx.tables.qpath_def(qpath, hir_id);
208 let Some(def_id) = opt_def_id(def),
209 Some(def_id) == cx.tcx.lang_items.owned_box(),
210 let QPath::Resolved(None, ref path) = *qpath,
211 let [ref bx] = *path.segments,
212 let PathParameters::AngleBracketedParameters(ref ab_data) = bx.parameters,
213 let [ref inner] = *ab_data.types
215 if is_any_trait(inner) {
216 // Ignore `Box<Any>` types, see #1884 for details.
220 let ltopt = if lt.is_elided() {
223 format!("{} ", lt.name.as_str())
225 let mutopt = if *mutbl == Mutability::MutMutable {
230 span_lint_and_sugg(cx,
233 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
235 format!("&{}{}{}", ltopt, mutopt, &snippet(cx, inner.span, ".."))
237 return; // don't recurse into the type
239 check_ty(cx, ty, is_local);
241 _ => check_ty(cx, ty, is_local),
247 TyPtr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
250 check_ty(cx, ty, is_local);
257 // Returns true if given type is `Any` trait.
258 fn is_any_trait(t: &hir::Ty) -> bool {
260 let TyTraitObject(ref traits, _) = t.node,
262 // Only Send/Sync can be used as additional traits, so it is enough to
263 // check only the first trait.
264 match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT)
272 #[allow(missing_copy_implementations)]
275 /// **What it does:** Checks for binding a unit value.
277 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
278 /// binding one is kind of pointless.
280 /// **Known problems:** None.
289 "creating a let binding to a value of unit type, which usually can't be used afterwards"
292 fn check_let_unit(cx: &LateContext, decl: &Decl) {
293 if let DeclLocal(ref local) = decl.node {
294 match cx.tables.pat_ty(&local.pat).sty {
295 ty::TyTuple(slice, _) if slice.is_empty() => {
296 if in_external_macro(cx, decl.span) || in_macro(local.pat.span) {
299 if higher::is_from_for_desugar(decl) {
307 "this let-binding has unit value. Consider omitting `let {} =`",
308 snippet(cx, local.pat.span, "..")
317 impl LintPass for LetPass {
318 fn get_lints(&self) -> LintArray {
319 lint_array!(LET_UNIT_VALUE)
323 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetPass {
324 fn check_decl(&mut self, cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl) {
325 check_let_unit(cx, decl)
329 /// **What it does:** Checks for comparisons to unit.
331 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
332 /// clumsily written constant. Mostly this happens when someone accidentally
333 /// adds semicolons at the end of the operands.
335 /// **Known problems:** None.
339 /// if { foo(); } == { bar(); } { baz(); }
343 /// { foo(); bar(); baz(); }
348 "comparing unit values"
351 #[allow(missing_copy_implementations)]
354 impl LintPass for UnitCmp {
355 fn get_lints(&self) -> LintArray {
356 lint_array!(UNIT_CMP)
360 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
361 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
362 if in_macro(expr.span) {
365 if let ExprBinary(ref cmp, ref left, _) = expr.node {
367 if op.is_comparison() {
368 match cx.tables.expr_ty(left).sty {
369 ty::TyTuple(slice, _) if slice.is_empty() => {
370 let result = match op {
371 BiEq | BiLe | BiGe => "true",
379 "{}-comparison of unit values detected. This will always be {}",
394 /// **What it does:** Checks for casts from any numerical to a float type where
395 /// the receiving type cannot store all values from the original type without
396 /// rounding errors. This possible rounding is to be expected, so this lint is
397 /// `Allow` by default.
399 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
400 /// or any 64-bit integer to `f64`.
402 /// **Why is this bad?** It's not bad at all. But in some applications it can be
403 /// helpful to know where precision loss can take place. This lint can help find
404 /// those places in the code.
406 /// **Known problems:** None.
410 /// let x = u64::MAX; x as f64
413 pub CAST_PRECISION_LOSS,
415 "casts that cause loss of precision, e.g. `x as f32` where `x: u64`"
418 /// **What it does:** Checks for casts from a signed to an unsigned numerical
419 /// type. In this case, negative values wrap around to large positive values,
420 /// which can be quite surprising in practice. However, as the cast works as
421 /// defined, this lint is `Allow` by default.
423 /// **Why is this bad?** Possibly surprising results. You can activate this lint
424 /// as a one-time check to see where numerical wrapping can arise.
426 /// **Known problems:** None.
431 /// y as u128 // will return 18446744073709551615
436 "casts from signed types to unsigned types, e.g. `x as u32` where `x: i32`"
439 /// **What it does:** Checks for on casts between numerical types that may
440 /// truncate large values. This is expected behavior, so the cast is `Allow` by
443 /// **Why is this bad?** In some problem domains, it is good practice to avoid
444 /// truncation. This lint can be activated to help assess where additional
445 /// checks could be beneficial.
447 /// **Known problems:** None.
451 /// fn as_u8(x: u64) -> u8 { x as u8 }
454 pub CAST_POSSIBLE_TRUNCATION,
456 "casts that may cause truncation of the value, e.g. `x as u8` where `x: u32`, \
457 or `x as i32` where `x: f32`"
460 /// **What it does:** Checks for casts from an unsigned type to a signed type of
461 /// the same size. Performing such a cast is a 'no-op' for the compiler,
462 /// i.e. nothing is changed at the bit level, and the binary representation of
463 /// the value is reinterpreted. This can cause wrapping if the value is too big
464 /// for the target signed type. However, the cast works as defined, so this lint
465 /// is `Allow` by default.
467 /// **Why is this bad?** While such a cast is not bad in itself, the results can
468 /// be surprising when this is not the intended behavior, as demonstrated by the
471 /// **Known problems:** None.
475 /// u32::MAX as i32 // will yield a value of `-1`
478 pub CAST_POSSIBLE_WRAP,
480 "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` \
484 /// **What it does:** Checks for casts to the same type.
486 /// **Why is this bad?** It's just unnecessary.
488 /// **Known problems:** None.
492 /// let _ = 2i32 as i32
495 pub UNNECESSARY_CAST,
497 "cast to the same type, e.g. `x as i32` where `x: i32`"
500 /// Returns the size in bits of an integral type.
501 /// Will return 0 if the type is not an int or uint variant
502 fn int_ty_to_nbits(typ: Ty, tcx: TyCtxt) -> u64 {
504 ty::TyInt(i) => match i {
505 IntTy::Is => tcx.data_layout.pointer_size.bits(),
512 ty::TyUint(i) => match i {
513 UintTy::Us => tcx.data_layout.pointer_size.bits(),
524 fn is_isize_or_usize(typ: Ty) -> bool {
526 ty::TyInt(IntTy::Is) |
527 ty::TyUint(UintTy::Us) => true,
532 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to_f64: bool) {
533 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
534 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
535 let arch_dependent_str = "on targets with 64-bit wide pointers ";
536 let from_nbits_str = if arch_dependent {
538 } else if is_isize_or_usize(cast_from) {
539 "32 or 64".to_owned()
541 int_ty_to_nbits(cast_from, cx.tcx).to_string()
548 "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
549 is only {4} bits wide)",
551 if cast_to_f64 { "f64" } else { "f32" },
569 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to: Ty) {
570 let arch_64_suffix = " on targets with 64-bit wide pointers";
571 let arch_32_suffix = " on targets with 32-bit wide pointers";
572 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
573 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
574 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
575 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
576 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
577 (true, true) | (false, false) => {
579 to_nbits < from_nbits,
581 to_nbits == from_nbits && cast_unsigned_to_signed,
593 to_nbits <= 32 && cast_unsigned_to_signed,
601 cast_unsigned_to_signed,
602 if from_nbits == 64 {
613 CAST_POSSIBLE_TRUNCATION,
616 "casting {} to {} may truncate the value{}",
619 match suffix_truncation {
620 ArchSuffix::_32 => arch_32_suffix,
621 ArchSuffix::_64 => arch_64_suffix,
622 ArchSuffix::None => "",
633 "casting {} to {} may wrap around the value{}",
637 ArchSuffix::_32 => arch_32_suffix,
638 ArchSuffix::_64 => arch_64_suffix,
639 ArchSuffix::None => "",
646 impl LintPass for CastPass {
647 fn get_lints(&self) -> LintArray {
651 CAST_POSSIBLE_TRUNCATION,
658 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
659 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
660 if let ExprCast(ref ex, _) = expr.node {
661 let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
662 if let ExprLit(ref lit) = ex.node {
663 use syntax::ast::{LitKind, LitIntType};
665 LitKind::Int(_, LitIntType::Unsuffixed) |
666 LitKind::FloatUnsuffixed(_) => {},
668 if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
673 &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
679 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
680 match (cast_from.is_integral(), cast_to.is_integral()) {
682 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
683 let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
688 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
689 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
695 CAST_POSSIBLE_TRUNCATION,
697 &format!("casting {} to {} may truncate the value", cast_from, cast_to),
699 if !cast_to.is_signed() {
704 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
709 if cast_from.is_signed() && !cast_to.is_signed() {
714 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
717 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
720 if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) =
721 (&cast_from.sty, &cast_to.sty)
725 CAST_POSSIBLE_TRUNCATION,
727 "casting f64 to f32 may truncate the value",
737 /// **What it does:** Checks for types used in structs, parameters and `let`
738 /// declarations above a certain complexity threshold.
740 /// **Why is this bad?** Too complex types make the code less readable. Consider
741 /// using a `type` definition to simplify them.
743 /// **Known problems:** None.
747 /// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
752 "usage of very complex types that might be better factored into `type` definitions"
755 #[allow(missing_copy_implementations)]
756 pub struct TypeComplexityPass {
760 impl TypeComplexityPass {
761 pub fn new(threshold: u64) -> Self {
762 Self { threshold: threshold }
766 impl LintPass for TypeComplexityPass {
767 fn get_lints(&self) -> LintArray {
768 lint_array!(TYPE_COMPLEXITY)
772 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
775 cx: &LateContext<'a, 'tcx>,
782 self.check_fndecl(cx, decl);
785 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx StructField) {
786 // enum variants are also struct fields now
787 self.check_type(cx, &field.ty);
790 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
792 ItemStatic(ref ty, _, _) |
793 ItemConst(ref ty, _) => self.check_type(cx, ty),
794 // functions, enums, structs, impls and traits are covered
799 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
801 TraitItemKind::Const(ref ty, _) |
802 TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
803 TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
804 // methods with default impl are covered by check_fn
809 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
811 ImplItemKind::Const(ref ty, _) |
812 ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
813 // methods are covered by check_fn
818 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
819 if let Some(ref ty) = local.ty {
820 self.check_type(cx, ty);
825 impl<'a, 'tcx> TypeComplexityPass {
826 fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
827 for arg in &decl.inputs {
828 self.check_type(cx, arg);
830 if let Return(ref ty) = decl.output {
831 self.check_type(cx, ty);
835 fn check_type(&self, cx: &LateContext, ty: &hir::Ty) {
836 if in_macro(ty.span) {
840 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
841 visitor.visit_ty(ty);
845 if score > self.threshold {
850 "very complex type used. Consider factoring parts into `type` definitions",
856 /// Walks a type and assigns a complexity score to it.
857 struct TypeComplexityVisitor {
858 /// total complexity score of the type
860 /// current nesting level
864 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
865 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
866 let (add_score, sub_nest) = match ty.node {
867 // _, &x and *x have only small overhead; don't mess with nesting level
868 TyInfer | TyPtr(..) | TyRptr(..) => (1, 0),
870 // the "normal" components of a type: named types, arrays/tuples
871 TyPath(..) | TySlice(..) | TyTup(..) | TyArray(..) => (10 * self.nest, 1),
873 // function types bring a lot of overhead
874 TyBareFn(..) => (50 * self.nest, 1),
876 TyTraitObject(ref param_bounds, _) => {
877 let has_lifetime_parameters = param_bounds.iter().any(
878 |bound| !bound.bound_lifetimes.is_empty(),
880 if has_lifetime_parameters {
881 // complex trait bounds like A<'a, 'b>
884 // simple trait bounds like A + B
891 self.score += add_score;
892 self.nest += sub_nest;
894 self.nest -= sub_nest;
896 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
897 NestedVisitorMap::None
901 /// **What it does:** Checks for expressions where a character literal is cast
902 /// to `u8` and suggests using a byte literal instead.
904 /// **Why is this bad?** In general, casting values to smaller types is
905 /// error-prone and should be avoided where possible. In the particular case of
906 /// converting a character literal to u8, it is easy to avoid by just using a
907 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
908 /// than `'a' as u8`.
910 /// **Known problems:** None.
919 "casting a character literal to u8"
922 pub struct CharLitAsU8;
924 impl LintPass for CharLitAsU8 {
925 fn get_lints(&self) -> LintArray {
926 lint_array!(CHAR_LIT_AS_U8)
930 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
931 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
932 use syntax::ast::{LitKind, UintTy};
934 if let ExprCast(ref e, _) = expr.node {
935 if let ExprLit(ref l) = e.node {
936 if let LitKind::Char(_) = l.node {
937 if ty::TyUint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
938 let msg = "casting character literal to u8. `char`s \
939 are 4 bytes wide in rust, so casting to u8 \
941 let help = format!("Consider using a byte literal instead:\nb{}", snippet(cx, e.span, "'x'"));
942 span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
950 /// **What it does:** Checks for comparisons where one side of the relation is
951 /// either the minimum or maximum value for its type and warns if it involves a
952 /// case that is always true or always false. Only integer and boolean types are
955 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
956 /// that is is possible for `x` to be less than the minimum. Expressions like
957 /// `max < x` are probably mistakes.
959 /// **Known problems:** None.
964 /// 100 > std::i32::MAX
967 pub ABSURD_EXTREME_COMPARISONS,
969 "a comparison with a maximum or minimum value that is always true or false"
972 pub struct AbsurdExtremeComparisons;
974 impl LintPass for AbsurdExtremeComparisons {
975 fn get_lints(&self) -> LintArray {
976 lint_array!(ABSURD_EXTREME_COMPARISONS)
985 struct ExtremeExpr<'a> {
990 enum AbsurdComparisonResult {
993 InequalityImpossible,
998 fn detect_absurd_comparison<'a>(
1003 ) -> Option<(ExtremeExpr<'a>, AbsurdComparisonResult)> {
1004 use types::ExtremeType::*;
1005 use types::AbsurdComparisonResult::*;
1006 use utils::comparisons::*;
1008 // absurd comparison only makes sense on primitive types
1009 // primitive types don't implement comparison operators with each other
1010 if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1014 let normalized = normalize_comparison(op, lhs, rhs);
1015 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1021 let lx = detect_extreme_expr(cx, normalized_lhs);
1022 let rx = detect_extreme_expr(cx, normalized_rhs);
1027 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1028 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1034 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1035 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), //max <= x
1036 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1037 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1041 Rel::Ne | Rel::Eq => return None,
1045 fn detect_extreme_expr<'a>(cx: &LateContext, expr: &'a Expr) -> Option<ExtremeExpr<'a>> {
1046 use rustc::middle::const_val::ConstVal::*;
1047 use rustc_const_math::*;
1048 use rustc_const_eval::*;
1049 use types::ExtremeType::*;
1051 let ty = cx.tables.expr_ty(expr);
1054 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
1058 let parent_item = cx.tcx.hir.get_parent(expr.id);
1059 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1060 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1061 let cv = match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
1063 Err(_) => return None,
1066 let which = match (&ty.sty, cv) {
1067 (&ty::TyBool, Bool(false)) |
1068 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MIN)))) |
1069 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MIN)))) |
1070 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MIN))) |
1071 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MIN))) |
1072 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MIN))) |
1073 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MIN))) |
1074 (&ty::TyInt(IntTy::I128), Integral(I128(::std::i128::MIN))) |
1075 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MIN)))) |
1076 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MIN)))) |
1077 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MIN))) |
1078 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MIN))) |
1079 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MIN))) |
1080 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MIN))) |
1081 (&ty::TyUint(UintTy::U128), Integral(U128(::std::u128::MIN))) => Minimum,
1083 (&ty::TyBool, Bool(true)) |
1084 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MAX)))) |
1085 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MAX)))) |
1086 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MAX))) |
1087 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MAX))) |
1088 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MAX))) |
1089 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MAX))) |
1090 (&ty::TyInt(IntTy::I128), Integral(I128(::std::i128::MAX))) |
1091 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MAX)))) |
1092 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MAX)))) |
1093 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MAX))) |
1094 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MAX))) |
1095 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MAX))) |
1096 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MAX))) |
1097 (&ty::TyUint(UintTy::U128), Integral(U128(::std::u128::MAX))) => Maximum,
1107 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1108 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1109 use types::ExtremeType::*;
1110 use types::AbsurdComparisonResult::*;
1112 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1113 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1114 if !in_macro(expr.span) {
1115 let msg = "this comparison involving the minimum or maximum element for this \
1116 type contains a case that is always true or always false";
1118 let conclusion = match result {
1119 AlwaysFalse => "this comparison is always false".to_owned(),
1120 AlwaysTrue => "this comparison is always true".to_owned(),
1121 InequalityImpossible => {
1123 "the case where the two sides are not equal never occurs, consider using {} == {} \
1125 snippet(cx, lhs.span, "lhs"),
1126 snippet(cx, rhs.span, "rhs")
1132 "because {} is the {} value for this type, {}",
1133 snippet(cx, culprit.expr.span, "x"),
1134 match culprit.which {
1135 Minimum => "minimum",
1136 Maximum => "maximum",
1141 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1148 /// **What it does:** Checks for comparisons where the relation is always either
1149 /// true or false, but where one side has been upcast so that the comparison is
1150 /// necessary. Only integer types are checked.
1152 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1153 /// will mistakenly imply that it is possible for `x` to be outside the range of
1156 /// **Known problems:** https://github.com/rust-lang-nursery/rust-clippy/issues/886
1160 /// let x : u8 = ...; (x as u32) > 300
1163 pub INVALID_UPCAST_COMPARISONS,
1165 "a comparison involving an upcast which is always true or false"
1168 pub struct InvalidUpcastComparisons;
1170 impl LintPass for InvalidUpcastComparisons {
1171 fn get_lints(&self) -> LintArray {
1172 lint_array!(INVALID_UPCAST_COMPARISONS)
1176 #[derive(Copy, Clone, Debug, Eq)]
1183 #[allow(cast_sign_loss)]
1184 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1187 } else if u > (i128::max_value() as u128) {
1195 impl PartialEq for FullInt {
1196 fn eq(&self, other: &Self) -> bool {
1197 self.partial_cmp(other).expect(
1198 "partial_cmp only returns Some(_)",
1199 ) == Ordering::Equal
1203 impl PartialOrd for FullInt {
1204 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1205 Some(match (self, other) {
1206 (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1207 (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1208 (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1209 (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1213 impl Ord for FullInt {
1214 fn cmp(&self, other: &Self) -> Ordering {
1215 self.partial_cmp(other).expect(
1216 "partial_cmp for FullInt can never return None",
1222 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1223 use syntax::ast::{IntTy, UintTy};
1226 if let ExprCast(ref cast_exp, _) = expr.node {
1227 let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1228 let cast_ty = cx.tables.expr_ty(expr);
1229 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1230 if type_size(cx, pre_cast_ty) == type_size(cx, cast_ty) {
1233 match pre_cast_ty.sty {
1234 ty::TyInt(int_ty) => {
1236 IntTy::I8 => (FullInt::S(i8::min_value() as i128), FullInt::S(i8::max_value() as i128)),
1237 IntTy::I16 => (FullInt::S(i16::min_value() as i128), FullInt::S(i16::max_value() as i128)),
1238 IntTy::I32 => (FullInt::S(i32::min_value() as i128), FullInt::S(i32::max_value() as i128)),
1239 IntTy::I64 => (FullInt::S(i64::min_value() as i128), FullInt::S(i64::max_value() as i128)),
1240 IntTy::I128 => (FullInt::S(i128::min_value() as i128), FullInt::S(i128::max_value() as i128)),
1241 IntTy::Is => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)),
1244 ty::TyUint(uint_ty) => {
1245 Some(match uint_ty {
1246 UintTy::U8 => (FullInt::U(u8::min_value() as u128), FullInt::U(u8::max_value() as u128)),
1247 UintTy::U16 => (FullInt::U(u16::min_value() as u128), FullInt::U(u16::max_value() as u128)),
1248 UintTy::U32 => (FullInt::U(u32::min_value() as u128), FullInt::U(u32::max_value() as u128)),
1249 UintTy::U64 => (FullInt::U(u64::min_value() as u128), FullInt::U(u64::max_value() as u128)),
1250 UintTy::U128 => (FullInt::U(u128::min_value() as u128), FullInt::U(u128::max_value() as u128)),
1251 UintTy::Us => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
1261 #[allow(cast_possible_wrap)]
1262 fn node_as_const_fullint(cx: &LateContext, expr: &Expr) -> Option<FullInt> {
1263 use rustc::middle::const_val::ConstVal::*;
1264 use rustc_const_eval::ConstContext;
1266 let parent_item = cx.tcx.hir.get_parent(expr.id);
1267 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1268 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1269 match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
1271 if let Integral(const_int) = val {
1272 match const_int.int_type() {
1273 IntType::SignedInt(_) => Some(FullInt::S(const_int.to_u128_unchecked() as i128)),
1274 IntType::UnsignedInt(_) => Some(FullInt::U(const_int.to_u128_unchecked())),
1284 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
1285 if let ExprCast(ref cast_val, _) = expr.node {
1288 INVALID_UPCAST_COMPARISONS,
1291 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1292 snippet(cx, cast_val.span, "the expression"),
1293 if always { "true" } else { "false" },
1299 fn upcast_comparison_bounds_err(
1302 rel: comparisons::Rel,
1303 lhs_bounds: Option<(FullInt, FullInt)>,
1308 use utils::comparisons::*;
1310 if let Some((lb, ub)) = lhs_bounds {
1311 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1312 if rel == Rel::Eq || rel == Rel::Ne {
1313 if norm_rhs_val < lb || norm_rhs_val > ub {
1314 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1316 } else if match rel {
1331 Rel::Eq | Rel::Ne => unreachable!(),
1334 err_upcast_comparison(cx, span, lhs, true)
1335 } else if match rel {
1350 Rel::Eq | Rel::Ne => unreachable!(),
1353 err_upcast_comparison(cx, span, lhs, false)
1359 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1360 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1361 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1363 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1364 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1370 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1371 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1373 upcast_comparison_bounds_err(cx, &expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1374 upcast_comparison_bounds_err(cx, &expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);