]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/types.rs
Merge branch 'feature/gh-pages-docs' of https://github.com/killercup/rust-clippy...
[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, higher, in_external_macro, in_macro, 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
20 /// `Box` it, you just add another level of indirection without any benefit whatsoever.
21 ///
22 /// **Known problems:** None
23 ///
24 /// **Example:**
25 /// ```rust
26 /// struct X {
27 ///     values: Box<Vec<Foo>>,
28 /// }
29 /// ```
30 declare_lint! {
31     pub BOX_VEC, Warn,
32     "usage of `Box<Vec<T>>`, vector elements are already on the heap"
33 }
34
35 /// **What it does:** This lint checks for usage of any `LinkedList`, suggesting to use a `Vec` or
36 /// a `VecDeque` (formerly called `RingBuf`).
37 ///
38 /// **Why is this bad?** Gankro says:
39 ///
40 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of pointers and indirection.
41 /// > It wastes memory, it has terrible cache locality, and is all-around slow. `RingBuf`, while
42 /// > "only" amortized for push/pop, should be faster in the general case for almost every possible
43 /// > workload, and isn't even amortized at all if you can predict the capacity you need.
44 /// >
45 /// > `LinkedList`s are only really good if you're doing a lot of merging or splitting of lists.
46 /// > This is because they can just mangle some pointers instead of actually copying the data. Even
47 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf` can still be better
48 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
49 ///
50 /// **Known problems:** False positives – the instances where using a `LinkedList` makes sense are
51 /// few and far between, but they can still happen.
52 ///
53 /// **Example:**
54 /// ```rust
55 /// let x = LinkedList::new();
56 /// ```
57 declare_lint! {
58     pub LINKEDLIST, Warn,
59     "usage of LinkedList, usually a vector is faster, or a more specialized data \
60      structure like a VecDeque"
61 }
62
63 impl LintPass for TypePass {
64     fn get_lints(&self) -> LintArray {
65         lint_array!(BOX_VEC, LINKEDLIST)
66     }
67 }
68
69 impl LateLintPass for TypePass {
70     fn check_ty(&mut self, cx: &LateContext, ast_ty: &Ty) {
71         if in_macro(cx, ast_ty.span) {
72             return;
73         }
74         if let Some(did) = cx.tcx.def_map.borrow().get(&ast_ty.id) {
75             if let def::Def::Struct(..) = did.full_def() {
76                 if Some(did.full_def().def_id()) == cx.tcx.lang_items.owned_box() {
77                     if_let_chain! {[
78                         let TyPath(_, ref path) = ast_ty.node,
79                         let Some(ref last) = path.segments.last(),
80                         let PathParameters::AngleBracketedParameters(ref ag) = last.parameters,
81                         let Some(ref vec) = ag.types.get(0),
82                         let Some(did) = cx.tcx.def_map.borrow().get(&vec.id),
83                         let def::Def::Struct(..) = did.full_def(),
84                         match_def_path(cx, did.full_def().def_id(), &paths::VEC),
85                     ], {
86                         span_help_and_lint(cx,
87                                            BOX_VEC,
88                                            ast_ty.span,
89                                            "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
90                                            "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.");
91                     }}
92                 } else if match_def_path(cx, did.full_def().def_id(), &paths::LINKED_LIST) {
93                     span_help_and_lint(cx,
94                                        LINKEDLIST,
95                                        ast_ty.span,
96                                        "I see you're using a LinkedList! Perhaps you meant some other data structure?",
97                                        "a VecDeque might work");
98                 }
99             }
100         }
101     }
102 }
103
104 #[allow(missing_copy_implementations)]
105 pub struct LetPass;
106
107 /// **What it does:** This lint checks for binding a unit value.
108 ///
109 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So binding one is kind of pointless.
110 ///
111 /// **Known problems:** None
112 ///
113 /// **Example:** `let x = { 1; };`
114 declare_lint! {
115     pub LET_UNIT_VALUE, Warn,
116     "creating a let binding to a value of unit type, which usually can't be used afterwards"
117 }
118
119 fn check_let_unit(cx: &LateContext, decl: &Decl) {
120     if let DeclLocal(ref local) = decl.node {
121         let bindtype = &cx.tcx.pat_ty(&local.pat).sty;
122         if *bindtype == ty::TyTuple(&[]) {
123             if in_external_macro(cx, decl.span) || in_macro(cx, local.pat.span) {
124                 return;
125             }
126             if higher::is_from_for_desugar(decl) {
127                 return;
128             }
129             span_lint(cx,
130                       LET_UNIT_VALUE,
131                       decl.span,
132                       &format!("this let-binding has unit value. Consider omitting `let {} =`",
133                                snippet(cx, local.pat.span, "..")));
134         }
135     }
136 }
137
138 impl LintPass for LetPass {
139     fn get_lints(&self) -> LintArray {
140         lint_array!(LET_UNIT_VALUE)
141     }
142 }
143
144 impl LateLintPass for LetPass {
145     fn check_decl(&mut self, cx: &LateContext, decl: &Decl) {
146         check_let_unit(cx, decl)
147     }
148 }
149
150 /// **What it does:** This lint checks for comparisons to unit.
151 ///
152 /// **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.
153 ///
154 /// **Known problems:** None
155 ///
156 /// **Example:** `if { foo(); } == { bar(); } { baz(); }` is equal to `{ foo(); bar(); baz(); }`
157 declare_lint! {
158     pub UNIT_CMP, Warn,
159     "comparing unit values (which is always `true` or `false`, respectively)"
160 }
161
162 #[allow(missing_copy_implementations)]
163 pub struct UnitCmp;
164
165 impl LintPass for UnitCmp {
166     fn get_lints(&self) -> LintArray {
167         lint_array!(UNIT_CMP)
168     }
169 }
170
171 impl LateLintPass for UnitCmp {
172     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
173         if in_macro(cx, expr.span) {
174             return;
175         }
176         if let ExprBinary(ref cmp, ref left, _) = expr.node {
177             let op = cmp.node;
178             let sty = &cx.tcx.expr_ty(left).sty;
179             if *sty == ty::TyTuple(&[]) && op.is_comparison() {
180                 let result = match op {
181                     BiEq | BiLe | BiGe => "true",
182                     _ => "false",
183                 };
184                 span_lint(cx,
185                           UNIT_CMP,
186                           expr.span,
187                           &format!("{}-comparison of unit values detected. This will always be {}",
188                                    op.as_str(),
189                                    result));
190             }
191         }
192     }
193 }
194
195 pub struct CastPass;
196
197 /// **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.
198 ///
199 /// Basically, this warns on casting any integer with 32 or more bits to `f32` or any 64-bit integer to `f64`.
200 ///
201 /// **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.
202 ///
203 /// **Known problems:** None
204 ///
205 /// **Example:** `let x = u64::MAX; x as f64`
206 declare_lint! {
207     pub CAST_PRECISION_LOSS, Allow,
208     "casts that cause loss of precision, e.g `x as f32` where `x: u64`"
209 }
210
211 /// **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.
212 ///
213 /// **Why is this bad?** Possibly surprising results. You can activate this lint as a one-time check to see where numerical wrapping can arise.
214 ///
215 /// **Known problems:** None
216 ///
217 /// **Example:** `let y : i8 = -1; y as u64` will return 18446744073709551615
218 declare_lint! {
219     pub CAST_SIGN_LOSS, Allow,
220     "casts from signed types to unsigned types, e.g `x as u32` where `x: i32`"
221 }
222
223 /// **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.
224 ///
225 /// **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.
226 ///
227 /// **Known problems:** None
228 ///
229 /// **Example:** `fn as_u8(x: u64) -> u8 { x as u8 }`
230 declare_lint! {
231     pub CAST_POSSIBLE_TRUNCATION, Allow,
232     "casts that may cause truncation of the value, e.g `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
233 }
234
235 /// **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.
236 ///
237 /// **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.
238 ///
239 /// **Known problems:** None
240 ///
241 /// **Example:** `u32::MAX as i32` will yield a value of `-1`.
242 declare_lint! {
243     pub CAST_POSSIBLE_WRAP, Allow,
244     "casts that may cause wrapping around the value, e.g `x as i32` where `x: u32` and `x > i32::MAX`"
245 }
246
247 /// Returns the size in bits of an integral type.
248 /// Will return 0 if the type is not an int or uint variant
249 fn int_ty_to_nbits(typ: &ty::TyS) -> usize {
250     let n = match typ.sty {
251         ty::TyInt(i) => 4 << (i as usize),
252         ty::TyUint(u) => 4 << (u as usize),
253         _ => 0,
254     };
255     // n == 4 is the usize/isize case
256     if n == 4 {
257         ::std::mem::size_of::<usize>() * 8
258     } else {
259         n
260     }
261 }
262
263 fn is_isize_or_usize(typ: &ty::TyS) -> bool {
264     match typ.sty {
265         ty::TyInt(IntTy::Is) |
266         ty::TyUint(UintTy::Us) => true,
267         _ => false,
268     }
269 }
270
271 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to_f64: bool) {
272     let mantissa_nbits = if cast_to_f64 {
273         52
274     } else {
275         23
276     };
277     let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
278     let arch_dependent_str = "on targets with 64-bit wide pointers ";
279     let from_nbits_str = if arch_dependent {
280         "64".to_owned()
281     } else if is_isize_or_usize(cast_from) {
282         "32 or 64".to_owned()
283     } else {
284         int_ty_to_nbits(cast_from).to_string()
285     };
286     span_lint(cx,
287               CAST_PRECISION_LOSS,
288               expr.span,
289               &format!("casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
290                         is only {4} bits wide)",
291                        cast_from,
292                        if cast_to_f64 {
293                            "f64"
294                        } else {
295                            "f32"
296                        },
297                        if arch_dependent {
298                            arch_dependent_str
299                        } else {
300                            ""
301                        },
302                        from_nbits_str,
303                        mantissa_nbits));
304 }
305
306 enum ArchSuffix {
307     _32,
308     _64,
309     None,
310 }
311
312 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to: &ty::TyS) {
313     let arch_64_suffix = " on targets with 64-bit wide pointers";
314     let arch_32_suffix = " on targets with 32-bit wide pointers";
315     let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
316     let (from_nbits, to_nbits) = (int_ty_to_nbits(cast_from), int_ty_to_nbits(cast_to));
317     let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) = match (is_isize_or_usize(cast_from),
318                                                                               is_isize_or_usize(cast_to)) {
319         (true, true) | (false, false) => {
320             (to_nbits < from_nbits,
321              ArchSuffix::None,
322              to_nbits == from_nbits && cast_unsigned_to_signed,
323              ArchSuffix::None)
324         }
325         (true, false) => {
326             (to_nbits <= 32,
327              if to_nbits == 32 {
328                 ArchSuffix::_64
329             } else {
330                 ArchSuffix::None
331             },
332              to_nbits <= 32 && cast_unsigned_to_signed,
333              ArchSuffix::_32)
334         }
335         (false, true) => {
336             (from_nbits == 64,
337              ArchSuffix::_32,
338              cast_unsigned_to_signed,
339              if from_nbits == 64 {
340                 ArchSuffix::_64
341             } else {
342                 ArchSuffix::_32
343             })
344         }
345     };
346     if span_truncation {
347         span_lint(cx,
348                   CAST_POSSIBLE_TRUNCATION,
349                   expr.span,
350                   &format!("casting {} to {} may truncate the value{}",
351                            cast_from,
352                            cast_to,
353                            match suffix_truncation {
354                                ArchSuffix::_32 => arch_32_suffix,
355                                ArchSuffix::_64 => arch_64_suffix,
356                                ArchSuffix::None => "",
357                            }));
358     }
359     if span_wrap {
360         span_lint(cx,
361                   CAST_POSSIBLE_WRAP,
362                   expr.span,
363                   &format!("casting {} to {} may wrap around the value{}",
364                            cast_from,
365                            cast_to,
366                            match suffix_wrap {
367                                ArchSuffix::_32 => arch_32_suffix,
368                                ArchSuffix::_64 => arch_64_suffix,
369                                ArchSuffix::None => "",
370                            }));
371     }
372 }
373
374 impl LintPass for CastPass {
375     fn get_lints(&self) -> LintArray {
376         lint_array!(CAST_PRECISION_LOSS,
377                     CAST_SIGN_LOSS,
378                     CAST_POSSIBLE_TRUNCATION,
379                     CAST_POSSIBLE_WRAP)
380     }
381 }
382
383 impl LateLintPass for CastPass {
384     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
385         if let ExprCast(ref ex, _) = expr.node {
386             let (cast_from, cast_to) = (cx.tcx.expr_ty(ex), cx.tcx.expr_ty(expr));
387             if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
388                 match (cast_from.is_integral(), cast_to.is_integral()) {
389                     (true, false) => {
390                         let from_nbits = int_ty_to_nbits(cast_from);
391                         let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
392                             32
393                         } else {
394                             64
395                         };
396                         if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
397                             span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
398                         }
399                     }
400                     (false, true) => {
401                         span_lint(cx,
402                                   CAST_POSSIBLE_TRUNCATION,
403                                   expr.span,
404                                   &format!("casting {} to {} may truncate the value", cast_from, cast_to));
405                         if !cast_to.is_signed() {
406                             span_lint(cx,
407                                       CAST_SIGN_LOSS,
408                                       expr.span,
409                                       &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
410                         }
411                     }
412                     (true, true) => {
413                         if cast_from.is_signed() && !cast_to.is_signed() {
414                             span_lint(cx,
415                                       CAST_SIGN_LOSS,
416                                       expr.span,
417                                       &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
418                         }
419                         check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
420                     }
421                     (false, false) => {
422                         if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty,
423                                                                                            &cast_to.sty) {
424                             span_lint(cx,
425                                       CAST_POSSIBLE_TRUNCATION,
426                                       expr.span,
427                                       "casting f64 to f32 may truncate the value");
428                         }
429                     }
430                 }
431             }
432         }
433     }
434 }
435
436 /// **What it does:** This lint checks for types used in structs, parameters and `let` declarations above a certain complexity threshold.
437 ///
438 /// **Why is this bad?** Too complex types make the code less readable. Consider using a `type` definition to simplify them.
439 ///
440 /// **Known problems:** None
441 ///
442 /// **Example:** `struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }`
443 declare_lint! {
444     pub TYPE_COMPLEXITY, Warn,
445     "usage of very complex types; recommends factoring out parts into `type` definitions"
446 }
447
448 #[allow(missing_copy_implementations)]
449 pub struct TypeComplexityPass {
450     threshold: u64,
451 }
452
453 impl TypeComplexityPass {
454     pub fn new(threshold: u64) -> Self {
455         TypeComplexityPass { threshold: threshold }
456     }
457 }
458
459 impl LintPass for TypeComplexityPass {
460     fn get_lints(&self) -> LintArray {
461         lint_array!(TYPE_COMPLEXITY)
462     }
463 }
464
465 impl LateLintPass for TypeComplexityPass {
466     fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
467         self.check_fndecl(cx, decl);
468     }
469
470     fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
471         // enum variants are also struct fields now
472         self.check_type(cx, &field.ty);
473     }
474
475     fn check_item(&mut self, cx: &LateContext, item: &Item) {
476         match item.node {
477             ItemStatic(ref ty, _, _) |
478             ItemConst(ref ty, _) => self.check_type(cx, ty),
479             // functions, enums, structs, impls and traits are covered
480             _ => (),
481         }
482     }
483
484     fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
485         match item.node {
486             ConstTraitItem(ref ty, _) |
487             TypeTraitItem(_, Some(ref ty)) => self.check_type(cx, ty),
488             MethodTraitItem(MethodSig { ref decl, .. }, None) => self.check_fndecl(cx, decl),
489             // methods with default impl are covered by check_fn
490             _ => (),
491         }
492     }
493
494     fn check_impl_item(&mut self, cx: &LateContext, item: &ImplItem) {
495         match item.node {
496             ImplItemKind::Const(ref ty, _) |
497             ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
498             // methods are covered by check_fn
499             _ => (),
500         }
501     }
502
503     fn check_local(&mut self, cx: &LateContext, local: &Local) {
504         if let Some(ref ty) = local.ty {
505             self.check_type(cx, ty);
506         }
507     }
508 }
509
510 impl TypeComplexityPass {
511     fn check_fndecl(&self, cx: &LateContext, decl: &FnDecl) {
512         for arg in &decl.inputs {
513             self.check_type(cx, &arg.ty);
514         }
515         if let Return(ref ty) = decl.output {
516             self.check_type(cx, ty);
517         }
518     }
519
520     fn check_type(&self, cx: &LateContext, ty: &Ty) {
521         if in_macro(cx, ty.span) {
522             return;
523         }
524         let score = {
525             let mut visitor = TypeComplexityVisitor {
526                 score: 0,
527                 nest: 1,
528             };
529             visitor.visit_ty(ty);
530             visitor.score
531         };
532
533         if score > self.threshold {
534             span_lint(cx,
535                       TYPE_COMPLEXITY,
536                       ty.span,
537                       "very complex type used. Consider factoring parts into `type` definitions");
538         }
539     }
540 }
541
542 /// Walks a type and assigns a complexity score to it.
543 struct TypeComplexityVisitor {
544     /// total complexity score of the type
545     score: u64,
546     /// current nesting level
547     nest: u64,
548 }
549
550 impl<'v> Visitor<'v> for TypeComplexityVisitor {
551     fn visit_ty(&mut self, ty: &'v Ty) {
552         let (add_score, sub_nest) = match ty.node {
553             // _, &x and *x have only small overhead; don't mess with nesting level
554             TyInfer | TyPtr(..) | TyRptr(..) => (1, 0),
555
556             // the "normal" components of a type: named types, arrays/tuples
557             TyPath(..) |
558             TyVec(..) |
559             TyTup(..) |
560             TyFixedLengthVec(..) => (10 * self.nest, 1),
561
562             // "Sum" of trait bounds
563             TyObjectSum(..) => (20 * self.nest, 0),
564
565             // function types and "for<...>" bring a lot of overhead
566             TyBareFn(..) |
567             TyPolyTraitRef(..) => (50 * self.nest, 1),
568
569             _ => (0, 0),
570         };
571         self.score += add_score;
572         self.nest += sub_nest;
573         walk_ty(self, ty);
574         self.nest -= sub_nest;
575     }
576 }
577
578 /// **What it does:** This lint points out expressions where a character literal is casted to `u8` and suggests using a byte literal instead.
579 ///
580 /// **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`.
581 ///
582 /// **Known problems:** None
583 ///
584 /// **Example:** `'x' as u8`
585 declare_lint! {
586     pub CHAR_LIT_AS_U8, Warn,
587     "Casting a character literal to u8"
588 }
589
590 pub struct CharLitAsU8;
591
592 impl LintPass for CharLitAsU8 {
593     fn get_lints(&self) -> LintArray {
594         lint_array!(CHAR_LIT_AS_U8)
595     }
596 }
597
598 impl LateLintPass for CharLitAsU8 {
599     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
600         use syntax::ast::{LitKind, UintTy};
601
602         if let ExprCast(ref e, _) = expr.node {
603             if let ExprLit(ref l) = e.node {
604                 if let LitKind::Char(_) = l.node {
605                     if ty::TyUint(UintTy::U8) == cx.tcx.expr_ty(expr).sty && !in_macro(cx, expr.span) {
606                         let msg = "casting character literal to u8. `char`s \
607                                    are 4 bytes wide in rust, so casting to u8 \
608                                    truncates them";
609                         let help = format!("Consider using a byte literal \
610                                             instead:\nb{}",
611                                            snippet(cx, e.span, "'x'"));
612                         span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
613                     }
614                 }
615             }
616         }
617     }
618 }
619
620 /// **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.
621 ///
622 /// **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.
623 ///
624 /// **Known problems:** None
625 ///
626 /// **Example:** `vec.len() <= 0`, `100 > std::i32::MAX`
627 declare_lint! {
628     pub ABSURD_EXTREME_COMPARISONS, Warn,
629     "a comparison involving a maximum or minimum value involves a case that is always \
630     true or always false"
631 }
632
633 pub struct AbsurdExtremeComparisons;
634
635 impl LintPass for AbsurdExtremeComparisons {
636     fn get_lints(&self) -> LintArray {
637         lint_array!(ABSURD_EXTREME_COMPARISONS)
638     }
639 }
640
641 enum ExtremeType {
642     Minimum,
643     Maximum,
644 }
645
646 struct ExtremeExpr<'a> {
647     which: ExtremeType,
648     expr: &'a Expr,
649 }
650
651 enum AbsurdComparisonResult {
652     AlwaysFalse,
653     AlwaysTrue,
654     InequalityImpossible,
655 }
656
657
658
659 fn detect_absurd_comparison<'a>(cx: &LateContext, op: BinOp_, lhs: &'a Expr, rhs: &'a Expr)
660                                 -> Option<(ExtremeExpr<'a>, AbsurdComparisonResult)> {
661     use types::ExtremeType::*;
662     use types::AbsurdComparisonResult::*;
663     use utils::comparisons::*;
664     type Extr<'a> = ExtremeExpr<'a>;
665
666     let normalized = normalize_comparison(op, lhs, rhs);
667     let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
668         val
669     } else {
670         return None;
671     };
672
673     let lx = detect_extreme_expr(cx, normalized_lhs);
674     let rx = detect_extreme_expr(cx, normalized_rhs);
675
676     Some(match rel {
677         Rel::Lt => {
678             match (lx, rx) {
679                 (Some(l @ Extr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
680                 (_, Some(r @ Extr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
681                 _ => return None,
682             }
683         }
684         Rel::Le => {
685             match (lx, rx) {
686                 (Some(l @ Extr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
687                 (Some(l @ Extr { which: Maximum, .. }), _) => (l, InequalityImpossible), //max <= x
688                 (_, Some(r @ Extr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
689                 (_, Some(r @ Extr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
690                 _ => return None,
691             }
692         }
693         Rel::Ne | Rel::Eq => return None,
694     })
695 }
696
697 fn detect_extreme_expr<'a>(cx: &LateContext, expr: &'a Expr) -> Option<ExtremeExpr<'a>> {
698     use rustc::middle::const_val::ConstVal::*;
699     use rustc_const_math::*;
700     use rustc_const_eval::EvalHint::ExprTypeChecked;
701     use rustc_const_eval::*;
702     use types::ExtremeType::*;
703
704     let ty = &cx.tcx.expr_ty(expr).sty;
705
706     match *ty {
707         ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
708         _ => return None,
709     };
710
711     let cv = match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
712         Ok(val) => val,
713         Err(_) => return None,
714     };
715
716     let which = match (ty, cv) {
717         (&ty::TyBool, Bool(false)) |
718         (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MIN)))) |
719         (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MIN)))) |
720         (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MIN))) |
721         (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MIN))) |
722         (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MIN))) |
723         (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MIN))) |
724         (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MIN)))) |
725         (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MIN)))) |
726         (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MIN))) |
727         (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MIN))) |
728         (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MIN))) |
729         (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MIN))) => Minimum,
730
731         (&ty::TyBool, Bool(true)) |
732         (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MAX)))) |
733         (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MAX)))) |
734         (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MAX))) |
735         (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MAX))) |
736         (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MAX))) |
737         (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MAX))) |
738         (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MAX)))) |
739         (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MAX)))) |
740         (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MAX))) |
741         (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MAX))) |
742         (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MAX))) |
743         (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MAX))) => Maximum,
744
745         _ => return None,
746     };
747     Some(ExtremeExpr {
748         which: which,
749         expr: expr,
750     })
751 }
752
753 impl LateLintPass for AbsurdExtremeComparisons {
754     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
755         use types::ExtremeType::*;
756         use types::AbsurdComparisonResult::*;
757
758         if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
759             if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
760                 if !in_macro(cx, expr.span) {
761                     let msg = "this comparison involving the minimum or maximum element for this \
762                                type contains a case that is always true or always false";
763
764                     let conclusion = match result {
765                         AlwaysFalse => "this comparison is always false".to_owned(),
766                         AlwaysTrue => "this comparison is always true".to_owned(),
767                         InequalityImpossible => {
768                             format!("the case where the two sides are not equal never occurs, consider using {} == {} \
769                                      instead",
770                                     snippet(cx, lhs.span, "lhs"),
771                                     snippet(cx, rhs.span, "rhs"))
772                         }
773                     };
774
775                     let help = format!("because {} is the {} value for this type, {}",
776                                        snippet(cx, culprit.expr.span, "x"),
777                                        match culprit.which {
778                                            Minimum => "minimum",
779                                            Maximum => "maximum",
780                                        },
781                                        conclusion);
782
783                     span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
784                 }
785             }
786         }
787     }
788 }
789
790 /// **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.
791 ///
792 /// **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`.
793 ///
794 /// **Known problems:** https://github.com/Manishearth/rust-clippy/issues/886
795 ///
796 /// **Example:** `let x : u8 = ...; (x as u32) > 300`
797 declare_lint! {
798     pub INVALID_UPCAST_COMPARISONS, Allow,
799     "a comparison involving an upcast which is always true or false"
800 }
801
802 pub struct InvalidUpcastComparisons;
803
804 impl LintPass for InvalidUpcastComparisons {
805     fn get_lints(&self) -> LintArray {
806         lint_array!(INVALID_UPCAST_COMPARISONS)
807     }
808 }
809
810 #[derive(Copy, Clone, Debug, Eq)]
811 enum FullInt {
812     S(i64),
813     U(u64),
814 }
815
816 impl FullInt {
817     #[allow(cast_sign_loss)]
818     fn cmp_s_u(s: i64, u: u64) -> Ordering {
819         if s < 0 {
820             Ordering::Less
821         } else if u > (i64::max_value() as u64) {
822             Ordering::Greater
823         } else {
824             (s as u64).cmp(&u)
825         }
826     }
827 }
828
829 impl PartialEq for FullInt {
830     fn eq(&self, other: &Self) -> bool {
831         self.partial_cmp(other).expect("partial_cmp only returns Some(_)") == Ordering::Equal
832     }
833 }
834
835 impl PartialOrd for FullInt {
836     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
837         Some(match (self, other) {
838             (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
839             (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
840             (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
841             (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
842         })
843     }
844 }
845 impl Ord for FullInt {
846     fn cmp(&self, other: &Self) -> Ordering {
847         self.partial_cmp(other).expect("partial_cmp for FullInt can never return None")
848     }
849 }
850
851
852 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
853     use rustc::ty::TypeVariants::{TyInt, TyUint};
854     use syntax::ast::{IntTy, UintTy};
855     use std::*;
856
857     if let ExprCast(ref cast_exp, _) = expr.node {
858         match cx.tcx.expr_ty(cast_exp).sty {
859             TyInt(int_ty) => {
860                 Some(match int_ty {
861                     IntTy::I8 => (FullInt::S(i8::min_value() as i64), FullInt::S(i8::max_value() as i64)),
862                     IntTy::I16 => (FullInt::S(i16::min_value() as i64), FullInt::S(i16::max_value() as i64)),
863                     IntTy::I32 => (FullInt::S(i32::min_value() as i64), FullInt::S(i32::max_value() as i64)),
864                     IntTy::I64 => (FullInt::S(i64::min_value() as i64), FullInt::S(i64::max_value() as i64)),
865                     IntTy::Is => (FullInt::S(isize::min_value() as i64), FullInt::S(isize::max_value() as i64)),
866                 })
867             }
868             TyUint(uint_ty) => {
869                 Some(match uint_ty {
870                     UintTy::U8 => (FullInt::U(u8::min_value() as u64), FullInt::U(u8::max_value() as u64)),
871                     UintTy::U16 => (FullInt::U(u16::min_value() as u64), FullInt::U(u16::max_value() as u64)),
872                     UintTy::U32 => (FullInt::U(u32::min_value() as u64), FullInt::U(u32::max_value() as u64)),
873                     UintTy::U64 => (FullInt::U(u64::min_value() as u64), FullInt::U(u64::max_value() as u64)),
874                     UintTy::Us => (FullInt::U(usize::min_value() as u64), FullInt::U(usize::max_value() as u64)),
875                 })
876             }
877             _ => None,
878         }
879     } else {
880         None
881     }
882 }
883
884 fn node_as_const_fullint(cx: &LateContext, expr: &Expr) -> Option<FullInt> {
885     use rustc::middle::const_val::ConstVal::*;
886     use rustc_const_eval::EvalHint::ExprTypeChecked;
887     use rustc_const_eval::eval_const_expr_partial;
888     use rustc_const_math::ConstInt;
889
890     match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
891         Ok(val) => {
892             if let Integral(const_int) = val {
893                 Some(match const_int.erase_type() {
894                     ConstInt::InferSigned(x) => FullInt::S(x as i64),
895                     ConstInt::Infer(x) => FullInt::U(x as u64),
896                     _ => unreachable!(),
897                 })
898             } else {
899                 None
900             }
901         }
902         Err(_) => None,
903     }
904 }
905
906 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
907     if let ExprCast(ref cast_val, _) = expr.node {
908         span_lint(cx,
909                   INVALID_UPCAST_COMPARISONS,
910                   *span,
911                   &format!(
912                 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
913                 snippet(cx, cast_val.span, "the expression"),
914                 if always { "true" } else { "false" },
915             ));
916     }
917 }
918
919 fn upcast_comparison_bounds_err(cx: &LateContext, span: &Span, rel: comparisons::Rel,
920                                 lhs_bounds: Option<(FullInt, FullInt)>, lhs: &Expr, rhs: &Expr, invert: bool) {
921     use utils::comparisons::*;
922
923     if let Some((lb, ub)) = lhs_bounds {
924         if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
925             if rel == Rel::Eq || rel == Rel::Ne {
926                 if norm_rhs_val < lb || norm_rhs_val > ub {
927                     err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
928                 }
929             } else if match rel {
930                 Rel::Lt => {
931                     if invert {
932                         norm_rhs_val < lb
933                     } else {
934                         ub < norm_rhs_val
935                     }
936                 }
937                 Rel::Le => {
938                     if invert {
939                         norm_rhs_val <= lb
940                     } else {
941                         ub <= norm_rhs_val
942                     }
943                 }
944                 Rel::Eq | Rel::Ne => unreachable!(),
945             } {
946                 err_upcast_comparison(cx, span, lhs, true)
947             } else if match rel {
948                 Rel::Lt => {
949                     if invert {
950                         norm_rhs_val >= ub
951                     } else {
952                         lb >= norm_rhs_val
953                     }
954                 }
955                 Rel::Le => {
956                     if invert {
957                         norm_rhs_val > ub
958                     } else {
959                         lb > norm_rhs_val
960                     }
961                 }
962                 Rel::Eq | Rel::Ne => unreachable!(),
963             } {
964                 err_upcast_comparison(cx, span, lhs, false)
965             }
966         }
967     }
968 }
969
970 impl LateLintPass for InvalidUpcastComparisons {
971     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
972         if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
973
974             let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
975             let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
976                 val
977             } else {
978                 return;
979             };
980
981             let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
982             let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
983
984             upcast_comparison_bounds_err(cx, &expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
985             upcast_comparison_bounds_err(cx, &expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
986         }
987     }
988 }