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