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