]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/types.rs
Fix 'cyclomatic complexity' warning
[rust.git] / clippy_lints / src / types.rs
1 use reexport::*;
2 use rustc::hir;
3 use rustc::hir::*;
4 use rustc::hir::intravisit::{FnKind, Visitor, walk_ty, NestedVisitorMap};
5 use rustc::lint::*;
6 use rustc::ty::{self, Ty};
7 use rustc::ty::subst::Substs;
8 use std::cmp::Ordering;
9 use syntax::ast::{IntTy, UintTy, FloatTy};
10 use syntax::attr::IntType;
11 use syntax::codemap::Span;
12 use utils::{comparisons, higher, in_external_macro, in_macro, match_def_path, snippet, span_help_and_lint, span_lint,
13             span_lint_and_sugg, opt_def_id, last_path_segment, type_size, match_path_old};
14 use utils::paths;
15
16 /// Handles all the linting of funky types
17 #[allow(missing_copy_implementations)]
18 pub struct TypePass;
19
20 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
21 ///
22 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
23 /// the heap. So if you `Box` it, you just add another level of indirection
24 /// without any benefit whatsoever.
25 ///
26 /// **Known problems:** None.
27 ///
28 /// **Example:**
29 /// ```rust
30 /// struct X {
31 ///     values: Box<Vec<Foo>>,
32 /// }
33 /// ```
34 declare_lint! {
35     pub BOX_VEC,
36     Warn,
37     "usage of `Box<Vec<T>>`, vector elements are already on the heap"
38 }
39
40 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
41 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
42 ///
43 /// **Why is this bad?** Gankro says:
44 ///
45 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
46 /// pointers and indirection.
47 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
48 /// `RingBuf`, while
49 /// > "only" amortized for push/pop, should be faster in the general case for
50 /// almost every possible
51 /// > workload, and isn't even amortized at all if you can predict the capacity
52 /// you need.
53 /// >
54 /// > `LinkedList`s are only really good if you're doing a lot of merging or
55 /// splitting of lists.
56 /// > This is because they can just mangle some pointers instead of actually
57 /// copying the data. Even
58 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
59 /// can still be better
60 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
61 ///
62 /// **Known problems:** False positives – the instances where using a
63 /// `LinkedList` makes sense are few and far between, but they can still happen.
64 ///
65 /// **Example:**
66 /// ```rust
67 /// let x = LinkedList::new();
68 /// ```
69 declare_lint! {
70     pub LINKEDLIST,
71     Warn,
72     "usage of LinkedList, usually a vector is faster, or a more specialized data \
73      structure like a VecDeque"
74 }
75
76 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
77 ///
78 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
79 /// general.
80 ///
81 /// **Known problems:** None.
82 ///
83 /// **Example:**
84 /// ```rust
85 /// fn foo(bar: &Box<T>) { ... }
86 /// ```
87 declare_lint! {
88     pub BORROWED_BOX,
89     Warn,
90     "a borrow of a boxed type"
91 }
92
93 impl LintPass for TypePass {
94     fn get_lints(&self) -> LintArray {
95         lint_array!(BOX_VEC, LINKEDLIST, BORROWED_BOX)
96     }
97 }
98
99 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypePass {
100     fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Body, _: Span, id: NodeId) {
101         // skip trait implementations, see #605
102         if let Some(map::NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(id)) {
103             if let ItemImpl(_, _, _, _, Some(..), _, _) = item.node {
104                 return;
105             }
106         }
107
108         check_fn_decl(cx, decl);
109     }
110
111     fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
112         check_ty(cx, &field.ty, false);
113     }
114
115     fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
116         match item.node {
117             TraitItemKind::Const(ref ty, _) |
118             TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
119             TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
120             _ => (),
121         }
122     }
123
124     fn check_local(&mut self, cx: &LateContext, local: &Local) {
125         if let Some(ref ty) = local.ty {
126             check_ty(cx, ty, true);
127         }
128     }
129 }
130
131 fn check_fn_decl(cx: &LateContext, decl: &FnDecl) {
132     for input in &decl.inputs {
133         check_ty(cx, input, false);
134     }
135
136     if let FunctionRetTy::Return(ref ty) = decl.output {
137         check_ty(cx, ty, false);
138     }
139 }
140
141 /// Recursively check for `TypePass` lints in the given type. Stop at the first
142 /// lint found.
143 ///
144 /// The parameter `is_local` distinguishes the context of the type; types from
145 /// local bindings should only be checked for the `BORROWED_BOX` lint.
146 fn check_ty(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool) {
147     if in_macro(ast_ty.span) {
148         return;
149     }
150     match ast_ty.node {
151         TyPath(ref qpath) if !is_local => {
152             let hir_id = cx.tcx.hir.node_to_hir_id(ast_ty.id);
153             let def = cx.tables.qpath_def(qpath, hir_id);
154             if let Some(def_id) = opt_def_id(def) {
155                 if Some(def_id) == cx.tcx.lang_items.owned_box() {
156                     let last = last_path_segment(qpath);
157                     if_let_chain! {[
158                         let PathParameters::AngleBracketedParameters(ref ag) = last.parameters,
159                         let Some(vec) = ag.types.get(0),
160                         let TyPath(ref qpath) = vec.node,
161                         let Some(did) = opt_def_id(cx.tables.qpath_def(qpath, cx.tcx.hir.node_to_hir_id(vec.id))),
162                         match_def_path(cx.tcx, did, &paths::VEC),
163                     ], {
164                         span_help_and_lint(cx,
165                                            BOX_VEC,
166                                            ast_ty.span,
167                                            "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
168                                            "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.");
169                         return; // don't recurse into the type
170                     }}
171                 } else if match_def_path(cx.tcx, def_id, &paths::LINKED_LIST) {
172                     span_help_and_lint(
173                         cx,
174                         LINKEDLIST,
175                         ast_ty.span,
176                         "I see you're using a LinkedList! Perhaps you meant some other data structure?",
177                         "a VecDeque might work",
178                     );
179                     return; // don't recurse into the type
180                 }
181             }
182             match *qpath {
183                 QPath::Resolved(Some(ref ty), ref p) => {
184                     check_ty(cx, ty, is_local);
185                     for ty in p.segments.iter().flat_map(|seg| seg.parameters.types()) {
186                         check_ty(cx, ty, is_local);
187                     }
188                 },
189                 QPath::Resolved(None, ref p) => {
190                     for ty in p.segments.iter().flat_map(|seg| seg.parameters.types()) {
191                         check_ty(cx, ty, is_local);
192                     }
193                 },
194                 QPath::TypeRelative(ref ty, ref seg) => {
195                     check_ty(cx, ty, is_local);
196                     for ty in seg.parameters.types() {
197                         check_ty(cx, ty, is_local);
198                     }
199                 },
200             }
201         },
202         TyRptr(ref lt, MutTy { ref ty, ref mutbl }) => {
203             match ty.node {
204                 TyPath(ref qpath) => {
205                     let hir_id = cx.tcx.hir.node_to_hir_id(ty.id);
206                     let def = cx.tables.qpath_def(qpath, hir_id);
207                     if_let_chain! {[
208                         let Some(def_id) = opt_def_id(def),
209                         Some(def_id) == cx.tcx.lang_items.owned_box(),
210                         let QPath::Resolved(None, ref path) = *qpath,
211                         let [ref bx] = *path.segments,
212                         let PathParameters::AngleBracketedParameters(ref ab_data) = bx.parameters,
213                         let [ref inner] = *ab_data.types
214                     ], {
215                         if is_any_trait(inner) {
216                             // Ignore `Box<Any>` types, see #1884 for details.
217                             return;
218                         }
219
220                         let ltopt = if lt.is_elided() {
221                             "".to_owned()
222                         } else {
223                             format!("{} ", lt.name.as_str())
224                         };
225                         let mutopt = if *mutbl == Mutability::MutMutable {
226                             "mut "
227                         } else {
228                             ""
229                         };
230                         span_lint_and_sugg(cx,
231                             BORROWED_BOX,
232                             ast_ty.span,
233                             "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
234                             "try",
235                             format!("&{}{}{}", ltopt, mutopt, &snippet(cx, inner.span, ".."))
236                         );
237                         return; // don't recurse into the type
238                     }};
239                     check_ty(cx, ty, is_local);
240                 },
241                 _ => check_ty(cx, ty, is_local),
242             }
243         },
244         // recurse
245         TySlice(ref ty) |
246         TyArray(ref ty, _) |
247         TyPtr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
248         TyTup(ref tys) => {
249             for ty in tys {
250                 check_ty(cx, ty, is_local);
251             }
252         },
253         _ => {},
254     }
255 }
256
257 // Returns true if given type is `Any` trait.
258 fn is_any_trait(t: &hir::Ty) -> bool {
259     if_let_chain! {[
260         let TyTraitObject(ref traits, _) = t.node,
261         traits.len() >= 1,
262         // Only Send/Sync can be used as additional traits, so it is enough to
263         // check only the first trait.
264         match_path_old(&traits[0].trait_ref.path, &paths::ANY_TRAIT)
265     ], {
266         return true;
267     }}
268
269     false
270 }
271
272 #[allow(missing_copy_implementations)]
273 pub struct LetPass;
274
275 /// **What it does:** Checks for binding a unit value.
276 ///
277 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
278 /// binding one is kind of pointless.
279 ///
280 /// **Known problems:** None.
281 ///
282 /// **Example:**
283 /// ```rust
284 /// let x = { 1; };
285 /// ```
286 declare_lint! {
287     pub LET_UNIT_VALUE,
288     Warn,
289     "creating a let binding to a value of unit type, which usually can't be used afterwards"
290 }
291
292 fn check_let_unit(cx: &LateContext, decl: &Decl) {
293     if let DeclLocal(ref local) = decl.node {
294         match cx.tables.pat_ty(&local.pat).sty {
295             ty::TyTuple(slice, _) if slice.is_empty() => {
296                 if in_external_macro(cx, decl.span) || in_macro(local.pat.span) {
297                     return;
298                 }
299                 if higher::is_from_for_desugar(decl) {
300                     return;
301                 }
302                 span_lint(
303                     cx,
304                     LET_UNIT_VALUE,
305                     decl.span,
306                     &format!(
307                         "this let-binding has unit value. Consider omitting `let {} =`",
308                         snippet(cx, local.pat.span, "..")
309                     ),
310                 );
311             },
312             _ => (),
313         }
314     }
315 }
316
317 impl LintPass for LetPass {
318     fn get_lints(&self) -> LintArray {
319         lint_array!(LET_UNIT_VALUE)
320     }
321 }
322
323 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetPass {
324     fn check_decl(&mut self, cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl) {
325         check_let_unit(cx, decl)
326     }
327 }
328
329 /// **What it does:** Checks for comparisons to unit.
330 ///
331 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
332 /// clumsily written constant. Mostly this happens when someone accidentally
333 /// adds semicolons at the end of the operands.
334 ///
335 /// **Known problems:** None.
336 ///
337 /// **Example:**
338 /// ```rust
339 /// if { foo(); } == { bar(); } { baz(); }
340 /// ```
341 /// is equal to
342 /// ```rust
343 /// { foo(); bar(); baz(); }
344 /// ```
345 declare_lint! {
346     pub UNIT_CMP,
347     Warn,
348     "comparing unit values"
349 }
350
351 #[allow(missing_copy_implementations)]
352 pub struct UnitCmp;
353
354 impl LintPass for UnitCmp {
355     fn get_lints(&self) -> LintArray {
356         lint_array!(UNIT_CMP)
357     }
358 }
359
360 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
361     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
362         if in_macro(expr.span) {
363             return;
364         }
365         if let ExprBinary(ref cmp, ref left, _) = expr.node {
366             let op = cmp.node;
367             if op.is_comparison() {
368                 match cx.tables.expr_ty(left).sty {
369                     ty::TyTuple(slice, _) if slice.is_empty() => {
370                         let result = match op {
371                             BiEq | BiLe | BiGe => "true",
372                             _ => "false",
373                         };
374                         span_lint(
375                             cx,
376                             UNIT_CMP,
377                             expr.span,
378                             &format!(
379                                 "{}-comparison of unit values detected. This will always be {}",
380                                 op.as_str(),
381                                 result
382                             ),
383                         );
384                     },
385                     _ => (),
386                 }
387             }
388         }
389     }
390 }
391
392 pub struct CastPass;
393
394 /// **What it does:** Checks for casts from any numerical to a float type where
395 /// the receiving type cannot store all values from the original type without
396 /// rounding errors. This possible rounding is to be expected, so this lint is
397 /// `Allow` by default.
398 ///
399 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
400 /// or any 64-bit integer to `f64`.
401 ///
402 /// **Why is this bad?** It's not bad at all. But in some applications it can be
403 /// helpful to know where precision loss can take place. This lint can help find
404 /// those places in the code.
405 ///
406 /// **Known problems:** None.
407 ///
408 /// **Example:**
409 /// ```rust
410 /// let x = u64::MAX; x as f64
411 /// ```
412 declare_lint! {
413     pub CAST_PRECISION_LOSS,
414     Allow,
415     "casts that cause loss of precision, e.g. `x as f32` where `x: u64`"
416 }
417
418 /// **What it does:** Checks for casts from a signed to an unsigned numerical
419 /// type. In this case, negative values wrap around to large positive values,
420 /// which can be quite surprising in practice. However, as the cast works as
421 /// defined, this lint is `Allow` by default.
422 ///
423 /// **Why is this bad?** Possibly surprising results. You can activate this lint
424 /// as a one-time check to see where numerical wrapping can arise.
425 ///
426 /// **Known problems:** None.
427 ///
428 /// **Example:**
429 /// ```rust
430 /// let y: i8 = -1;
431 /// y as u128  // will return 18446744073709551615
432 /// ```
433 declare_lint! {
434     pub CAST_SIGN_LOSS,
435     Allow,
436     "casts from signed types to unsigned types, e.g. `x as u32` where `x: i32`"
437 }
438
439 /// **What it does:** Checks for on casts between numerical types that may
440 /// truncate large values. This is expected behavior, so the cast is `Allow` by
441 /// default.
442 ///
443 /// **Why is this bad?** In some problem domains, it is good practice to avoid
444 /// truncation. This lint can be activated to help assess where additional
445 /// checks could be beneficial.
446 ///
447 /// **Known problems:** None.
448 ///
449 /// **Example:**
450 /// ```rust
451 /// fn as_u8(x: u64) -> u8 { x as u8 }
452 /// ```
453 declare_lint! {
454     pub CAST_POSSIBLE_TRUNCATION,
455     Allow,
456     "casts that may cause truncation of the value, e.g. `x as u8` where `x: u32`, \
457      or `x as i32` where `x: f32`"
458 }
459
460 /// **What it does:** Checks for casts from an unsigned type to a signed type of
461 /// the same size. Performing such a cast is a 'no-op' for the compiler,
462 /// i.e. nothing is changed at the bit level, and the binary representation of
463 /// the value is reinterpreted. This can cause wrapping if the value is too big
464 /// for the target signed type. However, the cast works as defined, so this lint
465 /// is `Allow` by default.
466 ///
467 /// **Why is this bad?** While such a cast is not bad in itself, the results can
468 /// be surprising when this is not the intended behavior, as demonstrated by the
469 /// example below.
470 ///
471 /// **Known problems:** None.
472 ///
473 /// **Example:**
474 /// ```rust
475 /// u32::MAX as i32  // will yield a value of `-1`
476 /// ```
477 declare_lint! {
478     pub CAST_POSSIBLE_WRAP,
479     Allow,
480     "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` \
481      and `x > i32::MAX`"
482 }
483
484 /// **What it does:** Checks for casts to the same type.
485 ///
486 /// **Why is this bad?** It's just unnecessary.
487 ///
488 /// **Known problems:** None.
489 ///
490 /// **Example:**
491 /// ```rust
492 /// let _ = 2i32 as i32
493 /// ```
494 declare_lint! {
495     pub UNNECESSARY_CAST,
496     Warn,
497     "cast to the same type, e.g. `x as i32` where `x: i32`"
498 }
499
500 /// Returns the size in bits of an integral type.
501 /// Will return 0 if the type is not an int or uint variant
502 fn int_ty_to_nbits(typ: Ty) -> usize {
503     let n = match typ.sty {
504         ty::TyInt(i) => 4 << (i as usize),
505         ty::TyUint(u) => 4 << (u as usize),
506         _ => 0,
507     };
508     // n == 4 is the usize/isize case
509     if n == 4 {
510         ::std::mem::size_of::<usize>() * 8
511     } else {
512         n
513     }
514 }
515
516 fn is_isize_or_usize(typ: Ty) -> bool {
517     match typ.sty {
518         ty::TyInt(IntTy::Is) |
519         ty::TyUint(UintTy::Us) => true,
520         _ => false,
521     }
522 }
523
524 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to_f64: bool) {
525     let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
526     let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
527     let arch_dependent_str = "on targets with 64-bit wide pointers ";
528     let from_nbits_str = if arch_dependent {
529         "64".to_owned()
530     } else if is_isize_or_usize(cast_from) {
531         "32 or 64".to_owned()
532     } else {
533         int_ty_to_nbits(cast_from).to_string()
534     };
535     span_lint(
536         cx,
537         CAST_PRECISION_LOSS,
538         expr.span,
539         &format!(
540             "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
541                         is only {4} bits wide)",
542             cast_from,
543             if cast_to_f64 { "f64" } else { "f32" },
544             if arch_dependent {
545                 arch_dependent_str
546             } else {
547                 ""
548             },
549             from_nbits_str,
550             mantissa_nbits
551         ),
552     );
553 }
554
555 enum ArchSuffix {
556     _32,
557     _64,
558     None,
559 }
560
561 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to: Ty) {
562     let arch_64_suffix = " on targets with 64-bit wide pointers";
563     let arch_32_suffix = " on targets with 32-bit wide pointers";
564     let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
565     let (from_nbits, to_nbits) = (int_ty_to_nbits(cast_from), int_ty_to_nbits(cast_to));
566     let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
567         match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
568             (true, true) | (false, false) => {
569                 (
570                     to_nbits < from_nbits,
571                     ArchSuffix::None,
572                     to_nbits == from_nbits && cast_unsigned_to_signed,
573                     ArchSuffix::None,
574                 )
575             },
576             (true, false) => {
577                 (
578                     to_nbits <= 32,
579                     if to_nbits == 32 {
580                         ArchSuffix::_64
581                     } else {
582                         ArchSuffix::None
583                     },
584                     to_nbits <= 32 && cast_unsigned_to_signed,
585                     ArchSuffix::_32,
586                 )
587             },
588             (false, true) => {
589                 (
590                     from_nbits == 64,
591                     ArchSuffix::_32,
592                     cast_unsigned_to_signed,
593                     if from_nbits == 64 {
594                         ArchSuffix::_64
595                     } else {
596                         ArchSuffix::_32
597                     },
598                 )
599             },
600         };
601     if span_truncation {
602         span_lint(
603             cx,
604             CAST_POSSIBLE_TRUNCATION,
605             expr.span,
606             &format!(
607                 "casting {} to {} may truncate the value{}",
608                 cast_from,
609                 cast_to,
610                 match suffix_truncation {
611                     ArchSuffix::_32 => arch_32_suffix,
612                     ArchSuffix::_64 => arch_64_suffix,
613                     ArchSuffix::None => "",
614                 }
615             ),
616         );
617     }
618     if span_wrap {
619         span_lint(
620             cx,
621             CAST_POSSIBLE_WRAP,
622             expr.span,
623             &format!(
624                 "casting {} to {} may wrap around the value{}",
625                 cast_from,
626                 cast_to,
627                 match suffix_wrap {
628                     ArchSuffix::_32 => arch_32_suffix,
629                     ArchSuffix::_64 => arch_64_suffix,
630                     ArchSuffix::None => "",
631                 }
632             ),
633         );
634     }
635 }
636
637 impl LintPass for CastPass {
638     fn get_lints(&self) -> LintArray {
639         lint_array!(
640             CAST_PRECISION_LOSS,
641             CAST_SIGN_LOSS,
642             CAST_POSSIBLE_TRUNCATION,
643             CAST_POSSIBLE_WRAP,
644             UNNECESSARY_CAST
645         )
646     }
647 }
648
649 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
650     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
651         if let ExprCast(ref ex, _) = expr.node {
652             let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
653             if let ExprLit(ref lit) = ex.node {
654                 use syntax::ast::{LitKind, LitIntType};
655                 match lit.node {
656                     LitKind::Int(_, LitIntType::Unsuffixed) |
657                     LitKind::FloatUnsuffixed(_) => {},
658                     _ => {
659                         if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
660                             span_lint(
661                                 cx,
662                                 UNNECESSARY_CAST,
663                                 expr.span,
664                                 &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
665                             );
666                         }
667                     },
668                 }
669             }
670             if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
671                 match (cast_from.is_integral(), cast_to.is_integral()) {
672                     (true, false) => {
673                         let from_nbits = int_ty_to_nbits(cast_from);
674                         let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
675                             32
676                         } else {
677                             64
678                         };
679                         if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
680                             span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
681                         }
682                     },
683                     (false, true) => {
684                         span_lint(
685                             cx,
686                             CAST_POSSIBLE_TRUNCATION,
687                             expr.span,
688                             &format!("casting {} to {} may truncate the value", cast_from, cast_to),
689                         );
690                         if !cast_to.is_signed() {
691                             span_lint(
692                                 cx,
693                                 CAST_SIGN_LOSS,
694                                 expr.span,
695                                 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
696                             );
697                         }
698                     },
699                     (true, true) => {
700                         if cast_from.is_signed() && !cast_to.is_signed() {
701                             span_lint(
702                                 cx,
703                                 CAST_SIGN_LOSS,
704                                 expr.span,
705                                 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
706                             );
707                         }
708                         check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
709                     },
710                     (false, false) => {
711                         if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) =
712                             (&cast_from.sty, &cast_to.sty)
713                         {
714                             span_lint(
715                                 cx,
716                                 CAST_POSSIBLE_TRUNCATION,
717                                 expr.span,
718                                 "casting f64 to f32 may truncate the value",
719                             );
720                         }
721                     },
722                 }
723             }
724         }
725     }
726 }
727
728 /// **What it does:** Checks for types used in structs, parameters and `let`
729 /// declarations above a certain complexity threshold.
730 ///
731 /// **Why is this bad?** Too complex types make the code less readable. Consider
732 /// using a `type` definition to simplify them.
733 ///
734 /// **Known problems:** None.
735 ///
736 /// **Example:**
737 /// ```rust
738 /// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
739 /// ```
740 declare_lint! {
741     pub TYPE_COMPLEXITY,
742     Warn,
743     "usage of very complex types that might be better factored into `type` definitions"
744 }
745
746 #[allow(missing_copy_implementations)]
747 pub struct TypeComplexityPass {
748     threshold: u64,
749 }
750
751 impl TypeComplexityPass {
752     pub fn new(threshold: u64) -> Self {
753         TypeComplexityPass { threshold: threshold }
754     }
755 }
756
757 impl LintPass for TypeComplexityPass {
758     fn get_lints(&self) -> LintArray {
759         lint_array!(TYPE_COMPLEXITY)
760     }
761 }
762
763 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
764     fn check_fn(
765         &mut self,
766         cx: &LateContext<'a, 'tcx>,
767         _: FnKind<'tcx>,
768         decl: &'tcx FnDecl,
769         _: &'tcx Body,
770         _: Span,
771         _: NodeId,
772     ) {
773         self.check_fndecl(cx, decl);
774     }
775
776     fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx StructField) {
777         // enum variants are also struct fields now
778         self.check_type(cx, &field.ty);
779     }
780
781     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
782         match item.node {
783             ItemStatic(ref ty, _, _) |
784             ItemConst(ref ty, _) => self.check_type(cx, ty),
785             // functions, enums, structs, impls and traits are covered
786             _ => (),
787         }
788     }
789
790     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
791         match item.node {
792             TraitItemKind::Const(ref ty, _) |
793             TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
794             TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
795             // methods with default impl are covered by check_fn
796             _ => (),
797         }
798     }
799
800     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
801         match item.node {
802             ImplItemKind::Const(ref ty, _) |
803             ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
804             // methods are covered by check_fn
805             _ => (),
806         }
807     }
808
809     fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
810         if let Some(ref ty) = local.ty {
811             self.check_type(cx, ty);
812         }
813     }
814 }
815
816 impl<'a, 'tcx> TypeComplexityPass {
817     fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
818         for arg in &decl.inputs {
819             self.check_type(cx, arg);
820         }
821         if let Return(ref ty) = decl.output {
822             self.check_type(cx, ty);
823         }
824     }
825
826     fn check_type(&self, cx: &LateContext, ty: &hir::Ty) {
827         if in_macro(ty.span) {
828             return;
829         }
830         let score = {
831             let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
832             visitor.visit_ty(ty);
833             visitor.score
834         };
835
836         if score > self.threshold {
837             span_lint(
838                 cx,
839                 TYPE_COMPLEXITY,
840                 ty.span,
841                 "very complex type used. Consider factoring parts into `type` definitions",
842             );
843         }
844     }
845 }
846
847 /// Walks a type and assigns a complexity score to it.
848 struct TypeComplexityVisitor {
849     /// total complexity score of the type
850     score: u64,
851     /// current nesting level
852     nest: u64,
853 }
854
855 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
856     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
857         let (add_score, sub_nest) = match ty.node {
858             // _, &x and *x have only small overhead; don't mess with nesting level
859             TyInfer | TyPtr(..) | TyRptr(..) => (1, 0),
860
861             // the "normal" components of a type: named types, arrays/tuples
862             TyPath(..) | TySlice(..) | TyTup(..) | TyArray(..) => (10 * self.nest, 1),
863
864             // function types bring a lot of overhead
865             TyBareFn(..) => (50 * self.nest, 1),
866
867             TyTraitObject(ref param_bounds, _) => {
868                 let has_lifetime_parameters = param_bounds.iter().any(
869                     |bound| !bound.bound_lifetimes.is_empty(),
870                 );
871                 if has_lifetime_parameters {
872                     // complex trait bounds like A<'a, 'b>
873                     (50 * self.nest, 1)
874                 } else {
875                     // simple trait bounds like A + B
876                     (20 * self.nest, 0)
877                 }
878             },
879
880             _ => (0, 0),
881         };
882         self.score += add_score;
883         self.nest += sub_nest;
884         walk_ty(self, ty);
885         self.nest -= sub_nest;
886     }
887     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
888         NestedVisitorMap::None
889     }
890 }
891
892 /// **What it does:** Checks for expressions where a character literal is cast
893 /// to `u8` and suggests using a byte literal instead.
894 ///
895 /// **Why is this bad?** In general, casting values to smaller types is
896 /// error-prone and should be avoided where possible. In the particular case of
897 /// converting a character literal to u8, it is easy to avoid by just using a
898 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
899 /// than `'a' as u8`.
900 ///
901 /// **Known problems:** None.
902 ///
903 /// **Example:**
904 /// ```rust
905 /// 'x' as u8
906 /// ```
907 declare_lint! {
908     pub CHAR_LIT_AS_U8,
909     Warn,
910     "casting a character literal to u8"
911 }
912
913 pub struct CharLitAsU8;
914
915 impl LintPass for CharLitAsU8 {
916     fn get_lints(&self) -> LintArray {
917         lint_array!(CHAR_LIT_AS_U8)
918     }
919 }
920
921 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
922     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
923         use syntax::ast::{LitKind, UintTy};
924
925         if let ExprCast(ref e, _) = expr.node {
926             if let ExprLit(ref l) = e.node {
927                 if let LitKind::Char(_) = l.node {
928                     if ty::TyUint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
929                         let msg = "casting character literal to u8. `char`s \
930                                    are 4 bytes wide in rust, so casting to u8 \
931                                    truncates them";
932                         let help = format!("Consider using a byte literal instead:\nb{}", snippet(cx, e.span, "'x'"));
933                         span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
934                     }
935                 }
936             }
937         }
938     }
939 }
940
941 /// **What it does:** Checks for comparisons where one side of the relation is
942 /// either the minimum or maximum value for its type and warns if it involves a
943 /// case that is always true or always false. Only integer and boolean types are
944 /// checked.
945 ///
946 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
947 /// that is is possible for `x` to be less than the minimum. Expressions like
948 /// `max < x` are probably mistakes.
949 ///
950 /// **Known problems:** None.
951 ///
952 /// **Example:**
953 /// ```rust
954 /// vec.len() <= 0
955 /// 100 > std::i32::MAX
956 /// ```
957 declare_lint! {
958     pub ABSURD_EXTREME_COMPARISONS,
959     Warn,
960     "a comparison with a maximum or minimum value that is always true or false"
961 }
962
963 pub struct AbsurdExtremeComparisons;
964
965 impl LintPass for AbsurdExtremeComparisons {
966     fn get_lints(&self) -> LintArray {
967         lint_array!(ABSURD_EXTREME_COMPARISONS)
968     }
969 }
970
971 enum ExtremeType {
972     Minimum,
973     Maximum,
974 }
975
976 struct ExtremeExpr<'a> {
977     which: ExtremeType,
978     expr: &'a Expr,
979 }
980
981 enum AbsurdComparisonResult {
982     AlwaysFalse,
983     AlwaysTrue,
984     InequalityImpossible,
985 }
986
987
988
989 fn detect_absurd_comparison<'a>(
990     cx: &LateContext,
991     op: BinOp_,
992     lhs: &'a Expr,
993     rhs: &'a Expr,
994 ) -> Option<(ExtremeExpr<'a>, AbsurdComparisonResult)> {
995     use types::ExtremeType::*;
996     use types::AbsurdComparisonResult::*;
997     use utils::comparisons::*;
998
999     // absurd comparison only makes sense on primitive types
1000     // primitive types don't implement comparison operators with each other
1001     if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1002         return None;
1003     }
1004
1005     let normalized = normalize_comparison(op, lhs, rhs);
1006     let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1007         val
1008     } else {
1009         return None;
1010     };
1011
1012     let lx = detect_extreme_expr(cx, normalized_lhs);
1013     let rx = detect_extreme_expr(cx, normalized_rhs);
1014
1015     Some(match rel {
1016         Rel::Lt => {
1017             match (lx, rx) {
1018                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1019                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1020                 _ => return None,
1021             }
1022         },
1023         Rel::Le => {
1024             match (lx, rx) {
1025                 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1026                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), //max <= x
1027                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1028                 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1029                 _ => return None,
1030             }
1031         },
1032         Rel::Ne | Rel::Eq => return None,
1033     })
1034 }
1035
1036 fn detect_extreme_expr<'a>(cx: &LateContext, expr: &'a Expr) -> Option<ExtremeExpr<'a>> {
1037     use rustc::middle::const_val::ConstVal::*;
1038     use rustc_const_math::*;
1039     use rustc_const_eval::*;
1040     use types::ExtremeType::*;
1041
1042     let ty = cx.tables.expr_ty(expr);
1043
1044     match ty.sty {
1045         ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
1046         _ => return None,
1047     };
1048
1049     let parent_item = cx.tcx.hir.get_parent(expr.id);
1050     let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1051     let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1052     let cv = match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
1053         Ok(val) => val,
1054         Err(_) => return None,
1055     };
1056
1057     let which = match (&ty.sty, cv) {
1058         (&ty::TyBool, Bool(false)) |
1059         (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MIN)))) |
1060         (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MIN)))) |
1061         (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MIN))) |
1062         (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MIN))) |
1063         (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MIN))) |
1064         (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MIN))) |
1065         (&ty::TyInt(IntTy::I128), Integral(I128(::std::i128::MIN))) |
1066         (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MIN)))) |
1067         (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MIN)))) |
1068         (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MIN))) |
1069         (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MIN))) |
1070         (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MIN))) |
1071         (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MIN))) |
1072         (&ty::TyUint(UintTy::U128), Integral(U128(::std::u128::MIN))) => Minimum,
1073
1074         (&ty::TyBool, Bool(true)) |
1075         (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MAX)))) |
1076         (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MAX)))) |
1077         (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MAX))) |
1078         (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MAX))) |
1079         (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MAX))) |
1080         (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MAX))) |
1081         (&ty::TyInt(IntTy::I128), Integral(I128(::std::i128::MAX))) |
1082         (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MAX)))) |
1083         (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MAX)))) |
1084         (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MAX))) |
1085         (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MAX))) |
1086         (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MAX))) |
1087         (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MAX))) |
1088         (&ty::TyUint(UintTy::U128), Integral(U128(::std::u128::MAX))) => Maximum,
1089
1090         _ => return None,
1091     };
1092     Some(ExtremeExpr {
1093         which: which,
1094         expr: expr,
1095     })
1096 }
1097
1098 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1099     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1100         use types::ExtremeType::*;
1101         use types::AbsurdComparisonResult::*;
1102
1103         if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1104             if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1105                 if !in_macro(expr.span) {
1106                     let msg = "this comparison involving the minimum or maximum element for this \
1107                                type contains a case that is always true or always false";
1108
1109                     let conclusion = match result {
1110                         AlwaysFalse => "this comparison is always false".to_owned(),
1111                         AlwaysTrue => "this comparison is always true".to_owned(),
1112                         InequalityImpossible => {
1113                             format!(
1114                                 "the case where the two sides are not equal never occurs, consider using {} == {} \
1115                                      instead",
1116                                 snippet(cx, lhs.span, "lhs"),
1117                                 snippet(cx, rhs.span, "rhs")
1118                             )
1119                         },
1120                     };
1121
1122                     let help = format!(
1123                         "because {} is the {} value for this type, {}",
1124                         snippet(cx, culprit.expr.span, "x"),
1125                         match culprit.which {
1126                             Minimum => "minimum",
1127                             Maximum => "maximum",
1128                         },
1129                         conclusion
1130                     );
1131
1132                     span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1133                 }
1134             }
1135         }
1136     }
1137 }
1138
1139 /// **What it does:** Checks for comparisons where the relation is always either
1140 /// true or false, but where one side has been upcast so that the comparison is
1141 /// necessary. Only integer types are checked.
1142 ///
1143 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1144 /// will mistakenly imply that it is possible for `x` to be outside the range of
1145 /// `u8`.
1146 ///
1147 /// **Known problems:** https://github.com/Manishearth/rust-clippy/issues/886
1148 ///
1149 /// **Example:**
1150 /// ```rust
1151 /// let x : u8 = ...; (x as u32) > 300
1152 /// ```
1153 declare_lint! {
1154     pub INVALID_UPCAST_COMPARISONS,
1155     Allow,
1156     "a comparison involving an upcast which is always true or false"
1157 }
1158
1159 pub struct InvalidUpcastComparisons;
1160
1161 impl LintPass for InvalidUpcastComparisons {
1162     fn get_lints(&self) -> LintArray {
1163         lint_array!(INVALID_UPCAST_COMPARISONS)
1164     }
1165 }
1166
1167 #[derive(Copy, Clone, Debug, Eq)]
1168 enum FullInt {
1169     S(i128),
1170     U(u128),
1171 }
1172
1173 impl FullInt {
1174     #[allow(cast_sign_loss)]
1175     fn cmp_s_u(s: i128, u: u128) -> Ordering {
1176         if s < 0 {
1177             Ordering::Less
1178         } else if u > (i128::max_value() as u128) {
1179             Ordering::Greater
1180         } else {
1181             (s as u128).cmp(&u)
1182         }
1183     }
1184 }
1185
1186 impl PartialEq for FullInt {
1187     fn eq(&self, other: &Self) -> bool {
1188         self.partial_cmp(other).expect(
1189             "partial_cmp only returns Some(_)",
1190         ) == Ordering::Equal
1191     }
1192 }
1193
1194 impl PartialOrd for FullInt {
1195     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1196         Some(match (self, other) {
1197             (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1198             (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1199             (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1200             (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1201         })
1202     }
1203 }
1204 impl Ord for FullInt {
1205     fn cmp(&self, other: &Self) -> Ordering {
1206         self.partial_cmp(other).expect(
1207             "partial_cmp for FullInt can never return None",
1208         )
1209     }
1210 }
1211
1212
1213 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1214     use syntax::ast::{IntTy, UintTy};
1215     use std::*;
1216
1217     if let ExprCast(ref cast_exp, _) = expr.node {
1218         let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1219         let cast_ty = cx.tables.expr_ty(expr);
1220         // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1221         if type_size(cx, pre_cast_ty) == type_size(cx, cast_ty) {
1222             return None;
1223         }
1224         match pre_cast_ty.sty {
1225             ty::TyInt(int_ty) => {
1226                 Some(match int_ty {
1227                     IntTy::I8 => (FullInt::S(i8::min_value() as i128), FullInt::S(i8::max_value() as i128)),
1228                     IntTy::I16 => (FullInt::S(i16::min_value() as i128), FullInt::S(i16::max_value() as i128)),
1229                     IntTy::I32 => (FullInt::S(i32::min_value() as i128), FullInt::S(i32::max_value() as i128)),
1230                     IntTy::I64 => (FullInt::S(i64::min_value() as i128), FullInt::S(i64::max_value() as i128)),
1231                     IntTy::I128 => (FullInt::S(i128::min_value() as i128), FullInt::S(i128::max_value() as i128)),
1232                     IntTy::Is => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)),
1233                 })
1234             },
1235             ty::TyUint(uint_ty) => {
1236                 Some(match uint_ty {
1237                     UintTy::U8 => (FullInt::U(u8::min_value() as u128), FullInt::U(u8::max_value() as u128)),
1238                     UintTy::U16 => (FullInt::U(u16::min_value() as u128), FullInt::U(u16::max_value() as u128)),
1239                     UintTy::U32 => (FullInt::U(u32::min_value() as u128), FullInt::U(u32::max_value() as u128)),
1240                     UintTy::U64 => (FullInt::U(u64::min_value() as u128), FullInt::U(u64::max_value() as u128)),
1241                     UintTy::U128 => (FullInt::U(u128::min_value() as u128), FullInt::U(u128::max_value() as u128)),
1242                     UintTy::Us => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
1243                 })
1244             },
1245             _ => None,
1246         }
1247     } else {
1248         None
1249     }
1250 }
1251
1252 #[allow(cast_possible_wrap)]
1253 fn node_as_const_fullint(cx: &LateContext, expr: &Expr) -> Option<FullInt> {
1254     use rustc::middle::const_val::ConstVal::*;
1255     use rustc_const_eval::ConstContext;
1256
1257     let parent_item = cx.tcx.hir.get_parent(expr.id);
1258     let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1259     let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1260     match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
1261         Ok(val) => {
1262             if let Integral(const_int) = val {
1263                 match const_int.int_type() {
1264                     IntType::SignedInt(_) => Some(FullInt::S(const_int.to_u128_unchecked() as i128)),
1265                     IntType::UnsignedInt(_) => Some(FullInt::U(const_int.to_u128_unchecked())),
1266                 }
1267             } else {
1268                 None
1269             }
1270         },
1271         Err(_) => None,
1272     }
1273 }
1274
1275 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
1276     if let ExprCast(ref cast_val, _) = expr.node {
1277         span_lint(
1278             cx,
1279             INVALID_UPCAST_COMPARISONS,
1280             *span,
1281             &format!(
1282                 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1283                 snippet(cx, cast_val.span, "the expression"),
1284                 if always { "true" } else { "false" },
1285             ),
1286         );
1287     }
1288 }
1289
1290 fn upcast_comparison_bounds_err(
1291     cx: &LateContext,
1292     span: &Span,
1293     rel: comparisons::Rel,
1294     lhs_bounds: Option<(FullInt, FullInt)>,
1295     lhs: &Expr,
1296     rhs: &Expr,
1297     invert: bool,
1298 ) {
1299     use utils::comparisons::*;
1300
1301     if let Some((lb, ub)) = lhs_bounds {
1302         if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1303             if rel == Rel::Eq || rel == Rel::Ne {
1304                 if norm_rhs_val < lb || norm_rhs_val > ub {
1305                     err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1306                 }
1307             } else if match rel {
1308                        Rel::Lt => {
1309                            if invert {
1310                                norm_rhs_val < lb
1311                            } else {
1312                                ub < norm_rhs_val
1313                            }
1314                        },
1315                        Rel::Le => {
1316                            if invert {
1317                                norm_rhs_val <= lb
1318                            } else {
1319                                ub <= norm_rhs_val
1320                            }
1321                        },
1322                        Rel::Eq | Rel::Ne => unreachable!(),
1323                    }
1324             {
1325                 err_upcast_comparison(cx, span, lhs, true)
1326             } else if match rel {
1327                        Rel::Lt => {
1328                            if invert {
1329                                norm_rhs_val >= ub
1330                            } else {
1331                                lb >= norm_rhs_val
1332                            }
1333                        },
1334                        Rel::Le => {
1335                            if invert {
1336                                norm_rhs_val > ub
1337                            } else {
1338                                lb > norm_rhs_val
1339                            }
1340                        },
1341                        Rel::Eq | Rel::Ne => unreachable!(),
1342                    }
1343             {
1344                 err_upcast_comparison(cx, span, lhs, false)
1345             }
1346         }
1347     }
1348 }
1349
1350 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1351     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1352         if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1353
1354             let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1355             let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1356                 val
1357             } else {
1358                 return;
1359             };
1360
1361             let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1362             let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1363
1364             upcast_comparison_bounds_err(cx, &expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1365             upcast_comparison_bounds_err(cx, &expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
1366         }
1367     }
1368 }