4 use rustc::hir::intravisit::{FnKind, Visitor, walk_ty, NestedVisitorMap};
6 use rustc::ty::{self, Ty};
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_old};
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_old(&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) -> usize {
503 let n = match typ.sty {
504 ty::TyInt(i) => 4 << (i as usize),
505 ty::TyUint(u) => 4 << (u as usize),
508 // n == 4 is the usize/isize case
510 ::std::mem::size_of::<usize>() * 8
516 fn is_isize_or_usize(typ: Ty) -> bool {
518 ty::TyInt(IntTy::Is) |
519 ty::TyUint(UintTy::Us) => true,
524 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to_f64: bool) {
525 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
526 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
527 let arch_dependent_str = "on targets with 64-bit wide pointers ";
528 let from_nbits_str = if arch_dependent {
530 } else if is_isize_or_usize(cast_from) {
531 "32 or 64".to_owned()
533 int_ty_to_nbits(cast_from).to_string()
540 "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
541 is only {4} bits wide)",
543 if cast_to_f64 { "f64" } else { "f32" },
561 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to: Ty) {
562 let arch_64_suffix = " on targets with 64-bit wide pointers";
563 let arch_32_suffix = " on targets with 32-bit wide pointers";
564 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
565 let (from_nbits, to_nbits) = (int_ty_to_nbits(cast_from), int_ty_to_nbits(cast_to));
566 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
567 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
568 (true, true) | (false, false) => {
570 to_nbits < from_nbits,
572 to_nbits == from_nbits && cast_unsigned_to_signed,
584 to_nbits <= 32 && cast_unsigned_to_signed,
592 cast_unsigned_to_signed,
593 if from_nbits == 64 {
604 CAST_POSSIBLE_TRUNCATION,
607 "casting {} to {} may truncate the value{}",
610 match suffix_truncation {
611 ArchSuffix::_32 => arch_32_suffix,
612 ArchSuffix::_64 => arch_64_suffix,
613 ArchSuffix::None => "",
624 "casting {} to {} may wrap around the value{}",
628 ArchSuffix::_32 => arch_32_suffix,
629 ArchSuffix::_64 => arch_64_suffix,
630 ArchSuffix::None => "",
637 impl LintPass for CastPass {
638 fn get_lints(&self) -> LintArray {
642 CAST_POSSIBLE_TRUNCATION,
649 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
650 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
651 if let ExprCast(ref ex, _) = expr.node {
652 let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
653 if let ExprLit(ref lit) = ex.node {
654 use syntax::ast::{LitKind, LitIntType};
656 LitKind::Int(_, LitIntType::Unsuffixed) |
657 LitKind::FloatUnsuffixed(_) => {},
659 if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
664 &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
670 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
671 match (cast_from.is_integral(), cast_to.is_integral()) {
673 let from_nbits = int_ty_to_nbits(cast_from);
674 let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
679 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
680 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
686 CAST_POSSIBLE_TRUNCATION,
688 &format!("casting {} to {} may truncate the value", cast_from, cast_to),
690 if !cast_to.is_signed() {
695 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
700 if cast_from.is_signed() && !cast_to.is_signed() {
705 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
708 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
711 if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) =
712 (&cast_from.sty, &cast_to.sty)
716 CAST_POSSIBLE_TRUNCATION,
718 "casting f64 to f32 may truncate the value",
728 /// **What it does:** Checks for types used in structs, parameters and `let`
729 /// declarations above a certain complexity threshold.
731 /// **Why is this bad?** Too complex types make the code less readable. Consider
732 /// using a `type` definition to simplify them.
734 /// **Known problems:** None.
738 /// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
743 "usage of very complex types that might be better factored into `type` definitions"
746 #[allow(missing_copy_implementations)]
747 pub struct TypeComplexityPass {
751 impl TypeComplexityPass {
752 pub fn new(threshold: u64) -> Self {
753 TypeComplexityPass { threshold: threshold }
757 impl LintPass for TypeComplexityPass {
758 fn get_lints(&self) -> LintArray {
759 lint_array!(TYPE_COMPLEXITY)
763 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
766 cx: &LateContext<'a, 'tcx>,
773 self.check_fndecl(cx, decl);
776 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx StructField) {
777 // enum variants are also struct fields now
778 self.check_type(cx, &field.ty);
781 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
783 ItemStatic(ref ty, _, _) |
784 ItemConst(ref ty, _) => self.check_type(cx, ty),
785 // functions, enums, structs, impls and traits are covered
790 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
792 TraitItemKind::Const(ref ty, _) |
793 TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
794 TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
795 // methods with default impl are covered by check_fn
800 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
802 ImplItemKind::Const(ref ty, _) |
803 ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
804 // methods are covered by check_fn
809 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
810 if let Some(ref ty) = local.ty {
811 self.check_type(cx, ty);
816 impl<'a, 'tcx> TypeComplexityPass {
817 fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
818 for arg in &decl.inputs {
819 self.check_type(cx, arg);
821 if let Return(ref ty) = decl.output {
822 self.check_type(cx, ty);
826 fn check_type(&self, cx: &LateContext, ty: &hir::Ty) {
827 if in_macro(ty.span) {
831 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
832 visitor.visit_ty(ty);
836 if score > self.threshold {
841 "very complex type used. Consider factoring parts into `type` definitions",
847 /// Walks a type and assigns a complexity score to it.
848 struct TypeComplexityVisitor {
849 /// total complexity score of the type
851 /// current nesting level
855 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
856 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
857 let (add_score, sub_nest) = match ty.node {
858 // _, &x and *x have only small overhead; don't mess with nesting level
859 TyInfer | TyPtr(..) | TyRptr(..) => (1, 0),
861 // the "normal" components of a type: named types, arrays/tuples
862 TyPath(..) | TySlice(..) | TyTup(..) | TyArray(..) => (10 * self.nest, 1),
864 // function types bring a lot of overhead
865 TyBareFn(..) => (50 * self.nest, 1),
867 TyTraitObject(ref param_bounds, _) => {
868 let has_lifetime_parameters = param_bounds.iter().any(
869 |bound| !bound.bound_lifetimes.is_empty(),
871 if has_lifetime_parameters {
872 // complex trait bounds like A<'a, 'b>
875 // simple trait bounds like A + B
882 self.score += add_score;
883 self.nest += sub_nest;
885 self.nest -= sub_nest;
887 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
888 NestedVisitorMap::None
892 /// **What it does:** Checks for expressions where a character literal is cast
893 /// to `u8` and suggests using a byte literal instead.
895 /// **Why is this bad?** In general, casting values to smaller types is
896 /// error-prone and should be avoided where possible. In the particular case of
897 /// converting a character literal to u8, it is easy to avoid by just using a
898 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
899 /// than `'a' as u8`.
901 /// **Known problems:** None.
910 "casting a character literal to u8"
913 pub struct CharLitAsU8;
915 impl LintPass for CharLitAsU8 {
916 fn get_lints(&self) -> LintArray {
917 lint_array!(CHAR_LIT_AS_U8)
921 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
922 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
923 use syntax::ast::{LitKind, UintTy};
925 if let ExprCast(ref e, _) = expr.node {
926 if let ExprLit(ref l) = e.node {
927 if let LitKind::Char(_) = l.node {
928 if ty::TyUint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
929 let msg = "casting character literal to u8. `char`s \
930 are 4 bytes wide in rust, so casting to u8 \
932 let help = format!("Consider using a byte literal instead:\nb{}", snippet(cx, e.span, "'x'"));
933 span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
941 /// **What it does:** Checks for comparisons where one side of the relation is
942 /// either the minimum or maximum value for its type and warns if it involves a
943 /// case that is always true or always false. Only integer and boolean types are
946 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
947 /// that is is possible for `x` to be less than the minimum. Expressions like
948 /// `max < x` are probably mistakes.
950 /// **Known problems:** None.
955 /// 100 > std::i32::MAX
958 pub ABSURD_EXTREME_COMPARISONS,
960 "a comparison with a maximum or minimum value that is always true or false"
963 pub struct AbsurdExtremeComparisons;
965 impl LintPass for AbsurdExtremeComparisons {
966 fn get_lints(&self) -> LintArray {
967 lint_array!(ABSURD_EXTREME_COMPARISONS)
976 struct ExtremeExpr<'a> {
981 enum AbsurdComparisonResult {
984 InequalityImpossible,
989 fn detect_absurd_comparison<'a>(
994 ) -> Option<(ExtremeExpr<'a>, AbsurdComparisonResult)> {
995 use types::ExtremeType::*;
996 use types::AbsurdComparisonResult::*;
997 use utils::comparisons::*;
999 // absurd comparison only makes sense on primitive types
1000 // primitive types don't implement comparison operators with each other
1001 if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1005 let normalized = normalize_comparison(op, lhs, rhs);
1006 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1012 let lx = detect_extreme_expr(cx, normalized_lhs);
1013 let rx = detect_extreme_expr(cx, normalized_rhs);
1018 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1019 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1025 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1026 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), //max <= x
1027 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1028 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1032 Rel::Ne | Rel::Eq => return None,
1036 fn detect_extreme_expr<'a>(cx: &LateContext, expr: &'a Expr) -> Option<ExtremeExpr<'a>> {
1037 use rustc::middle::const_val::ConstVal::*;
1038 use rustc_const_math::*;
1039 use rustc_const_eval::*;
1040 use types::ExtremeType::*;
1042 let ty = cx.tables.expr_ty(expr);
1045 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
1049 let parent_item = cx.tcx.hir.get_parent(expr.id);
1050 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1051 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1052 let cv = match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
1054 Err(_) => return None,
1057 let which = match (&ty.sty, cv) {
1058 (&ty::TyBool, Bool(false)) |
1059 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MIN)))) |
1060 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MIN)))) |
1061 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MIN))) |
1062 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MIN))) |
1063 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MIN))) |
1064 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MIN))) |
1065 (&ty::TyInt(IntTy::I128), Integral(I128(::std::i128::MIN))) |
1066 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MIN)))) |
1067 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MIN)))) |
1068 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MIN))) |
1069 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MIN))) |
1070 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MIN))) |
1071 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MIN))) |
1072 (&ty::TyUint(UintTy::U128), Integral(U128(::std::u128::MIN))) => Minimum,
1074 (&ty::TyBool, Bool(true)) |
1075 (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MAX)))) |
1076 (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MAX)))) |
1077 (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MAX))) |
1078 (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MAX))) |
1079 (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MAX))) |
1080 (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MAX))) |
1081 (&ty::TyInt(IntTy::I128), Integral(I128(::std::i128::MAX))) |
1082 (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MAX)))) |
1083 (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MAX)))) |
1084 (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MAX))) |
1085 (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MAX))) |
1086 (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MAX))) |
1087 (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MAX))) |
1088 (&ty::TyUint(UintTy::U128), Integral(U128(::std::u128::MAX))) => Maximum,
1098 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1099 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1100 use types::ExtremeType::*;
1101 use types::AbsurdComparisonResult::*;
1103 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1104 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1105 if !in_macro(expr.span) {
1106 let msg = "this comparison involving the minimum or maximum element for this \
1107 type contains a case that is always true or always false";
1109 let conclusion = match result {
1110 AlwaysFalse => "this comparison is always false".to_owned(),
1111 AlwaysTrue => "this comparison is always true".to_owned(),
1112 InequalityImpossible => {
1114 "the case where the two sides are not equal never occurs, consider using {} == {} \
1116 snippet(cx, lhs.span, "lhs"),
1117 snippet(cx, rhs.span, "rhs")
1123 "because {} is the {} value for this type, {}",
1124 snippet(cx, culprit.expr.span, "x"),
1125 match culprit.which {
1126 Minimum => "minimum",
1127 Maximum => "maximum",
1132 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1139 /// **What it does:** Checks for comparisons where the relation is always either
1140 /// true or false, but where one side has been upcast so that the comparison is
1141 /// necessary. Only integer types are checked.
1143 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1144 /// will mistakenly imply that it is possible for `x` to be outside the range of
1147 /// **Known problems:** https://github.com/Manishearth/rust-clippy/issues/886
1151 /// let x : u8 = ...; (x as u32) > 300
1154 pub INVALID_UPCAST_COMPARISONS,
1156 "a comparison involving an upcast which is always true or false"
1159 pub struct InvalidUpcastComparisons;
1161 impl LintPass for InvalidUpcastComparisons {
1162 fn get_lints(&self) -> LintArray {
1163 lint_array!(INVALID_UPCAST_COMPARISONS)
1167 #[derive(Copy, Clone, Debug, Eq)]
1174 #[allow(cast_sign_loss)]
1175 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1178 } else if u > (i128::max_value() as u128) {
1186 impl PartialEq for FullInt {
1187 fn eq(&self, other: &Self) -> bool {
1188 self.partial_cmp(other).expect(
1189 "partial_cmp only returns Some(_)",
1190 ) == Ordering::Equal
1194 impl PartialOrd for FullInt {
1195 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1196 Some(match (self, other) {
1197 (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1198 (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1199 (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1200 (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1204 impl Ord for FullInt {
1205 fn cmp(&self, other: &Self) -> Ordering {
1206 self.partial_cmp(other).expect(
1207 "partial_cmp for FullInt can never return None",
1213 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1214 use syntax::ast::{IntTy, UintTy};
1217 if let ExprCast(ref cast_exp, _) = expr.node {
1218 let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1219 let cast_ty = cx.tables.expr_ty(expr);
1220 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1221 if type_size(cx, pre_cast_ty) == type_size(cx, cast_ty) {
1224 match pre_cast_ty.sty {
1225 ty::TyInt(int_ty) => {
1227 IntTy::I8 => (FullInt::S(i8::min_value() as i128), FullInt::S(i8::max_value() as i128)),
1228 IntTy::I16 => (FullInt::S(i16::min_value() as i128), FullInt::S(i16::max_value() as i128)),
1229 IntTy::I32 => (FullInt::S(i32::min_value() as i128), FullInt::S(i32::max_value() as i128)),
1230 IntTy::I64 => (FullInt::S(i64::min_value() as i128), FullInt::S(i64::max_value() as i128)),
1231 IntTy::I128 => (FullInt::S(i128::min_value() as i128), FullInt::S(i128::max_value() as i128)),
1232 IntTy::Is => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)),
1235 ty::TyUint(uint_ty) => {
1236 Some(match uint_ty {
1237 UintTy::U8 => (FullInt::U(u8::min_value() as u128), FullInt::U(u8::max_value() as u128)),
1238 UintTy::U16 => (FullInt::U(u16::min_value() as u128), FullInt::U(u16::max_value() as u128)),
1239 UintTy::U32 => (FullInt::U(u32::min_value() as u128), FullInt::U(u32::max_value() as u128)),
1240 UintTy::U64 => (FullInt::U(u64::min_value() as u128), FullInt::U(u64::max_value() as u128)),
1241 UintTy::U128 => (FullInt::U(u128::min_value() as u128), FullInt::U(u128::max_value() as u128)),
1242 UintTy::Us => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
1252 #[allow(cast_possible_wrap)]
1253 fn node_as_const_fullint(cx: &LateContext, expr: &Expr) -> Option<FullInt> {
1254 use rustc::middle::const_val::ConstVal::*;
1255 use rustc_const_eval::ConstContext;
1257 let parent_item = cx.tcx.hir.get_parent(expr.id);
1258 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1259 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1260 match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
1262 if let Integral(const_int) = val {
1263 match const_int.int_type() {
1264 IntType::SignedInt(_) => Some(FullInt::S(const_int.to_u128_unchecked() as i128)),
1265 IntType::UnsignedInt(_) => Some(FullInt::U(const_int.to_u128_unchecked())),
1275 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
1276 if let ExprCast(ref cast_val, _) = expr.node {
1279 INVALID_UPCAST_COMPARISONS,
1282 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1283 snippet(cx, cast_val.span, "the expression"),
1284 if always { "true" } else { "false" },
1290 fn upcast_comparison_bounds_err(
1293 rel: comparisons::Rel,
1294 lhs_bounds: Option<(FullInt, FullInt)>,
1299 use utils::comparisons::*;
1301 if let Some((lb, ub)) = lhs_bounds {
1302 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1303 if rel == Rel::Eq || rel == Rel::Ne {
1304 if norm_rhs_val < lb || norm_rhs_val > ub {
1305 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1307 } else if match rel {
1322 Rel::Eq | Rel::Ne => unreachable!(),
1325 err_upcast_comparison(cx, span, lhs, true)
1326 } else if match rel {
1341 Rel::Eq | Rel::Ne => unreachable!(),
1344 err_upcast_comparison(cx, span, lhs, false)
1350 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1351 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1352 if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1354 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1355 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1361 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1362 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1364 upcast_comparison_bounds_err(cx, &expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1365 upcast_comparison_bounds_err(cx, &expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);