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