]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Rustup to 1.9.0-nightly (30a3849f2 2016-03-30)
[rust.git] / src / types.rs
1 use reexport::*;
2 use rustc::lint::*;
3 use rustc::middle::def;
4 use rustc::ty;
5 use rustc_front::hir::*;
6 use rustc_front::intravisit::{FnKind, Visitor, walk_ty};
7 use rustc_front::util::{is_comparison_binop, binop_to_string};
8 use syntax::ast::{IntTy, UintTy, FloatTy};
9 use syntax::codemap::Span;
10 use utils::*;
11
12 /// Handles all the linting of funky types
13 #[allow(missing_copy_implementations)]
14 pub struct TypePass;
15
16 /// **What it does:** This lint checks for use of `Box<Vec<_>>` anywhere in the code.
17 ///
18 /// **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.
19 ///
20 /// **Known problems:** None
21 ///
22 /// **Example:** `struct X { values: Box<Vec<Foo>> }`
23 declare_lint! {
24     pub BOX_VEC, Warn,
25     "usage of `Box<Vec<T>>`, vector elements are already on the heap"
26 }
27
28 /// **What it does:** This lint checks for usage of any `LinkedList`, suggesting to use a `Vec` or a `VecDeque` (formerly called `RingBuf`).
29 ///
30 /// **Why is this bad?** Gankro says:
31 ///
32 /// >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.
33 /// >
34 /// > `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`.
35 ///
36 /// **Known problems:** False positives – the instances where using a `LinkedList` makes sense are few and far between, but they can still happen.
37 ///
38 /// **Example:** `let x = LinkedList::new();`
39 declare_lint! {
40     pub LINKEDLIST, Warn,
41     "usage of LinkedList, usually a vector is faster, or a more specialized data \
42      structure like a VecDeque"
43 }
44
45 impl LintPass for TypePass {
46     fn get_lints(&self) -> LintArray {
47         lint_array!(BOX_VEC, LINKEDLIST)
48     }
49 }
50
51 impl LateLintPass for TypePass {
52     fn check_ty(&mut self, cx: &LateContext, ast_ty: &Ty) {
53         if in_macro(cx, ast_ty.span) {
54             return;
55         }
56         if let Some(did) = cx.tcx.def_map.borrow().get(&ast_ty.id) {
57             if let def::Def::Struct(..) = did.full_def() {
58                 if Some(did.def_id()) == cx.tcx.lang_items.owned_box() {
59                     if_let_chain! {
60                         [
61                             let TyPath(_, ref path) = ast_ty.node,
62                             let Some(ref last) = path.segments.last(),
63                             let PathParameters::AngleBracketedParameters(ref ag) = last.parameters,
64                             let Some(ref vec) = ag.types.get(0),
65                             let Some(did) = cx.tcx.def_map.borrow().get(&vec.id),
66                             let def::Def::Struct(..) = did.full_def(),
67                             match_def_path(cx, did.def_id(), &VEC_PATH),
68                         ],
69                         {
70                             span_help_and_lint(cx,
71                                                BOX_VEC,
72                                                ast_ty.span,
73                                                "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
74                                                "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.");
75                         }
76                     }
77                 } else if match_def_path(cx, did.def_id(), &LL_PATH) {
78                     span_help_and_lint(cx,
79                                        LINKEDLIST,
80                                        ast_ty.span,
81                                        "I see you're using a LinkedList! Perhaps you meant some other data structure?",
82                                        "a VecDeque might work");
83                 }
84             }
85         }
86     }
87 }
88
89 #[allow(missing_copy_implementations)]
90 pub struct LetPass;
91
92 /// **What it does:** This lint checks for binding a unit value.
93 ///
94 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So binding one is kind of pointless.
95 ///
96 /// **Known problems:** None
97 ///
98 /// **Example:** `let x = { 1; };`
99 declare_lint! {
100     pub LET_UNIT_VALUE, Warn,
101     "creating a let binding to a value of unit type, which usually can't be used afterwards"
102 }
103
104 fn check_let_unit(cx: &LateContext, decl: &Decl) {
105     if let DeclLocal(ref local) = decl.node {
106         let bindtype = &cx.tcx.pat_ty(&local.pat).sty;
107         if *bindtype == ty::TyTuple(vec![]) {
108             if in_external_macro(cx, decl.span) || in_macro(cx, local.pat.span) {
109                 return;
110             }
111             if is_from_for_desugar(decl) {
112                 return;
113             }
114             span_lint(cx,
115                       LET_UNIT_VALUE,
116                       decl.span,
117                       &format!("this let-binding has unit value. Consider omitting `let {} =`",
118                                snippet(cx, local.pat.span, "..")));
119         }
120     }
121 }
122
123 impl LintPass for LetPass {
124     fn get_lints(&self) -> LintArray {
125         lint_array!(LET_UNIT_VALUE)
126     }
127 }
128
129 impl LateLintPass for LetPass {
130     fn check_decl(&mut self, cx: &LateContext, decl: &Decl) {
131         check_let_unit(cx, decl)
132     }
133 }
134
135 /// **What it does:** This lint checks for comparisons to unit.
136 ///
137 /// **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.
138 ///
139 /// **Known problems:** None
140 ///
141 /// **Example:** `if { foo(); } == { bar(); } { baz(); }` is equal to `{ foo(); bar(); baz(); }`
142 declare_lint! {
143     pub UNIT_CMP, Warn,
144     "comparing unit values (which is always `true` or `false`, respectively)"
145 }
146
147 #[allow(missing_copy_implementations)]
148 pub struct UnitCmp;
149
150 impl LintPass for UnitCmp {
151     fn get_lints(&self) -> LintArray {
152         lint_array!(UNIT_CMP)
153     }
154 }
155
156 impl LateLintPass for UnitCmp {
157     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
158         if in_macro(cx, expr.span) {
159             return;
160         }
161         if let ExprBinary(ref cmp, ref left, _) = expr.node {
162             let op = cmp.node;
163             let sty = &cx.tcx.expr_ty(left).sty;
164             if *sty == ty::TyTuple(vec![]) && is_comparison_binop(op) {
165                 let result = match op {
166                     BiEq | BiLe | BiGe => "true",
167                     _ => "false",
168                 };
169                 span_lint(cx,
170                           UNIT_CMP,
171                           expr.span,
172                           &format!("{}-comparison of unit values detected. This will always be {}",
173                                    binop_to_string(op),
174                                    result));
175             }
176         }
177     }
178 }
179
180 pub struct CastPass;
181
182 /// **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.
183 ///
184 /// Basically, this warns on casting any integer with 32 or more bits to `f32` or any 64-bit integer to `f64`.
185 ///
186 /// **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.
187 ///
188 /// **Known problems:** None
189 ///
190 /// **Example:** `let x = u64::MAX; x as f64`
191 declare_lint! {
192     pub CAST_PRECISION_LOSS, Allow,
193     "casts that cause loss of precision, e.g `x as f32` where `x: u64`"
194 }
195
196 /// **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.
197 ///
198 /// **Why is this bad?** Possibly surprising results. You can activate this lint as a one-time check to see where numerical wrapping can arise.
199 ///
200 /// **Known problems:** None
201 ///
202 /// **Example:** `let y : i8 = -1; y as u64` will return 18446744073709551615
203 declare_lint! {
204     pub CAST_SIGN_LOSS, Allow,
205     "casts from signed types to unsigned types, e.g `x as u32` where `x: i32`"
206 }
207
208 /// **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.
209 ///
210 /// **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.
211 ///
212 /// **Known problems:** None
213 ///
214 /// **Example:** `fn as_u8(x: u64) -> u8 { x as u8 }`
215 declare_lint! {
216     pub CAST_POSSIBLE_TRUNCATION, Allow,
217     "casts that may cause truncation of the value, e.g `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
218 }
219
220 /// **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.
221 ///
222 /// **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.
223 ///
224 /// **Known problems:** None
225 ///
226 /// **Example:** `u32::MAX as i32` will yield a value of `-1`.
227 declare_lint! {
228     pub CAST_POSSIBLE_WRAP, Allow,
229     "casts that may cause wrapping around the value, e.g `x as i32` where `x: u32` and `x > i32::MAX`"
230 }
231
232 /// Returns the size in bits of an integral type.
233 /// Will return 0 if the type is not an int or uint variant
234 fn int_ty_to_nbits(typ: &ty::TyS) -> usize {
235     let n = match typ.sty {
236         ty::TyInt(i) => 4 << (i as usize),
237         ty::TyUint(u) => 4 << (u as usize),
238         _ => 0,
239     };
240     // n == 4 is the usize/isize case
241     if n == 4 {
242         ::std::mem::size_of::<usize>() * 8
243     } else {
244         n
245     }
246 }
247
248 fn is_isize_or_usize(typ: &ty::TyS) -> bool {
249     match typ.sty {
250         ty::TyInt(IntTy::Is) | ty::TyUint(UintTy::Us) => true,
251         _ => false,
252     }
253 }
254
255 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to_f64: bool) {
256     let mantissa_nbits = if cast_to_f64 {
257         52
258     } else {
259         23
260     };
261     let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
262     let arch_dependent_str = "on targets with 64-bit wide pointers ";
263     let from_nbits_str = if arch_dependent {
264         "64".to_owned()
265     } else if is_isize_or_usize(cast_from) {
266         "32 or 64".to_owned()
267     } else {
268         int_ty_to_nbits(cast_from).to_string()
269     };
270     span_lint(cx,
271               CAST_PRECISION_LOSS,
272               expr.span,
273               &format!("casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
274                         is only {4} bits wide)",
275                        cast_from,
276                        if cast_to_f64 {
277                            "f64"
278                        } else {
279                            "f32"
280                        },
281                        if arch_dependent {
282                            arch_dependent_str
283                        } else {
284                            ""
285                        },
286                        from_nbits_str,
287                        mantissa_nbits));
288 }
289
290 enum ArchSuffix {
291     _32,
292     _64,
293     None,
294 }
295
296 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: &ty::TyS, cast_to: &ty::TyS) {
297     let arch_64_suffix = " on targets with 64-bit wide pointers";
298     let arch_32_suffix = " on targets with 32-bit wide pointers";
299     let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
300     let (from_nbits, to_nbits) = (int_ty_to_nbits(cast_from), int_ty_to_nbits(cast_to));
301     let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) = match (is_isize_or_usize(cast_from),
302                                                                               is_isize_or_usize(cast_to)) {
303         (true, true) | (false, false) => {
304             (to_nbits < from_nbits,
305              ArchSuffix::None,
306              to_nbits == from_nbits && cast_unsigned_to_signed,
307              ArchSuffix::None)
308         }
309         (true, false) => {
310             (to_nbits <= 32,
311              if to_nbits == 32 {
312                 ArchSuffix::_64
313             } else {
314                 ArchSuffix::None
315             },
316              to_nbits <= 32 && cast_unsigned_to_signed,
317              ArchSuffix::_32)
318         }
319         (false, true) => {
320             (from_nbits == 64,
321              ArchSuffix::_32,
322              cast_unsigned_to_signed,
323              if from_nbits == 64 {
324                 ArchSuffix::_64
325             } else {
326                 ArchSuffix::_32
327             })
328         }
329     };
330     if span_truncation {
331         span_lint(cx,
332                   CAST_POSSIBLE_TRUNCATION,
333                   expr.span,
334                   &format!("casting {} to {} may truncate the value{}",
335                            cast_from,
336                            cast_to,
337                            match suffix_truncation {
338                                ArchSuffix::_32 => arch_32_suffix,
339                                ArchSuffix::_64 => arch_64_suffix,
340                                ArchSuffix::None => "",
341                            }));
342     }
343     if span_wrap {
344         span_lint(cx,
345                   CAST_POSSIBLE_WRAP,
346                   expr.span,
347                   &format!("casting {} to {} may wrap around the value{}",
348                            cast_from,
349                            cast_to,
350                            match suffix_wrap {
351                                ArchSuffix::_32 => arch_32_suffix,
352                                ArchSuffix::_64 => arch_64_suffix,
353                                ArchSuffix::None => "",
354                            }));
355     }
356 }
357
358 impl LintPass for CastPass {
359     fn get_lints(&self) -> LintArray {
360         lint_array!(CAST_PRECISION_LOSS,
361                     CAST_SIGN_LOSS,
362                     CAST_POSSIBLE_TRUNCATION,
363                     CAST_POSSIBLE_WRAP)
364     }
365 }
366
367 impl LateLintPass for CastPass {
368     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
369         if let ExprCast(ref ex, _) = expr.node {
370             let (cast_from, cast_to) = (cx.tcx.expr_ty(ex), cx.tcx.expr_ty(expr));
371             if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
372                 match (cast_from.is_integral(), cast_to.is_integral()) {
373                     (true, false) => {
374                         let from_nbits = int_ty_to_nbits(cast_from);
375                         let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
376                             32
377                         } else {
378                             64
379                         };
380                         if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
381                             span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
382                         }
383                     }
384                     (false, true) => {
385                         span_lint(cx,
386                                   CAST_POSSIBLE_TRUNCATION,
387                                   expr.span,
388                                   &format!("casting {} to {} may truncate the value", cast_from, cast_to));
389                         if !cast_to.is_signed() {
390                             span_lint(cx,
391                                       CAST_SIGN_LOSS,
392                                       expr.span,
393                                       &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
394                         }
395                     }
396                     (true, true) => {
397                         if cast_from.is_signed() && !cast_to.is_signed() {
398                             span_lint(cx,
399                                       CAST_SIGN_LOSS,
400                                       expr.span,
401                                       &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to));
402                         }
403                         check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
404                     }
405                     (false, false) => {
406                         if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty,
407                                                                                            &cast_to.sty) {
408                             span_lint(cx,
409                                       CAST_POSSIBLE_TRUNCATION,
410                                       expr.span,
411                                       "casting f64 to f32 may truncate the value");
412                         }
413                     }
414                 }
415             }
416         }
417     }
418 }
419
420 /// **What it does:** This lint checks for types used in structs, parameters and `let` declarations above a certain complexity threshold.
421 ///
422 /// **Why is this bad?** Too complex types make the code less readable. Consider using a `type` definition to simplify them.
423 ///
424 /// **Known problems:** None
425 ///
426 /// **Example:** `struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }`
427 declare_lint! {
428     pub TYPE_COMPLEXITY, Warn,
429     "usage of very complex types; recommends factoring out parts into `type` definitions"
430 }
431
432 #[allow(missing_copy_implementations)]
433 pub struct TypeComplexityPass {
434     threshold: u64,
435 }
436
437 impl TypeComplexityPass {
438     pub fn new(threshold: u64) -> Self {
439         TypeComplexityPass { threshold: threshold }
440     }
441 }
442
443 impl LintPass for TypeComplexityPass {
444     fn get_lints(&self) -> LintArray {
445         lint_array!(TYPE_COMPLEXITY)
446     }
447 }
448
449 impl LateLintPass for TypeComplexityPass {
450     fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
451         self.check_fndecl(cx, decl);
452     }
453
454     fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
455         // enum variants are also struct fields now
456         self.check_type(cx, &field.ty);
457     }
458
459     fn check_item(&mut self, cx: &LateContext, item: &Item) {
460         match item.node {
461             ItemStatic(ref ty, _, _) |
462             ItemConst(ref ty, _) => self.check_type(cx, ty),
463             // functions, enums, structs, impls and traits are covered
464             _ => (),
465         }
466     }
467
468     fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
469         match item.node {
470             ConstTraitItem(ref ty, _) |
471             TypeTraitItem(_, Some(ref ty)) => self.check_type(cx, ty),
472             MethodTraitItem(MethodSig { ref decl, .. }, None) => self.check_fndecl(cx, decl),
473             // methods with default impl are covered by check_fn
474             _ => (),
475         }
476     }
477
478     fn check_impl_item(&mut self, cx: &LateContext, item: &ImplItem) {
479         match item.node {
480             ImplItemKind::Const(ref ty, _) |
481             ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
482             // methods are covered by check_fn
483             _ => (),
484         }
485     }
486
487     fn check_local(&mut self, cx: &LateContext, local: &Local) {
488         if let Some(ref ty) = local.ty {
489             self.check_type(cx, ty);
490         }
491     }
492 }
493
494 impl TypeComplexityPass {
495     fn check_fndecl(&self, cx: &LateContext, decl: &FnDecl) {
496         for arg in &decl.inputs {
497             self.check_type(cx, &arg.ty);
498         }
499         if let Return(ref ty) = decl.output {
500             self.check_type(cx, ty);
501         }
502     }
503
504     fn check_type(&self, cx: &LateContext, ty: &Ty) {
505         if in_macro(cx, ty.span) {
506             return;
507         }
508         let score = {
509             let mut visitor = TypeComplexityVisitor {
510                 score: 0,
511                 nest: 1,
512             };
513             visitor.visit_ty(ty);
514             visitor.score
515         };
516
517         if score > self.threshold {
518             span_lint(cx,
519                       TYPE_COMPLEXITY,
520                       ty.span,
521                       "very complex type used. Consider factoring parts into `type` definitions");
522         }
523     }
524 }
525
526 /// Walks a type and assigns a complexity score to it.
527 struct TypeComplexityVisitor {
528     /// total complexity score of the type
529     score: u64,
530     /// current nesting level
531     nest: u64,
532 }
533
534 impl<'v> Visitor<'v> for TypeComplexityVisitor {
535     fn visit_ty(&mut self, ty: &'v Ty) {
536         let (add_score, sub_nest) = match ty.node {
537             // _, &x and *x have only small overhead; don't mess with nesting level
538             TyInfer |
539             TyPtr(..) |
540             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 fn detect_absurd_comparison<'a>(cx: &LateContext, op: BinOp_, lhs: &'a Expr, rhs: &'a Expr)
644                                 -> Option<(ExtremeExpr<'a>, AbsurdComparisonResult)> {
645     use types::ExtremeType::*;
646     use types::AbsurdComparisonResult::*;
647     type Extr<'a> = ExtremeExpr<'a>;
648
649     // Put the expression in the form lhs < rhs or lhs <= rhs.
650     enum Rel {
651         Lt,
652         Le,
653     };
654     let (rel, normalized_lhs, normalized_rhs) = match op {
655         BiLt => (Rel::Lt, lhs, rhs),
656         BiLe => (Rel::Le, lhs, rhs),
657         BiGt => (Rel::Lt, rhs, lhs),
658         BiGe => (Rel::Le, rhs, lhs),
659         _ => return None,
660     };
661
662     let lx = detect_extreme_expr(cx, normalized_lhs);
663     let rx = detect_extreme_expr(cx, normalized_rhs);
664
665     Some(match rel {
666         Rel::Lt => {
667             match (lx, rx) {
668                 (Some(l @ Extr { which: Maximum, ..}), _) => (l, AlwaysFalse), // max < x
669                 (_, Some(r @ Extr { which: Minimum, ..})) => (r, AlwaysFalse), // x < min
670                 _ => return None,
671             }
672         }
673         Rel::Le => {
674             match (lx, rx) {
675                 (Some(l @ Extr { which: Minimum, ..}), _) => (l, AlwaysTrue), // min <= x
676                 (Some(l @ Extr { which: Maximum, ..}), _) => (l, InequalityImpossible), //max <= x
677                 (_, Some(r @ Extr { which: Minimum, ..})) => (r, InequalityImpossible), // x <= min
678                 (_, Some(r @ Extr { which: Maximum, ..})) => (r, AlwaysTrue), // x <= max
679                 _ => return None,
680             }
681         }
682     })
683 }
684
685 fn detect_extreme_expr<'a>(cx: &LateContext, expr: &'a Expr) -> Option<ExtremeExpr<'a>> {
686     use rustc::middle::const_val::ConstVal::*;
687     use rustc_const_math::*;
688     use rustc_const_eval::EvalHint::ExprTypeChecked;
689     use rustc_const_eval::*;
690     use types::ExtremeType::*;
691
692     let ty = &cx.tcx.expr_ty(expr).sty;
693
694     match *ty {
695         ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
696         _ => return None,
697     };
698
699     let cv = match eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None) {
700         Ok(val) => val,
701         Err(_) => return None,
702     };
703
704     let which = match (ty, cv) {
705         (&ty::TyBool, Bool(false)) |
706
707         (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MIN)))) |
708         (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MIN)))) |
709         (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MIN))) |
710         (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MIN))) |
711         (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MIN))) |
712         (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MIN))) |
713
714         (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MIN)))) |
715         (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MIN)))) |
716         (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MIN))) |
717         (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MIN))) |
718         (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MIN))) |
719         (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MIN))) => Minimum,
720
721         (&ty::TyBool, Bool(true)) |
722
723         (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MAX)))) |
724         (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MAX)))) |
725         (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MAX))) |
726         (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MAX))) |
727         (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MAX))) |
728         (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MAX))) |
729
730         (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MAX)))) |
731         (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MAX)))) |
732         (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MAX))) |
733         (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MAX))) |
734         (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MAX))) |
735         (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MAX))) => Maximum,
736
737         _ => return None,
738     };
739     Some(ExtremeExpr {
740         which: which,
741         expr: expr,
742     })
743 }
744
745 impl LateLintPass for AbsurdExtremeComparisons {
746     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
747         use types::ExtremeType::*;
748         use types::AbsurdComparisonResult::*;
749
750         if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
751             if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
752                 if !in_macro(cx, expr.span) {
753                     let msg = "this comparison involving the minimum or maximum element for this \
754                                type contains a case that is always true or always false";
755
756                     let conclusion = match result {
757                         AlwaysFalse => "this comparison is always false".to_owned(),
758                         AlwaysTrue => "this comparison is always true".to_owned(),
759                         InequalityImpossible => {
760                             format!("the case where the two sides are not equal never occurs, consider using {} == {} \
761                                      instead",
762                                     snippet(cx, lhs.span, "lhs"),
763                                     snippet(cx, rhs.span, "rhs"))
764                         }
765                     };
766
767                     let help = format!("because {} is the {} value for this type, {}",
768                                        snippet(cx, culprit.expr.span, "x"),
769                                        match culprit.which {
770                                            Minimum => "minimum",
771                                            Maximum => "maximum",
772                                        },
773                                        conclusion);
774
775                     span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
776                 }
777             }
778         }
779     }
780 }