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