]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/types.rs
Incorporate upstream changes
[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, TyCtxt};
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};
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(&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, tcx: TyCtxt) -> u64 {
503     match typ.sty {
504         ty::TyInt(i) => match i {
505             IntTy::Is => tcx.data_layout.pointer_size.bits(),
506             IntTy::I8 => 8,
507             IntTy::I16 => 16,
508             IntTy::I32 => 32,
509             IntTy::I64 => 64,
510             IntTy::I128 => 128,
511         },
512         ty::TyUint(i) => match i {
513             UintTy::Us => tcx.data_layout.pointer_size.bits(),
514             UintTy::U8 => 8,
515             UintTy::U16 => 16,
516             UintTy::U32 => 32,
517             UintTy::U64 => 64,
518             UintTy::U128 => 128,
519         },
520         _ => 0,
521     }
522 }
523
524 fn is_isize_or_usize(typ: Ty) -> bool {
525     match typ.sty {
526         ty::TyInt(IntTy::Is) |
527         ty::TyUint(UintTy::Us) => true,
528         _ => false,
529     }
530 }
531
532 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to_f64: bool) {
533     let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
534     let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
535     let arch_dependent_str = "on targets with 64-bit wide pointers ";
536     let from_nbits_str = if arch_dependent {
537         "64".to_owned()
538     } else if is_isize_or_usize(cast_from) {
539         "32 or 64".to_owned()
540     } else {
541         int_ty_to_nbits(cast_from, cx.tcx).to_string()
542     };
543     span_lint(
544         cx,
545         CAST_PRECISION_LOSS,
546         expr.span,
547         &format!(
548             "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
549                         is only {4} bits wide)",
550             cast_from,
551             if cast_to_f64 { "f64" } else { "f32" },
552             if arch_dependent {
553                 arch_dependent_str
554             } else {
555                 ""
556             },
557             from_nbits_str,
558             mantissa_nbits
559         ),
560     );
561 }
562
563 enum ArchSuffix {
564     _32,
565     _64,
566     None,
567 }
568
569 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to: Ty) {
570     let arch_64_suffix = " on targets with 64-bit wide pointers";
571     let arch_32_suffix = " on targets with 32-bit wide pointers";
572     let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
573     let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
574     let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
575     let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
576         match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
577             (true, true) | (false, false) => {
578                 (
579                     to_nbits < from_nbits,
580                     ArchSuffix::None,
581                     to_nbits == from_nbits && cast_unsigned_to_signed,
582                     ArchSuffix::None,
583                 )
584             },
585             (true, false) => {
586                 (
587                     to_nbits <= 32,
588                     if to_nbits == 32 {
589                         ArchSuffix::_64
590                     } else {
591                         ArchSuffix::None
592                     },
593                     to_nbits <= 32 && cast_unsigned_to_signed,
594                     ArchSuffix::_32,
595                 )
596             },
597             (false, true) => {
598                 (
599                     from_nbits == 64,
600                     ArchSuffix::_32,
601                     cast_unsigned_to_signed,
602                     if from_nbits == 64 {
603                         ArchSuffix::_64
604                     } else {
605                         ArchSuffix::_32
606                     },
607                 )
608             },
609         };
610     if span_truncation {
611         span_lint(
612             cx,
613             CAST_POSSIBLE_TRUNCATION,
614             expr.span,
615             &format!(
616                 "casting {} to {} may truncate the value{}",
617                 cast_from,
618                 cast_to,
619                 match suffix_truncation {
620                     ArchSuffix::_32 => arch_32_suffix,
621                     ArchSuffix::_64 => arch_64_suffix,
622                     ArchSuffix::None => "",
623                 }
624             ),
625         );
626     }
627     if span_wrap {
628         span_lint(
629             cx,
630             CAST_POSSIBLE_WRAP,
631             expr.span,
632             &format!(
633                 "casting {} to {} may wrap around the value{}",
634                 cast_from,
635                 cast_to,
636                 match suffix_wrap {
637                     ArchSuffix::_32 => arch_32_suffix,
638                     ArchSuffix::_64 => arch_64_suffix,
639                     ArchSuffix::None => "",
640                 }
641             ),
642         );
643     }
644 }
645
646 impl LintPass for CastPass {
647     fn get_lints(&self) -> LintArray {
648         lint_array!(
649             CAST_PRECISION_LOSS,
650             CAST_SIGN_LOSS,
651             CAST_POSSIBLE_TRUNCATION,
652             CAST_POSSIBLE_WRAP,
653             UNNECESSARY_CAST
654         )
655     }
656 }
657
658 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
659     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
660         if let ExprCast(ref ex, _) = expr.node {
661             let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
662             if let ExprLit(ref lit) = ex.node {
663                 use syntax::ast::{LitKind, LitIntType};
664                 match lit.node {
665                     LitKind::Int(_, LitIntType::Unsuffixed) |
666                     LitKind::FloatUnsuffixed(_) => {},
667                     _ => {
668                         if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
669                             span_lint(
670                                 cx,
671                                 UNNECESSARY_CAST,
672                                 expr.span,
673                                 &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
674                             );
675                         }
676                     },
677                 }
678             }
679             if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
680                 match (cast_from.is_integral(), cast_to.is_integral()) {
681                     (true, false) => {
682                         let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
683                         let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
684                             32
685                         } else {
686                             64
687                         };
688                         if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
689                             span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
690                         }
691                     },
692                     (false, true) => {
693                         span_lint(
694                             cx,
695                             CAST_POSSIBLE_TRUNCATION,
696                             expr.span,
697                             &format!("casting {} to {} may truncate the value", cast_from, cast_to),
698                         );
699                         if !cast_to.is_signed() {
700                             span_lint(
701                                 cx,
702                                 CAST_SIGN_LOSS,
703                                 expr.span,
704                                 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
705                             );
706                         }
707                     },
708                     (true, true) => {
709                         if cast_from.is_signed() && !cast_to.is_signed() {
710                             span_lint(
711                                 cx,
712                                 CAST_SIGN_LOSS,
713                                 expr.span,
714                                 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
715                             );
716                         }
717                         check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
718                     },
719                     (false, false) => {
720                         if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) =
721                             (&cast_from.sty, &cast_to.sty)
722                         {
723                             span_lint(
724                                 cx,
725                                 CAST_POSSIBLE_TRUNCATION,
726                                 expr.span,
727                                 "casting f64 to f32 may truncate the value",
728                             );
729                         }
730                     },
731                 }
732             }
733         }
734     }
735 }
736
737 /// **What it does:** Checks for types used in structs, parameters and `let`
738 /// declarations above a certain complexity threshold.
739 ///
740 /// **Why is this bad?** Too complex types make the code less readable. Consider
741 /// using a `type` definition to simplify them.
742 ///
743 /// **Known problems:** None.
744 ///
745 /// **Example:**
746 /// ```rust
747 /// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
748 /// ```
749 declare_lint! {
750     pub TYPE_COMPLEXITY,
751     Warn,
752     "usage of very complex types that might be better factored into `type` definitions"
753 }
754
755 #[allow(missing_copy_implementations)]
756 pub struct TypeComplexityPass {
757     threshold: u64,
758 }
759
760 impl TypeComplexityPass {
761     pub fn new(threshold: u64) -> Self {
762         Self { threshold: threshold }
763     }
764 }
765
766 impl LintPass for TypeComplexityPass {
767     fn get_lints(&self) -> LintArray {
768         lint_array!(TYPE_COMPLEXITY)
769     }
770 }
771
772 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
773     fn check_fn(
774         &mut self,
775         cx: &LateContext<'a, 'tcx>,
776         _: FnKind<'tcx>,
777         decl: &'tcx FnDecl,
778         _: &'tcx Body,
779         _: Span,
780         _: NodeId,
781     ) {
782         self.check_fndecl(cx, decl);
783     }
784
785     fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx StructField) {
786         // enum variants are also struct fields now
787         self.check_type(cx, &field.ty);
788     }
789
790     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
791         match item.node {
792             ItemStatic(ref ty, _, _) |
793             ItemConst(ref ty, _) => self.check_type(cx, ty),
794             // functions, enums, structs, impls and traits are covered
795             _ => (),
796         }
797     }
798
799     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
800         match item.node {
801             TraitItemKind::Const(ref ty, _) |
802             TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
803             TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
804             // methods with default impl are covered by check_fn
805             _ => (),
806         }
807     }
808
809     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
810         match item.node {
811             ImplItemKind::Const(ref ty, _) |
812             ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
813             // methods are covered by check_fn
814             _ => (),
815         }
816     }
817
818     fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
819         if let Some(ref ty) = local.ty {
820             self.check_type(cx, ty);
821         }
822     }
823 }
824
825 impl<'a, 'tcx> TypeComplexityPass {
826     fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
827         for arg in &decl.inputs {
828             self.check_type(cx, arg);
829         }
830         if let Return(ref ty) = decl.output {
831             self.check_type(cx, ty);
832         }
833     }
834
835     fn check_type(&self, cx: &LateContext, ty: &hir::Ty) {
836         if in_macro(ty.span) {
837             return;
838         }
839         let score = {
840             let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
841             visitor.visit_ty(ty);
842             visitor.score
843         };
844
845         if score > self.threshold {
846             span_lint(
847                 cx,
848                 TYPE_COMPLEXITY,
849                 ty.span,
850                 "very complex type used. Consider factoring parts into `type` definitions",
851             );
852         }
853     }
854 }
855
856 /// Walks a type and assigns a complexity score to it.
857 struct TypeComplexityVisitor {
858     /// total complexity score of the type
859     score: u64,
860     /// current nesting level
861     nest: u64,
862 }
863
864 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
865     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
866         let (add_score, sub_nest) = match ty.node {
867             // _, &x and *x have only small overhead; don't mess with nesting level
868             TyInfer | TyPtr(..) | TyRptr(..) => (1, 0),
869
870             // the "normal" components of a type: named types, arrays/tuples
871             TyPath(..) | TySlice(..) | TyTup(..) | TyArray(..) => (10 * self.nest, 1),
872
873             // function types bring a lot of overhead
874             TyBareFn(..) => (50 * self.nest, 1),
875
876             TyTraitObject(ref param_bounds, _) => {
877                 let has_lifetime_parameters = param_bounds.iter().any(
878                     |bound| !bound.bound_lifetimes.is_empty(),
879                 );
880                 if has_lifetime_parameters {
881                     // complex trait bounds like A<'a, 'b>
882                     (50 * self.nest, 1)
883                 } else {
884                     // simple trait bounds like A + B
885                     (20 * self.nest, 0)
886                 }
887             },
888
889             _ => (0, 0),
890         };
891         self.score += add_score;
892         self.nest += sub_nest;
893         walk_ty(self, ty);
894         self.nest -= sub_nest;
895     }
896     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
897         NestedVisitorMap::None
898     }
899 }
900
901 /// **What it does:** Checks for expressions where a character literal is cast
902 /// to `u8` and suggests using a byte literal instead.
903 ///
904 /// **Why is this bad?** In general, casting values to smaller types is
905 /// error-prone and should be avoided where possible. In the particular case of
906 /// converting a character literal to u8, it is easy to avoid by just using a
907 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
908 /// than `'a' as u8`.
909 ///
910 /// **Known problems:** None.
911 ///
912 /// **Example:**
913 /// ```rust
914 /// 'x' as u8
915 /// ```
916 declare_lint! {
917     pub CHAR_LIT_AS_U8,
918     Warn,
919     "casting a character literal to u8"
920 }
921
922 pub struct CharLitAsU8;
923
924 impl LintPass for CharLitAsU8 {
925     fn get_lints(&self) -> LintArray {
926         lint_array!(CHAR_LIT_AS_U8)
927     }
928 }
929
930 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
931     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
932         use syntax::ast::{LitKind, UintTy};
933
934         if let ExprCast(ref e, _) = expr.node {
935             if let ExprLit(ref l) = e.node {
936                 if let LitKind::Char(_) = l.node {
937                     if ty::TyUint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
938                         let msg = "casting character literal to u8. `char`s \
939                                    are 4 bytes wide in rust, so casting to u8 \
940                                    truncates them";
941                         let help = format!("Consider using a byte literal instead:\nb{}", snippet(cx, e.span, "'x'"));
942                         span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
943                     }
944                 }
945             }
946         }
947     }
948 }
949
950 /// **What it does:** Checks for comparisons where one side of the relation is
951 /// either the minimum or maximum value for its type and warns if it involves a
952 /// case that is always true or always false. Only integer and boolean types are
953 /// checked.
954 ///
955 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
956 /// that is is possible for `x` to be less than the minimum. Expressions like
957 /// `max < x` are probably mistakes.
958 ///
959 /// **Known problems:** None.
960 ///
961 /// **Example:**
962 /// ```rust
963 /// vec.len() <= 0
964 /// 100 > std::i32::MAX
965 /// ```
966 declare_lint! {
967     pub ABSURD_EXTREME_COMPARISONS,
968     Warn,
969     "a comparison with a maximum or minimum value that is always true or false"
970 }
971
972 pub struct AbsurdExtremeComparisons;
973
974 impl LintPass for AbsurdExtremeComparisons {
975     fn get_lints(&self) -> LintArray {
976         lint_array!(ABSURD_EXTREME_COMPARISONS)
977     }
978 }
979
980 enum ExtremeType {
981     Minimum,
982     Maximum,
983 }
984
985 struct ExtremeExpr<'a> {
986     which: ExtremeType,
987     expr: &'a Expr,
988 }
989
990 enum AbsurdComparisonResult {
991     AlwaysFalse,
992     AlwaysTrue,
993     InequalityImpossible,
994 }
995
996
997
998 fn detect_absurd_comparison<'a>(
999     cx: &LateContext,
1000     op: BinOp_,
1001     lhs: &'a Expr,
1002     rhs: &'a Expr,
1003 ) -> Option<(ExtremeExpr<'a>, AbsurdComparisonResult)> {
1004     use types::ExtremeType::*;
1005     use types::AbsurdComparisonResult::*;
1006     use utils::comparisons::*;
1007
1008     // absurd comparison only makes sense on primitive types
1009     // primitive types don't implement comparison operators with each other
1010     if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1011         return None;
1012     }
1013
1014     let normalized = normalize_comparison(op, lhs, rhs);
1015     let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1016         val
1017     } else {
1018         return None;
1019     };
1020
1021     let lx = detect_extreme_expr(cx, normalized_lhs);
1022     let rx = detect_extreme_expr(cx, normalized_rhs);
1023
1024     Some(match rel {
1025         Rel::Lt => {
1026             match (lx, rx) {
1027                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1028                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1029                 _ => return None,
1030             }
1031         },
1032         Rel::Le => {
1033             match (lx, rx) {
1034                 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1035                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), //max <= x
1036                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1037                 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1038                 _ => return None,
1039             }
1040         },
1041         Rel::Ne | Rel::Eq => return None,
1042     })
1043 }
1044
1045 fn detect_extreme_expr<'a>(cx: &LateContext, expr: &'a Expr) -> Option<ExtremeExpr<'a>> {
1046     use rustc::middle::const_val::ConstVal::*;
1047     use rustc_const_math::*;
1048     use rustc_const_eval::*;
1049     use types::ExtremeType::*;
1050
1051     let ty = cx.tables.expr_ty(expr);
1052
1053     match ty.sty {
1054         ty::TyBool | ty::TyInt(_) | ty::TyUint(_) => (),
1055         _ => return None,
1056     };
1057
1058     let parent_item = cx.tcx.hir.get_parent(expr.id);
1059     let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1060     let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1061     let cv = match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
1062         Ok(val) => val,
1063         Err(_) => return None,
1064     };
1065
1066     let which = match (&ty.sty, cv) {
1067         (&ty::TyBool, Bool(false)) |
1068         (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MIN)))) |
1069         (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MIN)))) |
1070         (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MIN))) |
1071         (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MIN))) |
1072         (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MIN))) |
1073         (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MIN))) |
1074         (&ty::TyInt(IntTy::I128), Integral(I128(::std::i128::MIN))) |
1075         (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MIN)))) |
1076         (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MIN)))) |
1077         (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MIN))) |
1078         (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MIN))) |
1079         (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MIN))) |
1080         (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MIN))) |
1081         (&ty::TyUint(UintTy::U128), Integral(U128(::std::u128::MIN))) => Minimum,
1082
1083         (&ty::TyBool, Bool(true)) |
1084         (&ty::TyInt(IntTy::Is), Integral(Isize(Is32(::std::i32::MAX)))) |
1085         (&ty::TyInt(IntTy::Is), Integral(Isize(Is64(::std::i64::MAX)))) |
1086         (&ty::TyInt(IntTy::I8), Integral(I8(::std::i8::MAX))) |
1087         (&ty::TyInt(IntTy::I16), Integral(I16(::std::i16::MAX))) |
1088         (&ty::TyInt(IntTy::I32), Integral(I32(::std::i32::MAX))) |
1089         (&ty::TyInt(IntTy::I64), Integral(I64(::std::i64::MAX))) |
1090         (&ty::TyInt(IntTy::I128), Integral(I128(::std::i128::MAX))) |
1091         (&ty::TyUint(UintTy::Us), Integral(Usize(Us32(::std::u32::MAX)))) |
1092         (&ty::TyUint(UintTy::Us), Integral(Usize(Us64(::std::u64::MAX)))) |
1093         (&ty::TyUint(UintTy::U8), Integral(U8(::std::u8::MAX))) |
1094         (&ty::TyUint(UintTy::U16), Integral(U16(::std::u16::MAX))) |
1095         (&ty::TyUint(UintTy::U32), Integral(U32(::std::u32::MAX))) |
1096         (&ty::TyUint(UintTy::U64), Integral(U64(::std::u64::MAX))) |
1097         (&ty::TyUint(UintTy::U128), Integral(U128(::std::u128::MAX))) => Maximum,
1098
1099         _ => return None,
1100     };
1101     Some(ExtremeExpr {
1102         which: which,
1103         expr: expr,
1104     })
1105 }
1106
1107 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1108     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1109         use types::ExtremeType::*;
1110         use types::AbsurdComparisonResult::*;
1111
1112         if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1113             if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1114                 if !in_macro(expr.span) {
1115                     let msg = "this comparison involving the minimum or maximum element for this \
1116                                type contains a case that is always true or always false";
1117
1118                     let conclusion = match result {
1119                         AlwaysFalse => "this comparison is always false".to_owned(),
1120                         AlwaysTrue => "this comparison is always true".to_owned(),
1121                         InequalityImpossible => {
1122                             format!(
1123                                 "the case where the two sides are not equal never occurs, consider using {} == {} \
1124                                      instead",
1125                                 snippet(cx, lhs.span, "lhs"),
1126                                 snippet(cx, rhs.span, "rhs")
1127                             )
1128                         },
1129                     };
1130
1131                     let help = format!(
1132                         "because {} is the {} value for this type, {}",
1133                         snippet(cx, culprit.expr.span, "x"),
1134                         match culprit.which {
1135                             Minimum => "minimum",
1136                             Maximum => "maximum",
1137                         },
1138                         conclusion
1139                     );
1140
1141                     span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1142                 }
1143             }
1144         }
1145     }
1146 }
1147
1148 /// **What it does:** Checks for comparisons where the relation is always either
1149 /// true or false, but where one side has been upcast so that the comparison is
1150 /// necessary. Only integer types are checked.
1151 ///
1152 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1153 /// will mistakenly imply that it is possible for `x` to be outside the range of
1154 /// `u8`.
1155 ///
1156 /// **Known problems:** https://github.com/rust-lang-nursery/rust-clippy/issues/886
1157 ///
1158 /// **Example:**
1159 /// ```rust
1160 /// let x : u8 = ...; (x as u32) > 300
1161 /// ```
1162 declare_lint! {
1163     pub INVALID_UPCAST_COMPARISONS,
1164     Allow,
1165     "a comparison involving an upcast which is always true or false"
1166 }
1167
1168 pub struct InvalidUpcastComparisons;
1169
1170 impl LintPass for InvalidUpcastComparisons {
1171     fn get_lints(&self) -> LintArray {
1172         lint_array!(INVALID_UPCAST_COMPARISONS)
1173     }
1174 }
1175
1176 #[derive(Copy, Clone, Debug, Eq)]
1177 enum FullInt {
1178     S(i128),
1179     U(u128),
1180 }
1181
1182 impl FullInt {
1183     #[allow(cast_sign_loss)]
1184     fn cmp_s_u(s: i128, u: u128) -> Ordering {
1185         if s < 0 {
1186             Ordering::Less
1187         } else if u > (i128::max_value() as u128) {
1188             Ordering::Greater
1189         } else {
1190             (s as u128).cmp(&u)
1191         }
1192     }
1193 }
1194
1195 impl PartialEq for FullInt {
1196     fn eq(&self, other: &Self) -> bool {
1197         self.partial_cmp(other).expect(
1198             "partial_cmp only returns Some(_)",
1199         ) == Ordering::Equal
1200     }
1201 }
1202
1203 impl PartialOrd for FullInt {
1204     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1205         Some(match (self, other) {
1206             (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1207             (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1208             (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1209             (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1210         })
1211     }
1212 }
1213 impl Ord for FullInt {
1214     fn cmp(&self, other: &Self) -> Ordering {
1215         self.partial_cmp(other).expect(
1216             "partial_cmp for FullInt can never return None",
1217         )
1218     }
1219 }
1220
1221
1222 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1223     use syntax::ast::{IntTy, UintTy};
1224     use std::*;
1225
1226     if let ExprCast(ref cast_exp, _) = expr.node {
1227         let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1228         let cast_ty = cx.tables.expr_ty(expr);
1229         // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1230         if type_size(cx, pre_cast_ty) == type_size(cx, cast_ty) {
1231             return None;
1232         }
1233         match pre_cast_ty.sty {
1234             ty::TyInt(int_ty) => {
1235                 Some(match int_ty {
1236                     IntTy::I8 => (FullInt::S(i8::min_value() as i128), FullInt::S(i8::max_value() as i128)),
1237                     IntTy::I16 => (FullInt::S(i16::min_value() as i128), FullInt::S(i16::max_value() as i128)),
1238                     IntTy::I32 => (FullInt::S(i32::min_value() as i128), FullInt::S(i32::max_value() as i128)),
1239                     IntTy::I64 => (FullInt::S(i64::min_value() as i128), FullInt::S(i64::max_value() as i128)),
1240                     IntTy::I128 => (FullInt::S(i128::min_value() as i128), FullInt::S(i128::max_value() as i128)),
1241                     IntTy::Is => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)),
1242                 })
1243             },
1244             ty::TyUint(uint_ty) => {
1245                 Some(match uint_ty {
1246                     UintTy::U8 => (FullInt::U(u8::min_value() as u128), FullInt::U(u8::max_value() as u128)),
1247                     UintTy::U16 => (FullInt::U(u16::min_value() as u128), FullInt::U(u16::max_value() as u128)),
1248                     UintTy::U32 => (FullInt::U(u32::min_value() as u128), FullInt::U(u32::max_value() as u128)),
1249                     UintTy::U64 => (FullInt::U(u64::min_value() as u128), FullInt::U(u64::max_value() as u128)),
1250                     UintTy::U128 => (FullInt::U(u128::min_value() as u128), FullInt::U(u128::max_value() as u128)),
1251                     UintTy::Us => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
1252                 })
1253             },
1254             _ => None,
1255         }
1256     } else {
1257         None
1258     }
1259 }
1260
1261 #[allow(cast_possible_wrap)]
1262 fn node_as_const_fullint(cx: &LateContext, expr: &Expr) -> Option<FullInt> {
1263     use rustc::middle::const_val::ConstVal::*;
1264     use rustc_const_eval::ConstContext;
1265
1266     let parent_item = cx.tcx.hir.get_parent(expr.id);
1267     let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1268     let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1269     match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
1270         Ok(val) => {
1271             if let Integral(const_int) = val {
1272                 match const_int.int_type() {
1273                     IntType::SignedInt(_) => Some(FullInt::S(const_int.to_u128_unchecked() as i128)),
1274                     IntType::UnsignedInt(_) => Some(FullInt::U(const_int.to_u128_unchecked())),
1275                 }
1276             } else {
1277                 None
1278             }
1279         },
1280         Err(_) => None,
1281     }
1282 }
1283
1284 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
1285     if let ExprCast(ref cast_val, _) = expr.node {
1286         span_lint(
1287             cx,
1288             INVALID_UPCAST_COMPARISONS,
1289             *span,
1290             &format!(
1291                 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1292                 snippet(cx, cast_val.span, "the expression"),
1293                 if always { "true" } else { "false" },
1294             ),
1295         );
1296     }
1297 }
1298
1299 fn upcast_comparison_bounds_err(
1300     cx: &LateContext,
1301     span: &Span,
1302     rel: comparisons::Rel,
1303     lhs_bounds: Option<(FullInt, FullInt)>,
1304     lhs: &Expr,
1305     rhs: &Expr,
1306     invert: bool,
1307 ) {
1308     use utils::comparisons::*;
1309
1310     if let Some((lb, ub)) = lhs_bounds {
1311         if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1312             if rel == Rel::Eq || rel == Rel::Ne {
1313                 if norm_rhs_val < lb || norm_rhs_val > ub {
1314                     err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1315                 }
1316             } else if match rel {
1317                        Rel::Lt => {
1318                            if invert {
1319                                norm_rhs_val < lb
1320                            } else {
1321                                ub < norm_rhs_val
1322                            }
1323                        },
1324                        Rel::Le => {
1325                            if invert {
1326                                norm_rhs_val <= lb
1327                            } else {
1328                                ub <= norm_rhs_val
1329                            }
1330                        },
1331                        Rel::Eq | Rel::Ne => unreachable!(),
1332                    }
1333             {
1334                 err_upcast_comparison(cx, span, lhs, true)
1335             } else if match rel {
1336                        Rel::Lt => {
1337                            if invert {
1338                                norm_rhs_val >= ub
1339                            } else {
1340                                lb >= norm_rhs_val
1341                            }
1342                        },
1343                        Rel::Le => {
1344                            if invert {
1345                                norm_rhs_val > ub
1346                            } else {
1347                                lb > norm_rhs_val
1348                            }
1349                        },
1350                        Rel::Eq | Rel::Ne => unreachable!(),
1351                    }
1352             {
1353                 err_upcast_comparison(cx, span, lhs, false)
1354             }
1355         }
1356     }
1357 }
1358
1359 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1360     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1361         if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1362
1363             let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1364             let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1365                 val
1366             } else {
1367                 return;
1368             };
1369
1370             let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1371             let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1372
1373             upcast_comparison_bounds_err(cx, &expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1374             upcast_comparison_bounds_err(cx, &expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
1375         }
1376     }
1377 }