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