]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/types.rs
Merge pull request #950 from oli-obk/split3
[rust.git] / clippy_lints / src / types.rs
1 use reexport::*;
2 use rustc::hir::*;
3 use rustc::hir::intravisit::{FnKind, Visitor, walk_ty};
4 use rustc::lint::*;
5 use rustc::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};
11 use utils::paths;
12
13 /// Handles all the linting of funky types
14 #[allow(missing_copy_implementations)]
15 pub struct TypePass;
16
17 /// **What it does:** This lint checks for use of `Box<Vec<_>>` anywhere in the code.
18 ///
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.
20 ///
21 /// **Known problems:** None
22 ///
23 /// **Example:** `struct X { values: Box<Vec<Foo>> }`
24 declare_lint! {
25     pub BOX_VEC, Warn,
26     "usage of `Box<Vec<T>>`, vector elements are already on the heap"
27 }
28
29 /// **What it does:** This lint checks for usage of any `LinkedList`, suggesting to use a `Vec` or a `VecDeque` (formerly called `RingBuf`).
30 ///
31 /// **Why is this bad?** Gankro says:
32 ///
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.
34 /// >
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`.
36 ///
37 /// **Known problems:** False positives – the instances where using a `LinkedList` makes sense are few and far between, but they can still happen.
38 ///
39 /// **Example:** `let x = LinkedList::new();`
40 declare_lint! {
41     pub LINKEDLIST, Warn,
42     "usage of LinkedList, usually a vector is faster, or a more specialized data \
43      structure like a VecDeque"
44 }
45
46 impl LintPass for TypePass {
47     fn get_lints(&self) -> LintArray {
48         lint_array!(BOX_VEC, LINKEDLIST)
49     }
50 }
51
52 impl LateLintPass for TypePass {
53     fn check_ty(&mut self, cx: &LateContext, ast_ty: &Ty) {
54         if in_macro(cx, ast_ty.span) {
55             return;
56         }
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() {
60                     if_let_chain! {
61                         [
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),
69                         ],
70                         {
71                             span_help_and_lint(cx,
72                                                BOX_VEC,
73                                                ast_ty.span,
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.");
76                         }
77                     }
78                 } else if match_def_path(cx, did.def_id(), &paths::LINKED_LIST) {
79                     span_help_and_lint(cx,
80                                        LINKEDLIST,
81                                        ast_ty.span,
82                                        "I see you're using a LinkedList! Perhaps you meant some other data structure?",
83                                        "a VecDeque might work");
84                 }
85             }
86         }
87     }
88 }
89
90 #[allow(missing_copy_implementations)]
91 pub struct LetPass;
92
93 /// **What it does:** This lint checks for binding a unit value.
94 ///
95 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So binding one is kind of pointless.
96 ///
97 /// **Known problems:** None
98 ///
99 /// **Example:** `let x = { 1; };`
100 declare_lint! {
101     pub LET_UNIT_VALUE, Warn,
102     "creating a let binding to a value of unit type, which usually can't be used afterwards"
103 }
104
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) {
110                 return;
111             }
112             if is_from_for_desugar(decl) {
113                 return;
114             }
115             span_lint(cx,
116                       LET_UNIT_VALUE,
117                       decl.span,
118                       &format!("this let-binding has unit value. Consider omitting `let {} =`",
119                                snippet(cx, local.pat.span, "..")));
120         }
121     }
122 }
123
124 impl LintPass for LetPass {
125     fn get_lints(&self) -> LintArray {
126         lint_array!(LET_UNIT_VALUE)
127     }
128 }
129
130 impl LateLintPass for LetPass {
131     fn check_decl(&mut self, cx: &LateContext, decl: &Decl) {
132         check_let_unit(cx, decl)
133     }
134 }
135
136 /// **What it does:** This lint checks for comparisons to unit.
137 ///
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.
139 ///
140 /// **Known problems:** None
141 ///
142 /// **Example:** `if { foo(); } == { bar(); } { baz(); }` is equal to `{ foo(); bar(); baz(); }`
143 declare_lint! {
144     pub UNIT_CMP, Warn,
145     "comparing unit values (which is always `true` or `false`, respectively)"
146 }
147
148 #[allow(missing_copy_implementations)]
149 pub struct UnitCmp;
150
151 impl LintPass for UnitCmp {
152     fn get_lints(&self) -> LintArray {
153         lint_array!(UNIT_CMP)
154     }
155 }
156
157 impl LateLintPass for UnitCmp {
158     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
159         if in_macro(cx, expr.span) {
160             return;
161         }
162         if let ExprBinary(ref cmp, ref left, _) = expr.node {
163             let op = cmp.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",
168                     _ => "false",
169                 };
170                 span_lint(cx,
171                           UNIT_CMP,
172                           expr.span,
173                           &format!("{}-comparison of unit values detected. This will always be {}",
174                                    op.as_str(),
175                                    result));
176             }
177         }
178     }
179 }
180
181 pub struct CastPass;
182
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.
184 ///
185 /// Basically, this warns on casting any integer with 32 or more bits to `f32` or any 64-bit integer to `f64`.
186 ///
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.
188 ///
189 /// **Known problems:** None
190 ///
191 /// **Example:** `let x = u64::MAX; x as f64`
192 declare_lint! {
193     pub CAST_PRECISION_LOSS, Allow,
194     "casts that cause loss of precision, e.g `x as f32` where `x: u64`"
195 }
196
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.
198 ///
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.
200 ///
201 /// **Known problems:** None
202 ///
203 /// **Example:** `let y : i8 = -1; y as u64` will return 18446744073709551615
204 declare_lint! {
205     pub CAST_SIGN_LOSS, Allow,
206     "casts from signed types to unsigned types, e.g `x as u32` where `x: i32`"
207 }
208
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.
210 ///
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.
212 ///
213 /// **Known problems:** None
214 ///
215 /// **Example:** `fn as_u8(x: u64) -> u8 { x as u8 }`
216 declare_lint! {
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`"
219 }
220
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.
222 ///
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.
224 ///
225 /// **Known problems:** None
226 ///
227 /// **Example:** `u32::MAX as i32` will yield a value of `-1`.
228 declare_lint! {
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`"
231 }
232
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),
239         _ => 0,
240     };
241     // n == 4 is the usize/isize case
242     if n == 4 {
243         ::std::mem::size_of::<usize>() * 8
244     } else {
245         n
246     }
247 }
248
249 fn is_isize_or_usize(typ: &ty::TyS) -> bool {
250     match typ.sty {
251         ty::TyInt(IntTy::Is) |
252         ty::TyUint(UintTy::Us) => true,
253         _ => false,
254     }
255 }
256
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 {
259         52
260     } else {
261         23
262     };
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 {
266         "64".to_owned()
267     } else if is_isize_or_usize(cast_from) {
268         "32 or 64".to_owned()
269     } else {
270         int_ty_to_nbits(cast_from).to_string()
271     };
272     span_lint(cx,
273               CAST_PRECISION_LOSS,
274               expr.span,
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)",
277                        cast_from,
278                        if cast_to_f64 {
279                            "f64"
280                        } else {
281                            "f32"
282                        },
283                        if arch_dependent {
284                            arch_dependent_str
285                        } else {
286                            ""
287                        },
288                        from_nbits_str,
289                        mantissa_nbits));
290 }
291
292 enum ArchSuffix {
293     _32,
294     _64,
295     None,
296 }
297
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,
307              ArchSuffix::None,
308              to_nbits == from_nbits && cast_unsigned_to_signed,
309              ArchSuffix::None)
310         }
311         (true, false) => {
312             (to_nbits <= 32,
313              if to_nbits == 32 {
314                 ArchSuffix::_64
315             } else {
316                 ArchSuffix::None
317             },
318              to_nbits <= 32 && cast_unsigned_to_signed,
319              ArchSuffix::_32)
320         }
321         (false, true) => {
322             (from_nbits == 64,
323              ArchSuffix::_32,
324              cast_unsigned_to_signed,
325              if from_nbits == 64 {
326                 ArchSuffix::_64
327             } else {
328                 ArchSuffix::_32
329             })
330         }
331     };
332     if span_truncation {
333         span_lint(cx,
334                   CAST_POSSIBLE_TRUNCATION,
335                   expr.span,
336                   &format!("casting {} to {} may truncate the value{}",
337                            cast_from,
338                            cast_to,
339                            match suffix_truncation {
340                                ArchSuffix::_32 => arch_32_suffix,
341                                ArchSuffix::_64 => arch_64_suffix,
342                                ArchSuffix::None => "",
343                            }));
344     }
345     if span_wrap {
346         span_lint(cx,
347                   CAST_POSSIBLE_WRAP,
348                   expr.span,
349                   &format!("casting {} to {} may wrap around the value{}",
350                            cast_from,
351                            cast_to,
352                            match suffix_wrap {
353                                ArchSuffix::_32 => arch_32_suffix,
354                                ArchSuffix::_64 => arch_64_suffix,
355                                ArchSuffix::None => "",
356                            }));
357     }
358 }
359
360 impl LintPass for CastPass {
361     fn get_lints(&self) -> LintArray {
362         lint_array!(CAST_PRECISION_LOSS,
363                     CAST_SIGN_LOSS,
364                     CAST_POSSIBLE_TRUNCATION,
365                     CAST_POSSIBLE_WRAP)
366     }
367 }
368
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()) {
375                     (true, false) => {
376                         let from_nbits = int_ty_to_nbits(cast_from);
377                         let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
378                             32
379                         } else {
380                             64
381                         };
382                         if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
383                             span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
384                         }
385                     }
386                     (false, true) => {
387                         span_lint(cx,
388                                   CAST_POSSIBLE_TRUNCATION,
389                                   expr.span,
390                                   &format!("casting {} to {} may truncate the value", cast_from, cast_to));
391                         if !cast_to.is_signed() {
392                             span_lint(cx,
393                                       CAST_SIGN_LOSS,
394                                       expr.span,
395                                       &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
396                         }
397                     }
398                     (true, true) => {
399                         if cast_from.is_signed() && !cast_to.is_signed() {
400                             span_lint(cx,
401                                       CAST_SIGN_LOSS,
402                                       expr.span,
403                                       &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
404                         }
405                         check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
406                     }
407                     (false, false) => {
408                         if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty,
409                                                                                            &cast_to.sty) {
410                             span_lint(cx,
411                                       CAST_POSSIBLE_TRUNCATION,
412                                       expr.span,
413                                       "casting f64 to f32 may truncate the value");
414                         }
415                     }
416                 }
417             }
418         }
419     }
420 }
421
422 /// **What it does:** This lint checks for types used in structs, parameters and `let` declarations above a certain complexity threshold.
423 ///
424 /// **Why is this bad?** Too complex types make the code less readable. Consider using a `type` definition to simplify them.
425 ///
426 /// **Known problems:** None
427 ///
428 /// **Example:** `struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }`
429 declare_lint! {
430     pub TYPE_COMPLEXITY, Warn,
431     "usage of very complex types; recommends factoring out parts into `type` definitions"
432 }
433
434 #[allow(missing_copy_implementations)]
435 pub struct TypeComplexityPass {
436     threshold: u64,
437 }
438
439 impl TypeComplexityPass {
440     pub fn new(threshold: u64) -> Self {
441         TypeComplexityPass { threshold: threshold }
442     }
443 }
444
445 impl LintPass for TypeComplexityPass {
446     fn get_lints(&self) -> LintArray {
447         lint_array!(TYPE_COMPLEXITY)
448     }
449 }
450
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);
454     }
455
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);
459     }
460
461     fn check_item(&mut self, cx: &LateContext, item: &Item) {
462         match item.node {
463             ItemStatic(ref ty, _, _) |
464             ItemConst(ref ty, _) => self.check_type(cx, ty),
465             // functions, enums, structs, impls and traits are covered
466             _ => (),
467         }
468     }
469
470     fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
471         match item.node {
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
476             _ => (),
477         }
478     }
479
480     fn check_impl_item(&mut self, cx: &LateContext, item: &ImplItem) {
481         match item.node {
482             ImplItemKind::Const(ref ty, _) |
483             ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
484             // methods are covered by check_fn
485             _ => (),
486         }
487     }
488
489     fn check_local(&mut self, cx: &LateContext, local: &Local) {
490         if let Some(ref ty) = local.ty {
491             self.check_type(cx, ty);
492         }
493     }
494 }
495
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);
500         }
501         if let Return(ref ty) = decl.output {
502             self.check_type(cx, ty);
503         }
504     }
505
506     fn check_type(&self, cx: &LateContext, ty: &Ty) {
507         if in_macro(cx, ty.span) {
508             return;
509         }
510         let score = {
511             let mut visitor = TypeComplexityVisitor {
512                 score: 0,
513                 nest: 1,
514             };
515             visitor.visit_ty(ty);
516             visitor.score
517         };
518
519         if score > self.threshold {
520             span_lint(cx,
521                       TYPE_COMPLEXITY,
522                       ty.span,
523                       "very complex type used. Consider factoring parts into `type` definitions");
524         }
525     }
526 }
527
528 /// Walks a type and assigns a complexity score to it.
529 struct TypeComplexityVisitor {
530     /// total complexity score of the type
531     score: u64,
532     /// current nesting level
533     nest: u64,
534 }
535
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),
541
542             // the "normal" components of a type: named types, arrays/tuples
543             TyPath(..) |
544             TyVec(..) |
545             TyTup(..) |
546             TyFixedLengthVec(..) => (10 * self.nest, 1),
547
548             // "Sum" of trait bounds
549             TyObjectSum(..) => (20 * self.nest, 0),
550
551             // function types and "for<...>" bring a lot of overhead
552             TyBareFn(..) |
553             TyPolyTraitRef(..) => (50 * self.nest, 1),
554
555             _ => (0, 0),
556         };
557         self.score += add_score;
558         self.nest += sub_nest;
559         walk_ty(self, ty);
560         self.nest -= sub_nest;
561     }
562 }
563
564 /// **What it does:** This lint points out expressions where a character literal is casted to `u8` and suggests using a byte literal instead.
565 ///
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`.
567 ///
568 /// **Known problems:** None
569 ///
570 /// **Example:** `'x' as u8`
571 declare_lint! {
572     pub CHAR_LIT_AS_U8, Warn,
573     "Casting a character literal to u8"
574 }
575
576 pub struct CharLitAsU8;
577
578 impl LintPass for CharLitAsU8 {
579     fn get_lints(&self) -> LintArray {
580         lint_array!(CHAR_LIT_AS_U8)
581     }
582 }
583
584 impl LateLintPass for CharLitAsU8 {
585     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
586         use syntax::ast::{LitKind, UintTy};
587
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 \
594                                    truncates them";
595                         let help = format!("Consider using a byte literal \
596                                             instead:\nb{}",
597                                            snippet(cx, e.span, "'x'"));
598                         span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
599                     }
600                 }
601             }
602         }
603     }
604 }
605
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.
607 ///
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.
609 ///
610 /// **Known problems:** None
611 ///
612 /// **Example:** `vec.len() <= 0`, `100 > std::i32::MAX`
613 declare_lint! {
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"
617 }
618
619 pub struct AbsurdExtremeComparisons;
620
621 impl LintPass for AbsurdExtremeComparisons {
622     fn get_lints(&self) -> LintArray {
623         lint_array!(ABSURD_EXTREME_COMPARISONS)
624     }
625 }
626
627 enum ExtremeType {
628     Minimum,
629     Maximum,
630 }
631
632 struct ExtremeExpr<'a> {
633     which: ExtremeType,
634     expr: &'a Expr,
635 }
636
637 enum AbsurdComparisonResult {
638     AlwaysFalse,
639     AlwaysTrue,
640     InequalityImpossible,
641 }
642
643
644
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>;
651
652     let normalized = normalize_comparison(op, lhs, rhs);
653     let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
654         val
655     } else {
656         return None;
657     };
658
659     let lx = detect_extreme_expr(cx, normalized_lhs);
660     let rx = detect_extreme_expr(cx, normalized_rhs);
661
662     Some(match rel {
663         Rel::Lt => {
664             match (lx, rx) {
665                 (Some(l @ Extr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
666                 (_, Some(r @ Extr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
667                 _ => return None,
668             }
669         }
670         Rel::Le => {
671             match (lx, rx) {
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
676                 _ => return None,
677             }
678         }
679         Rel::Ne | Rel::Eq => return None,
680     })
681 }
682
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::*;
689
690     let ty = &cx.tcx.expr_ty(expr).sty;
691
692     match *ty {
693         ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
694         _ => return None,
695     };
696
697     let cv = match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
698         Ok(val) => val,
699         Err(_) => return None,
700     };
701
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,
716
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,
730
731         _ => return None,
732     };
733     Some(ExtremeExpr {
734         which: which,
735         expr: expr,
736     })
737 }
738
739 impl LateLintPass for AbsurdExtremeComparisons {
740     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
741         use types::ExtremeType::*;
742         use types::AbsurdComparisonResult::*;
743
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";
749
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 {} == {} \
755                                      instead",
756                                     snippet(cx, lhs.span, "lhs"),
757                                     snippet(cx, rhs.span, "rhs"))
758                         }
759                     };
760
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",
766                                        },
767                                        conclusion);
768
769                     span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
770                 }
771             }
772         }
773     }
774 }
775
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.
777 ///
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`.
779 ///
780 /// **Known problems:** https://github.com/Manishearth/rust-clippy/issues/886
781 ///
782 /// **Example:** `let x : u8 = ...; (x as u32) > 300`
783 declare_lint! {
784     pub INVALID_UPCAST_COMPARISONS, Allow,
785     "a comparison involving an upcast which is always true or false"
786 }
787
788 pub struct InvalidUpcastComparisons;
789
790 impl LintPass for InvalidUpcastComparisons {
791     fn get_lints(&self) -> LintArray {
792         lint_array!(INVALID_UPCAST_COMPARISONS)
793     }
794 }
795
796 #[derive(Copy, Clone, Debug, Eq)]
797 enum FullInt {
798     S(i64),
799     U(u64),
800 }
801
802 impl FullInt {
803     #[allow(cast_sign_loss)]
804     fn cmp_s_u(s: i64, u: u64) -> Ordering {
805         if s < 0 {
806             Ordering::Less
807         } else if u > (i64::max_value() as u64) {
808             Ordering::Greater
809         } else {
810             (s as u64).cmp(&u)
811         }
812     }
813 }
814
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
818     }
819 }
820
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(),
828         })
829     }
830 }
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")
834     }
835 }
836
837
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};
841     use std::*;
842
843     if let ExprCast(ref cast_exp, _) = expr.node {
844         match cx.tcx.expr_ty(cast_exp).sty {
845             TyInt(int_ty) => {
846                 Some(match int_ty {
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)),
852                 })
853             }
854             TyUint(uint_ty) => {
855                 Some(match uint_ty {
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)),
861                 })
862             }
863             _ => None,
864         }
865     } else {
866         None
867     }
868 }
869
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;
875
876     match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
877         Ok(val) => {
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),
882                     _ => unreachable!(),
883                 })
884             } else {
885                 None
886             }
887         }
888         Err(_) => None,
889     }
890 }
891
892 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
893     if let ExprCast(ref cast_val, _) = expr.node {
894         span_lint(cx,
895                   INVALID_UPCAST_COMPARISONS,
896                   *span,
897                   &format!(
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" },
901             ));
902     }
903 }
904
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::*;
908
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);
914                 }
915             } else if match rel {
916                 Rel::Lt => {
917                     if invert {
918                         norm_rhs_val < lb
919                     } else {
920                         ub < norm_rhs_val
921                     }
922                 }
923                 Rel::Le => {
924                     if invert {
925                         norm_rhs_val <= lb
926                     } else {
927                         ub <= norm_rhs_val
928                     }
929                 }
930                 Rel::Eq | Rel::Ne => unreachable!(),
931             } {
932                 err_upcast_comparison(cx, span, lhs, true)
933             } else if match rel {
934                 Rel::Lt => {
935                     if invert {
936                         norm_rhs_val >= ub
937                     } else {
938                         lb >= norm_rhs_val
939                     }
940                 }
941                 Rel::Le => {
942                     if invert {
943                         norm_rhs_val > ub
944                     } else {
945                         lb > norm_rhs_val
946                     }
947                 }
948                 Rel::Eq | Rel::Ne => unreachable!(),
949             } {
950                 err_upcast_comparison(cx, span, lhs, false)
951             }
952         }
953     }
954 }
955
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 {
959
960             let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
961             let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
962                 val
963             } else {
964                 return;
965             };
966
967             let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
968             let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
969
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);
972         }
973     }
974 }