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