]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/types.rs
Merge branch 'macro-use' into HEAD
[rust.git] / clippy_lints / src / types.rs
1 use crate::reexport::*;
2 use rustc::hir;
3 use rustc::hir::*;
4 use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
5 use rustc::lint::*;
6 use rustc::{declare_lint, lint_array};
7 use if_chain::if_chain;
8 use rustc::ty::{self, Ty, TyCtxt, TypeckTables};
9 use rustc::ty::layout::LayoutOf;
10 use rustc_typeck::hir_ty_to_ty;
11 use std::cmp::Ordering;
12 use std::collections::BTreeMap;
13 use std::borrow::Cow;
14 use syntax::ast::{FloatTy, IntTy, UintTy};
15 use syntax::codemap::Span;
16 use syntax::errors::DiagnosticBuilder;
17 use crate::utils::{comparisons, differing_macro_contexts, higher, in_constant, in_external_macro, in_macro, last_path_segment, match_def_path, match_path,
18             match_type, multispan_sugg, opt_def_id, same_tys, snippet, snippet_opt, span_help_and_lint, span_lint,
19             span_lint_and_sugg, span_lint_and_then, clip, unsext, sext, int_bits};
20 use crate::utils::paths;
21 use crate::consts::{constant, Constant};
22
23 /// Handles all the linting of funky types
24 #[allow(missing_copy_implementations)]
25 pub struct TypePass;
26
27 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
28 ///
29 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
30 /// the heap. So if you `Box` it, you just add another level of indirection
31 /// without any benefit whatsoever.
32 ///
33 /// **Known problems:** None.
34 ///
35 /// **Example:**
36 /// ```rust
37 /// struct X {
38 ///     values: Box<Vec<Foo>>,
39 /// }
40 /// ```
41 ///
42 /// Better:
43 ///
44 /// ```rust
45 /// struct X {
46 ///     values: Vec<Foo>,
47 /// }
48 /// ```
49 declare_clippy_lint! {
50     pub BOX_VEC,
51     perf,
52     "usage of `Box<Vec<T>>`, vector elements are already on the heap"
53 }
54
55 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
56 /// definitions
57 ///
58 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
59 /// represents an optional optional value which is logically the same thing as an optional
60 /// value but has an unneeded extra level of wrapping.
61 ///
62 /// **Known problems:** None.
63 ///
64 /// **Example**
65 /// ```rust
66 /// fn x() -> Option<Option<u32>> {
67 ///     None
68 /// }
69 declare_clippy_lint! {
70     pub OPTION_OPTION,
71     complexity,
72     "usage of `Option<Option<T>>`"
73 }
74
75 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
76 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
77 ///
78 /// **Why is this bad?** Gankro says:
79 ///
80 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
81 /// pointers and indirection.
82 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
83 /// `RingBuf`, while
84 /// > "only" amortized for push/pop, should be faster in the general case for
85 /// almost every possible
86 /// > workload, and isn't even amortized at all if you can predict the capacity
87 /// you need.
88 /// >
89 /// > `LinkedList`s are only really good if you're doing a lot of merging or
90 /// splitting of lists.
91 /// > This is because they can just mangle some pointers instead of actually
92 /// copying the data. Even
93 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
94 /// can still be better
95 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
96 ///
97 /// **Known problems:** False positives – the instances where using a
98 /// `LinkedList` makes sense are few and far between, but they can still happen.
99 ///
100 /// **Example:**
101 /// ```rust
102 /// let x = LinkedList::new();
103 /// ```
104 declare_clippy_lint! {
105     pub LINKEDLIST,
106     pedantic,
107     "usage of LinkedList, usually a vector is faster, or a more specialized data \
108      structure like a VecDeque"
109 }
110
111 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
112 ///
113 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
114 /// general.
115 ///
116 /// **Known problems:** None.
117 ///
118 /// **Example:**
119 /// ```rust
120 /// fn foo(bar: &Box<T>) { ... }
121 /// ```
122 ///
123 /// Better:
124 ///
125 /// ```rust
126 /// fn foo(bar: &T) { ... }
127 /// ```
128 declare_clippy_lint! {
129     pub BORROWED_BOX,
130     complexity,
131     "a borrow of a boxed type"
132 }
133
134 impl LintPass for TypePass {
135     fn get_lints(&self) -> LintArray {
136         lint_array!(BOX_VEC, OPTION_OPTION, LINKEDLIST, BORROWED_BOX)
137     }
138 }
139
140 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypePass {
141     fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Body, _: Span, id: NodeId) {
142         // skip trait implementations, see #605
143         if let Some(map::NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(id)) {
144             if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
145                 return;
146             }
147         }
148
149         check_fn_decl(cx, decl);
150     }
151
152     fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
153         check_ty(cx, &field.ty, false);
154     }
155
156     fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
157         match item.node {
158             TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
159             TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
160             _ => (),
161         }
162     }
163
164     fn check_local(&mut self, cx: &LateContext, local: &Local) {
165         if let Some(ref ty) = local.ty {
166             check_ty(cx, ty, true);
167         }
168     }
169 }
170
171 fn check_fn_decl(cx: &LateContext, decl: &FnDecl) {
172     for input in &decl.inputs {
173         check_ty(cx, input, false);
174     }
175
176     if let FunctionRetTy::Return(ref ty) = decl.output {
177         check_ty(cx, ty, false);
178     }
179 }
180
181 /// Check if `qpath` has last segment with type parameter matching `path`
182 fn match_type_parameter(cx: &LateContext, qpath: &QPath, path: &[&str]) -> bool {
183     let last = last_path_segment(qpath);
184     if_chain! {
185         if let Some(ref params) = last.args;
186         if !params.parenthesized;
187         if let Some(ty) = params.args.iter().find_map(|arg| match arg {
188             GenericArg::Type(ty) => Some(ty),
189             GenericArg::Lifetime(_) => None,
190         });
191         if let TyKind::Path(ref qpath) = ty.node;
192         if let Some(did) = opt_def_id(cx.tables.qpath_def(qpath, cx.tcx.hir.node_to_hir_id(ty.id)));
193         if match_def_path(cx.tcx, did, path);
194         then {
195             return true;
196         }
197     }
198     false
199 }
200
201 /// Recursively check for `TypePass` lints in the given type. Stop at the first
202 /// lint found.
203 ///
204 /// The parameter `is_local` distinguishes the context of the type; types from
205 /// local bindings should only be checked for the `BORROWED_BOX` lint.
206 fn check_ty(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool) {
207     if in_macro(ast_ty.span) {
208         return;
209     }
210     match ast_ty.node {
211         TyKind::Path(ref qpath) if !is_local => {
212             let hir_id = cx.tcx.hir.node_to_hir_id(ast_ty.id);
213             let def = cx.tables.qpath_def(qpath, hir_id);
214             if let Some(def_id) = opt_def_id(def) {
215                 if Some(def_id) == cx.tcx.lang_items().owned_box() {
216                     if match_type_parameter(cx, qpath, &paths::VEC) {
217                         span_help_and_lint(
218                             cx,
219                             BOX_VEC,
220                             ast_ty.span,
221                             "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
222                             "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
223                         );
224                         return; // don't recurse into the type
225                     }
226                 } else if match_def_path(cx.tcx, def_id, &paths::OPTION) {
227                     if match_type_parameter(cx, qpath, &paths::OPTION) {
228                         span_lint(
229                             cx,
230                             OPTION_OPTION,
231                             ast_ty.span,
232                             "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
233                             enum if you need to distinguish all 3 cases",
234                         );
235                         return; // don't recurse into the type
236                     }
237                 } else if match_def_path(cx.tcx, def_id, &paths::LINKED_LIST) {
238                     span_help_and_lint(
239                         cx,
240                         LINKEDLIST,
241                         ast_ty.span,
242                         "I see you're using a LinkedList! Perhaps you meant some other data structure?",
243                         "a VecDeque might work",
244                     );
245                     return; // don't recurse into the type
246                 }
247             }
248             match *qpath {
249                 QPath::Resolved(Some(ref ty), ref p) => {
250                     check_ty(cx, ty, is_local);
251                     for ty in p.segments.iter().flat_map(|seg| {
252                         seg.args
253                             .as_ref()
254                             .map_or_else(|| [].iter(), |params| params.args.iter())
255                             .filter_map(|arg| match arg {
256                                 GenericArg::Type(ty) => Some(ty),
257                                 GenericArg::Lifetime(_) => None,
258                             })
259                     }) {
260                         check_ty(cx, ty, is_local);
261                     }
262                 },
263                 QPath::Resolved(None, ref p) => for ty in p.segments.iter().flat_map(|seg| {
264                     seg.args
265                         .as_ref()
266                         .map_or_else(|| [].iter(), |params| params.args.iter())
267                         .filter_map(|arg| match arg {
268                             GenericArg::Type(ty) => Some(ty),
269                             GenericArg::Lifetime(_) => None,
270                         })
271                 }) {
272                     check_ty(cx, ty, is_local);
273                 },
274                 QPath::TypeRelative(ref ty, ref seg) => {
275                     check_ty(cx, ty, is_local);
276                     if let Some(ref params) = seg.args {
277                         for ty in params.args.iter().filter_map(|arg| match arg {
278                             GenericArg::Type(ty) => Some(ty),
279                             GenericArg::Lifetime(_) => None,
280                         }) {
281                             check_ty(cx, ty, is_local);
282                         }
283                     }
284                 },
285             }
286         },
287         TyKind::Rptr(ref lt, ref mut_ty) => check_ty_rptr(cx, ast_ty, is_local, lt, mut_ty),
288         // recurse
289         TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
290         TyKind::Tup(ref tys) => for ty in tys {
291             check_ty(cx, ty, is_local);
292         },
293         _ => {},
294     }
295 }
296
297 fn check_ty_rptr(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool, lt: &Lifetime, mut_ty: &MutTy) {
298     match mut_ty.ty.node {
299         TyKind::Path(ref qpath) => {
300             let hir_id = cx.tcx.hir.node_to_hir_id(mut_ty.ty.id);
301             let def = cx.tables.qpath_def(qpath, hir_id);
302             if_chain! {
303                 if let Some(def_id) = opt_def_id(def);
304                 if Some(def_id) == cx.tcx.lang_items().owned_box();
305                 if let QPath::Resolved(None, ref path) = *qpath;
306                 if let [ref bx] = *path.segments;
307                 if let Some(ref params) = bx.args;
308                 if !params.parenthesized;
309                 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
310                     GenericArg::Type(ty) => Some(ty),
311                     GenericArg::Lifetime(_) => None,
312                 });
313                 then {
314                     if is_any_trait(inner) {
315                         // Ignore `Box<Any>` types, see #1884 for details.
316                         return;
317                     }
318
319                     let ltopt = if lt.is_elided() {
320                         "".to_owned()
321                     } else {
322                         format!("{} ", lt.name.ident().name.as_str())
323                     };
324                     let mutopt = if mut_ty.mutbl == Mutability::MutMutable {
325                         "mut "
326                     } else {
327                         ""
328                     };
329                     span_lint_and_sugg(cx,
330                         BORROWED_BOX,
331                         ast_ty.span,
332                         "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
333                         "try",
334                         format!("&{}{}{}", ltopt, mutopt, &snippet(cx, inner.span, ".."))
335                     );
336                     return; // don't recurse into the type
337                 }
338             };
339             check_ty(cx, &mut_ty.ty, is_local);
340         },
341         _ => check_ty(cx, &mut_ty.ty, is_local),
342     }
343 }
344
345 // Returns true if given type is `Any` trait.
346 fn is_any_trait(t: &hir::Ty) -> bool {
347     if_chain! {
348         if let TyKind::TraitObject(ref traits, _) = t.node;
349         if traits.len() >= 1;
350         // Only Send/Sync can be used as additional traits, so it is enough to
351         // check only the first trait.
352         if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
353         then {
354             return true;
355         }
356     }
357
358     false
359 }
360
361 #[allow(missing_copy_implementations)]
362 pub struct LetPass;
363
364 /// **What it does:** Checks for binding a unit value.
365 ///
366 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
367 /// binding one is kind of pointless.
368 ///
369 /// **Known problems:** None.
370 ///
371 /// **Example:**
372 /// ```rust
373 /// let x = { 1; };
374 /// ```
375 declare_clippy_lint! {
376     pub LET_UNIT_VALUE,
377     style,
378     "creating a let binding to a value of unit type, which usually can't be used afterwards"
379 }
380
381 fn check_let_unit(cx: &LateContext, decl: &Decl) {
382     if let DeclKind::Local(ref local) = decl.node {
383         if is_unit(cx.tables.pat_ty(&local.pat)) {
384             if in_external_macro(cx, decl.span) || in_macro(local.pat.span) {
385                 return;
386             }
387             if higher::is_from_for_desugar(decl) {
388                 return;
389             }
390             span_lint(
391                 cx,
392                 LET_UNIT_VALUE,
393                 decl.span,
394                 &format!(
395                     "this let-binding has unit value. Consider omitting `let {} =`",
396                     snippet(cx, local.pat.span, "..")
397                 ),
398             );
399         }
400     }
401 }
402
403 impl LintPass for LetPass {
404     fn get_lints(&self) -> LintArray {
405         lint_array!(LET_UNIT_VALUE)
406     }
407 }
408
409 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetPass {
410     fn check_decl(&mut self, cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl) {
411         check_let_unit(cx, decl)
412     }
413 }
414
415 /// **What it does:** Checks for comparisons to unit.
416 ///
417 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
418 /// clumsily written constant. Mostly this happens when someone accidentally
419 /// adds semicolons at the end of the operands.
420 ///
421 /// **Known problems:** None.
422 ///
423 /// **Example:**
424 /// ```rust
425 /// if { foo(); } == { bar(); } { baz(); }
426 /// ```
427 /// is equal to
428 /// ```rust
429 /// { foo(); bar(); baz(); }
430 /// ```
431 declare_clippy_lint! {
432     pub UNIT_CMP,
433     correctness,
434     "comparing unit values"
435 }
436
437 #[allow(missing_copy_implementations)]
438 pub struct UnitCmp;
439
440 impl LintPass for UnitCmp {
441     fn get_lints(&self) -> LintArray {
442         lint_array!(UNIT_CMP)
443     }
444 }
445
446 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
447     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
448         if in_macro(expr.span) {
449             return;
450         }
451         if let ExprKind::Binary(ref cmp, ref left, _) = expr.node {
452             let op = cmp.node;
453             if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
454                 let result = match op {
455                     BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
456                     _ => "false",
457                 };
458                 span_lint(
459                     cx,
460                     UNIT_CMP,
461                     expr.span,
462                     &format!(
463                         "{}-comparison of unit values detected. This will always be {}",
464                         op.as_str(),
465                         result
466                     ),
467                 );
468             }
469         }
470     }
471 }
472
473 /// **What it does:** Checks for passing a unit value as an argument to a function without using a unit literal (`()`).
474 ///
475 /// **Why is this bad?** This is likely the result of an accidental semicolon.
476 ///
477 /// **Known problems:** None.
478 ///
479 /// **Example:**
480 /// ```rust
481 /// foo({
482 ///   let a = bar();
483 ///   baz(a);
484 /// })
485 /// ```
486 declare_clippy_lint! {
487     pub UNIT_ARG,
488     complexity,
489     "passing unit to a function"
490 }
491
492 pub struct UnitArg;
493
494 impl LintPass for UnitArg {
495     fn get_lints(&self) -> LintArray {
496         lint_array!(UNIT_ARG)
497     }
498 }
499
500 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
501     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
502         if in_macro(expr.span) {
503             return;
504         }
505         match expr.node {
506             ExprKind::Call(_, ref args) | ExprKind::MethodCall(_, _, ref args) => {
507                 for arg in args {
508                     if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
509                         let map = &cx.tcx.hir;
510                         // apparently stuff in the desugaring of `?` can trigger this
511                         // so check for that here
512                         // only the calls to `Try::from_error` is marked as desugared,
513                         // so we need to check both the current Expr and its parent.
514                         if !is_questionmark_desugar_marked_call(expr) {
515                             if_chain!{
516                                 let opt_parent_node = map.find(map.get_parent_node(expr.id));
517                                 if let Some(hir::map::NodeExpr(parent_expr)) = opt_parent_node;
518                                 if is_questionmark_desugar_marked_call(parent_expr);
519                                 then {}
520                                 else {
521                                     // `expr` and `parent_expr` where _both_ not from
522                                     // desugaring `?`, so lint
523                                     span_lint_and_sugg(
524                                         cx,
525                                         UNIT_ARG,
526                                         arg.span,
527                                         "passing a unit value to a function",
528                                         "if you intended to pass a unit value, use a unit literal instead",
529                                         "()".to_string(),
530                                     );
531                                 }
532                             }
533                         }
534                     }
535                 }
536             },
537             _ => (),
538         }
539     }
540 }
541
542 fn is_questionmark_desugar_marked_call(expr: &Expr) -> bool {
543     use syntax_pos::hygiene::CompilerDesugaringKind;
544     if let ExprKind::Call(ref callee, _) = expr.node {
545         callee.span.is_compiler_desugaring(CompilerDesugaringKind::QuestionMark)
546     } else {
547         false
548     }
549 }
550
551 fn is_unit(ty: Ty) -> bool {
552     match ty.sty {
553         ty::TyTuple(slice) if slice.is_empty() => true,
554         _ => false,
555     }
556 }
557
558 fn is_unit_literal(expr: &Expr) -> bool {
559     match expr.node {
560         ExprKind::Tup(ref slice) if slice.is_empty() => true,
561         _ => false,
562     }
563 }
564
565 pub struct CastPass;
566
567 /// **What it does:** Checks for casts from any numerical to a float type where
568 /// the receiving type cannot store all values from the original type without
569 /// rounding errors. This possible rounding is to be expected, so this lint is
570 /// `Allow` by default.
571 ///
572 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
573 /// or any 64-bit integer to `f64`.
574 ///
575 /// **Why is this bad?** It's not bad at all. But in some applications it can be
576 /// helpful to know where precision loss can take place. This lint can help find
577 /// those places in the code.
578 ///
579 /// **Known problems:** None.
580 ///
581 /// **Example:**
582 /// ```rust
583 /// let x = u64::MAX; x as f64
584 /// ```
585 declare_clippy_lint! {
586     pub CAST_PRECISION_LOSS,
587     pedantic,
588     "casts that cause loss of precision, e.g. `x as f32` where `x: u64`"
589 }
590
591 /// **What it does:** Checks for casts from a signed to an unsigned numerical
592 /// type. In this case, negative values wrap around to large positive values,
593 /// which can be quite surprising in practice. However, as the cast works as
594 /// defined, this lint is `Allow` by default.
595 ///
596 /// **Why is this bad?** Possibly surprising results. You can activate this lint
597 /// as a one-time check to see where numerical wrapping can arise.
598 ///
599 /// **Known problems:** None.
600 ///
601 /// **Example:**
602 /// ```rust
603 /// let y: i8 = -1;
604 /// y as u128  // will return 18446744073709551615
605 /// ```
606 declare_clippy_lint! {
607     pub CAST_SIGN_LOSS,
608     pedantic,
609     "casts from signed types to unsigned types, e.g. `x as u32` where `x: i32`"
610 }
611
612 /// **What it does:** Checks for on casts between numerical types that may
613 /// truncate large values. This is expected behavior, so the cast is `Allow` by
614 /// default.
615 ///
616 /// **Why is this bad?** In some problem domains, it is good practice to avoid
617 /// truncation. This lint can be activated to help assess where additional
618 /// checks could be beneficial.
619 ///
620 /// **Known problems:** None.
621 ///
622 /// **Example:**
623 /// ```rust
624 /// fn as_u8(x: u64) -> u8 { x as u8 }
625 /// ```
626 declare_clippy_lint! {
627     pub CAST_POSSIBLE_TRUNCATION,
628     pedantic,
629     "casts that may cause truncation of the value, e.g. `x as u8` where `x: u32`, \
630      or `x as i32` where `x: f32`"
631 }
632
633 /// **What it does:** Checks for casts from an unsigned type to a signed type of
634 /// the same size. Performing such a cast is a 'no-op' for the compiler,
635 /// i.e. nothing is changed at the bit level, and the binary representation of
636 /// the value is reinterpreted. This can cause wrapping if the value is too big
637 /// for the target signed type. However, the cast works as defined, so this lint
638 /// is `Allow` by default.
639 ///
640 /// **Why is this bad?** While such a cast is not bad in itself, the results can
641 /// be surprising when this is not the intended behavior, as demonstrated by the
642 /// example below.
643 ///
644 /// **Known problems:** None.
645 ///
646 /// **Example:**
647 /// ```rust
648 /// u32::MAX as i32  // will yield a value of `-1`
649 /// ```
650 declare_clippy_lint! {
651     pub CAST_POSSIBLE_WRAP,
652     pedantic,
653     "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` \
654      and `x > i32::MAX`"
655 }
656
657 /// **What it does:** Checks for on casts between numerical types that may
658 /// be replaced by safe conversion functions.
659 ///
660 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
661 /// conversions, including silently lossy conversions. Conversion functions such
662 /// as `i32::from` will only perform lossless conversions. Using the conversion
663 /// functions prevents conversions from turning into silent lossy conversions if
664 /// the types of the input expressions ever change, and make it easier for
665 /// people reading the code to know that the conversion is lossless.
666 ///
667 /// **Known problems:** None.
668 ///
669 /// **Example:**
670 /// ```rust
671 /// fn as_u64(x: u8) -> u64 { x as u64 }
672 /// ```
673 ///
674 /// Using `::from` would look like this:
675 ///
676 /// ```rust
677 /// fn as_u64(x: u8) -> u64 { u64::from(x) }
678 /// ```
679 declare_clippy_lint! {
680     pub CAST_LOSSLESS,
681     complexity,
682     "casts using `as` that are known to be lossless, e.g. `x as u64` where `x: u8`"
683 }
684
685 /// **What it does:** Checks for casts to the same type.
686 ///
687 /// **Why is this bad?** It's just unnecessary.
688 ///
689 /// **Known problems:** None.
690 ///
691 /// **Example:**
692 /// ```rust
693 /// let _ = 2i32 as i32
694 /// ```
695 declare_clippy_lint! {
696     pub UNNECESSARY_CAST,
697     complexity,
698     "cast to the same type, e.g. `x as i32` where `x: i32`"
699 }
700
701 /// **What it does:** Checks for casts of a function pointer to a numeric type not enough to store address.
702 ///
703 /// **Why is this bad?** Casting a function pointer to not eligable type could truncate the address value.
704 ///
705 /// **Known problems:** None.
706 ///
707 /// **Example:**
708 /// ```rust
709 /// fn test_fn() -> i16;
710 /// let _ = test_fn as i32
711 /// ```
712 declare_clippy_lint! {
713     pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
714     correctness,
715     "cast function pointer to the numeric type with value truncation"
716 }
717
718 /// **What it does:** Checks for casts of a function pointer to a numeric type except `usize`.
719 ///
720 /// **Why is this bad?** Casting a function pointer to something other than `usize` is not a good style.
721 ///
722 /// **Known problems:** None.
723 ///
724 /// **Example:**
725 /// ```rust
726 /// fn test_fn() -> i16;
727 /// let _ = test_fn as i128
728 /// ```
729 declare_clippy_lint! {
730     pub FN_TO_NUMERIC_CAST,
731     style,
732     "cast function pointer to the numeric type"
733 }
734
735 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
736 /// more-strictly-aligned pointer
737 ///
738 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
739 /// behavior.
740 ///
741 /// **Known problems:** None.
742 ///
743 /// **Example:**
744 /// ```rust
745 /// let _ = (&1u8 as *const u8) as *const u16;
746 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
747 /// ```
748 declare_clippy_lint! {
749     pub CAST_PTR_ALIGNMENT,
750     correctness,
751     "cast from a pointer to a more-strictly-aligned pointer"
752 }
753
754 /// Returns the size in bits of an integral type.
755 /// Will return 0 if the type is not an int or uint variant
756 fn int_ty_to_nbits(typ: Ty, tcx: TyCtxt) -> u64 {
757     match typ.sty {
758         ty::TyInt(i) => match i {
759             IntTy::Isize => tcx.data_layout.pointer_size.bits(),
760             IntTy::I8 => 8,
761             IntTy::I16 => 16,
762             IntTy::I32 => 32,
763             IntTy::I64 => 64,
764             IntTy::I128 => 128,
765         },
766         ty::TyUint(i) => match i {
767             UintTy::Usize => tcx.data_layout.pointer_size.bits(),
768             UintTy::U8 => 8,
769             UintTy::U16 => 16,
770             UintTy::U32 => 32,
771             UintTy::U64 => 64,
772             UintTy::U128 => 128,
773         },
774         _ => 0,
775     }
776 }
777
778 fn is_isize_or_usize(typ: Ty) -> bool {
779     match typ.sty {
780         ty::TyInt(IntTy::Isize) | ty::TyUint(UintTy::Usize) => true,
781         _ => false,
782     }
783 }
784
785 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to_f64: bool) {
786     let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
787     let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
788     let arch_dependent_str = "on targets with 64-bit wide pointers ";
789     let from_nbits_str = if arch_dependent {
790         "64".to_owned()
791     } else if is_isize_or_usize(cast_from) {
792         "32 or 64".to_owned()
793     } else {
794         int_ty_to_nbits(cast_from, cx.tcx).to_string()
795     };
796     span_lint(
797         cx,
798         CAST_PRECISION_LOSS,
799         expr.span,
800         &format!(
801             "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
802              is only {4} bits wide)",
803             cast_from,
804             if cast_to_f64 { "f64" } else { "f32" },
805             if arch_dependent {
806                 arch_dependent_str
807             } else {
808                 ""
809             },
810             from_nbits_str,
811             mantissa_nbits
812         ),
813     );
814 }
815
816 fn should_strip_parens(op: &Expr, snip: &str) -> bool {
817     if let ExprKind::Binary(_, _, _) = op.node {
818         if snip.starts_with('(') && snip.ends_with(')') {
819             return true;
820         }
821     }
822     false
823 }
824
825 fn span_lossless_lint(cx: &LateContext, expr: &Expr, op: &Expr, cast_from: Ty, cast_to: Ty) {
826     // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
827     if in_constant(cx, expr.id) { return }
828     // The suggestion is to use a function call, so if the original expression
829     // has parens on the outside, they are no longer needed.
830     let opt = snippet_opt(cx, op.span);
831     let sugg = if let Some(ref snip) = opt {
832         if should_strip_parens(op, snip) {
833             &snip[1..snip.len() - 1]
834         } else {
835             snip.as_str()
836         }
837     } else {
838         ".."
839     };
840
841     span_lint_and_sugg(
842         cx,
843         CAST_LOSSLESS,
844         expr.span,
845         &format!("casting {} to {} may become silently lossy if types change", cast_from, cast_to),
846         "try",
847         format!("{}::from({})", cast_to, sugg),
848     );
849 }
850
851 enum ArchSuffix {
852     _32,
853     _64,
854     None,
855 }
856
857 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to: Ty) {
858     let arch_64_suffix = " on targets with 64-bit wide pointers";
859     let arch_32_suffix = " on targets with 32-bit wide pointers";
860     let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
861     let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
862     let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
863     let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
864         match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
865             (true, true) | (false, false) => (
866                 to_nbits < from_nbits,
867                 ArchSuffix::None,
868                 to_nbits == from_nbits && cast_unsigned_to_signed,
869                 ArchSuffix::None,
870             ),
871             (true, false) => (
872                 to_nbits <= 32,
873                 if to_nbits == 32 {
874                     ArchSuffix::_64
875                 } else {
876                     ArchSuffix::None
877                 },
878                 to_nbits <= 32 && cast_unsigned_to_signed,
879                 ArchSuffix::_32,
880             ),
881             (false, true) => (
882                 from_nbits == 64,
883                 ArchSuffix::_32,
884                 cast_unsigned_to_signed,
885                 if from_nbits == 64 {
886                     ArchSuffix::_64
887                 } else {
888                     ArchSuffix::_32
889                 },
890             ),
891         };
892     if span_truncation {
893         span_lint(
894             cx,
895             CAST_POSSIBLE_TRUNCATION,
896             expr.span,
897             &format!(
898                 "casting {} to {} may truncate the value{}",
899                 cast_from,
900                 cast_to,
901                 match suffix_truncation {
902                     ArchSuffix::_32 => arch_32_suffix,
903                     ArchSuffix::_64 => arch_64_suffix,
904                     ArchSuffix::None => "",
905                 }
906             ),
907         );
908     }
909     if span_wrap {
910         span_lint(
911             cx,
912             CAST_POSSIBLE_WRAP,
913             expr.span,
914             &format!(
915                 "casting {} to {} may wrap around the value{}",
916                 cast_from,
917                 cast_to,
918                 match suffix_wrap {
919                     ArchSuffix::_32 => arch_32_suffix,
920                     ArchSuffix::_64 => arch_64_suffix,
921                     ArchSuffix::None => "",
922                 }
923             ),
924         );
925     }
926 }
927
928 fn check_lossless(cx: &LateContext, expr: &Expr, op: &Expr, cast_from: Ty, cast_to: Ty) {
929     let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
930     let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
931     let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
932     if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
933     {
934         span_lossless_lint(cx, expr, op, cast_from, cast_to);
935     }
936 }
937
938 impl LintPass for CastPass {
939     fn get_lints(&self) -> LintArray {
940         lint_array!(
941             CAST_PRECISION_LOSS,
942             CAST_SIGN_LOSS,
943             CAST_POSSIBLE_TRUNCATION,
944             CAST_POSSIBLE_WRAP,
945             CAST_LOSSLESS,
946             UNNECESSARY_CAST,
947             CAST_PTR_ALIGNMENT,
948             FN_TO_NUMERIC_CAST,
949             FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
950         )
951     }
952 }
953
954 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
955     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
956         if let ExprKind::Cast(ref ex, _) = expr.node {
957             let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
958             if let ExprKind::Lit(ref lit) = ex.node {
959                 use syntax::ast::{LitIntType, LitKind};
960                 match lit.node {
961                     LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
962                     _ => if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
963                         span_lint(
964                             cx,
965                             UNNECESSARY_CAST,
966                             expr.span,
967                             &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
968                         );
969                     },
970                 }
971             }
972             if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
973                 match (cast_from.is_integral(), cast_to.is_integral()) {
974                     (true, false) => {
975                         let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
976                         let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
977                             32
978                         } else {
979                             64
980                         };
981                         if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
982                             span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
983                         }
984                         if from_nbits < to_nbits {
985                             span_lossless_lint(cx, expr, ex, cast_from, cast_to);
986                         }
987                     },
988                     (false, true) => {
989                         span_lint(
990                             cx,
991                             CAST_POSSIBLE_TRUNCATION,
992                             expr.span,
993                             &format!("casting {} to {} may truncate the value", cast_from, cast_to),
994                         );
995                         if !cast_to.is_signed() {
996                             span_lint(
997                                 cx,
998                                 CAST_SIGN_LOSS,
999                                 expr.span,
1000                                 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1001                             );
1002                         }
1003                     },
1004                     (true, true) => {
1005                         if cast_from.is_signed() && !cast_to.is_signed() {
1006                             span_lint(
1007                                 cx,
1008                                 CAST_SIGN_LOSS,
1009                                 expr.span,
1010                                 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1011                             );
1012                         }
1013                         check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1014                         check_lossless(cx, expr, ex, cast_from, cast_to);
1015                     },
1016                     (false, false) => {
1017                         if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty)
1018                         {
1019                             span_lint(
1020                                 cx,
1021                                 CAST_POSSIBLE_TRUNCATION,
1022                                 expr.span,
1023                                 "casting f64 to f32 may truncate the value",
1024                             );
1025                         }
1026                         if let (&ty::TyFloat(FloatTy::F32), &ty::TyFloat(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty)
1027                         {
1028                             span_lossless_lint(cx, expr, ex, cast_from, cast_to);
1029                         }
1030                     },
1031                 }
1032             }
1033
1034             match &cast_from.sty {
1035                 ty::TyFnDef(..) |
1036                 ty::TyFnPtr(..) => {
1037                     if cast_to.is_numeric() && cast_to.sty != ty::TyUint(UintTy::Usize){
1038                         let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1039                         let pointer_nbits = cx.tcx.data_layout.pointer_size.bits();
1040                         if to_nbits < pointer_nbits || (to_nbits == pointer_nbits && cast_to.is_signed()) {
1041                             span_lint_and_sugg(
1042                                 cx,
1043                                 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1044                                 expr.span,
1045                                 &format!("casting a `{}` to `{}` may truncate the function address value.", cast_from, cast_to),
1046                                 "if you need the address of the function, consider",
1047                                 format!("{} as usize", &snippet(cx, ex.span, "x"))
1048                             );
1049                         } else {
1050                             span_lint_and_sugg(
1051                                 cx,
1052                                 FN_TO_NUMERIC_CAST,
1053                                 expr.span,
1054                                 &format!("casting a `{}` to `{}` is bad style.", cast_from, cast_to),
1055                                 "if you need the address of the function, consider",
1056                                 format!("{} as usize", &snippet(cx, ex.span, "x"))
1057                             );
1058
1059                         };
1060                     }
1061                 }
1062                 _ => ()
1063             }
1064
1065             if_chain!{
1066                 if let ty::TyRawPtr(from_ptr_ty) = &cast_from.sty;
1067                 if let ty::TyRawPtr(to_ptr_ty) = &cast_to.sty;
1068                 if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi());
1069                 if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi());
1070                 if from_align < to_align;
1071                 // with c_void, we inherently need to trust the user
1072                 if ! (
1073                     match_type(cx, from_ptr_ty.ty, &paths::C_VOID)
1074                     || match_type(cx, from_ptr_ty.ty, &paths::C_VOID_LIBC)
1075                 );
1076                 then {
1077                     span_lint(
1078                         cx,
1079                         CAST_PTR_ALIGNMENT,
1080                         expr.span,
1081                         &format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
1082                     );
1083                 }
1084             }
1085         }
1086     }
1087 }
1088
1089 /// **What it does:** Checks for types used in structs, parameters and `let`
1090 /// declarations above a certain complexity threshold.
1091 ///
1092 /// **Why is this bad?** Too complex types make the code less readable. Consider
1093 /// using a `type` definition to simplify them.
1094 ///
1095 /// **Known problems:** None.
1096 ///
1097 /// **Example:**
1098 /// ```rust
1099 /// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
1100 /// ```
1101 declare_clippy_lint! {
1102     pub TYPE_COMPLEXITY,
1103     complexity,
1104     "usage of very complex types that might be better factored into `type` definitions"
1105 }
1106
1107 #[allow(missing_copy_implementations)]
1108 pub struct TypeComplexityPass {
1109     threshold: u64,
1110 }
1111
1112 impl TypeComplexityPass {
1113     pub fn new(threshold: u64) -> Self {
1114         Self {
1115             threshold,
1116         }
1117     }
1118 }
1119
1120 impl LintPass for TypeComplexityPass {
1121     fn get_lints(&self) -> LintArray {
1122         lint_array!(TYPE_COMPLEXITY)
1123     }
1124 }
1125
1126 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
1127     fn check_fn(
1128         &mut self,
1129         cx: &LateContext<'a, 'tcx>,
1130         _: FnKind<'tcx>,
1131         decl: &'tcx FnDecl,
1132         _: &'tcx Body,
1133         _: Span,
1134         _: NodeId,
1135     ) {
1136         self.check_fndecl(cx, decl);
1137     }
1138
1139     fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx StructField) {
1140         // enum variants are also struct fields now
1141         self.check_type(cx, &field.ty);
1142     }
1143
1144     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1145         match item.node {
1146             ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1147             // functions, enums, structs, impls and traits are covered
1148             _ => (),
1149         }
1150     }
1151
1152     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
1153         match item.node {
1154             TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1155             TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
1156             // methods with default impl are covered by check_fn
1157             _ => (),
1158         }
1159     }
1160
1161     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
1162         match item.node {
1163             ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
1164             // methods are covered by check_fn
1165             _ => (),
1166         }
1167     }
1168
1169     fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
1170         if let Some(ref ty) = local.ty {
1171             self.check_type(cx, ty);
1172         }
1173     }
1174 }
1175
1176 impl<'a, 'tcx> TypeComplexityPass {
1177     fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
1178         for arg in &decl.inputs {
1179             self.check_type(cx, arg);
1180         }
1181         if let Return(ref ty) = decl.output {
1182             self.check_type(cx, ty);
1183         }
1184     }
1185
1186     fn check_type(&self, cx: &LateContext, ty: &hir::Ty) {
1187         if in_macro(ty.span) {
1188             return;
1189         }
1190         let score = {
1191             let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1192             visitor.visit_ty(ty);
1193             visitor.score
1194         };
1195
1196         if score > self.threshold {
1197             span_lint(
1198                 cx,
1199                 TYPE_COMPLEXITY,
1200                 ty.span,
1201                 "very complex type used. Consider factoring parts into `type` definitions",
1202             );
1203         }
1204     }
1205 }
1206
1207 /// Walks a type and assigns a complexity score to it.
1208 struct TypeComplexityVisitor {
1209     /// total complexity score of the type
1210     score: u64,
1211     /// current nesting level
1212     nest: u64,
1213 }
1214
1215 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1216     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1217         let (add_score, sub_nest) = match ty.node {
1218             // _, &x and *x have only small overhead; don't mess with nesting level
1219             TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1220
1221             // the "normal" components of a type: named types, arrays/tuples
1222             TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1223
1224             // function types bring a lot of overhead
1225             TyKind::BareFn(..) => (50 * self.nest, 1),
1226
1227             TyKind::TraitObject(ref param_bounds, _) => {
1228                 let has_lifetime_parameters = param_bounds
1229                     .iter()
1230                     .any(|bound| bound.bound_generic_params.iter().any(|gen| match gen.kind {
1231                         GenericParamKind::Lifetime { .. } => true,
1232                         _ => false,
1233                     }));
1234                 if has_lifetime_parameters {
1235                     // complex trait bounds like A<'a, 'b>
1236                     (50 * self.nest, 1)
1237                 } else {
1238                     // simple trait bounds like A + B
1239                     (20 * self.nest, 0)
1240                 }
1241             },
1242
1243             _ => (0, 0),
1244         };
1245         self.score += add_score;
1246         self.nest += sub_nest;
1247         walk_ty(self, ty);
1248         self.nest -= sub_nest;
1249     }
1250     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1251         NestedVisitorMap::None
1252     }
1253 }
1254
1255 /// **What it does:** Checks for expressions where a character literal is cast
1256 /// to `u8` and suggests using a byte literal instead.
1257 ///
1258 /// **Why is this bad?** In general, casting values to smaller types is
1259 /// error-prone and should be avoided where possible. In the particular case of
1260 /// converting a character literal to u8, it is easy to avoid by just using a
1261 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1262 /// than `'a' as u8`.
1263 ///
1264 /// **Known problems:** None.
1265 ///
1266 /// **Example:**
1267 /// ```rust
1268 /// 'x' as u8
1269 /// ```
1270 ///
1271 /// A better version, using the byte literal:
1272 ///
1273 /// ```rust
1274 /// b'x'
1275 /// ```
1276 declare_clippy_lint! {
1277     pub CHAR_LIT_AS_U8,
1278     complexity,
1279     "casting a character literal to u8"
1280 }
1281
1282 pub struct CharLitAsU8;
1283
1284 impl LintPass for CharLitAsU8 {
1285     fn get_lints(&self) -> LintArray {
1286         lint_array!(CHAR_LIT_AS_U8)
1287     }
1288 }
1289
1290 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1291     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1292         use syntax::ast::{LitKind, UintTy};
1293
1294         if let ExprKind::Cast(ref e, _) = expr.node {
1295             if let ExprKind::Lit(ref l) = e.node {
1296                 if let LitKind::Char(_) = l.node {
1297                     if ty::TyUint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
1298                         let msg = "casting character literal to u8. `char`s \
1299                                    are 4 bytes wide in rust, so casting to u8 \
1300                                    truncates them";
1301                         let help = format!("Consider using a byte literal instead:\nb{}", snippet(cx, e.span, "'x'"));
1302                         span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
1303                     }
1304                 }
1305             }
1306         }
1307     }
1308 }
1309
1310 /// **What it does:** Checks for comparisons where one side of the relation is
1311 /// either the minimum or maximum value for its type and warns if it involves a
1312 /// case that is always true or always false. Only integer and boolean types are
1313 /// checked.
1314 ///
1315 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1316 /// that is is possible for `x` to be less than the minimum. Expressions like
1317 /// `max < x` are probably mistakes.
1318 ///
1319 /// **Known problems:** For `usize` the size of the current compile target will
1320 /// be assumed (e.g. 64 bits on 64 bit systems). This means code that uses such
1321 /// a comparison to detect target pointer width will trigger this lint. One can
1322 /// use `mem::sizeof` and compare its value or conditional compilation
1323 /// attributes
1324 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1325 ///
1326 /// **Example:**
1327 /// ```rust
1328 /// vec.len() <= 0
1329 /// 100 > std::i32::MAX
1330 /// ```
1331 declare_clippy_lint! {
1332     pub ABSURD_EXTREME_COMPARISONS,
1333     correctness,
1334     "a comparison with a maximum or minimum value that is always true or false"
1335 }
1336
1337 pub struct AbsurdExtremeComparisons;
1338
1339 impl LintPass for AbsurdExtremeComparisons {
1340     fn get_lints(&self) -> LintArray {
1341         lint_array!(ABSURD_EXTREME_COMPARISONS)
1342     }
1343 }
1344
1345 enum ExtremeType {
1346     Minimum,
1347     Maximum,
1348 }
1349
1350 struct ExtremeExpr<'a> {
1351     which: ExtremeType,
1352     expr: &'a Expr,
1353 }
1354
1355 enum AbsurdComparisonResult {
1356     AlwaysFalse,
1357     AlwaysTrue,
1358     InequalityImpossible,
1359 }
1360
1361
1362 fn is_cast_between_fixed_and_target<'a, 'tcx>(
1363     cx: &LateContext<'a, 'tcx>,
1364     expr: &'tcx Expr
1365 ) -> bool {
1366
1367     if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1368         let precast_ty = cx.tables.expr_ty(cast_exp);
1369         let cast_ty = cx.tables.expr_ty(expr);
1370
1371         return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty)
1372     }
1373
1374     false
1375 }
1376
1377 fn detect_absurd_comparison<'a, 'tcx>(
1378     cx: &LateContext<'a, 'tcx>,
1379     op: BinOpKind,
1380     lhs: &'tcx Expr,
1381     rhs: &'tcx Expr,
1382 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1383     use crate::types::ExtremeType::*;
1384     use crate::types::AbsurdComparisonResult::*;
1385     use crate::utils::comparisons::*;
1386
1387     // absurd comparison only makes sense on primitive types
1388     // primitive types don't implement comparison operators with each other
1389     if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1390         return None;
1391     }
1392
1393     // comparisons between fix sized types and target sized types are considered unanalyzable
1394     if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1395         return None;
1396     }
1397
1398     let normalized = normalize_comparison(op, lhs, rhs);
1399     let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1400         val
1401     } else {
1402         return None;
1403     };
1404
1405     let lx = detect_extreme_expr(cx, normalized_lhs);
1406     let rx = detect_extreme_expr(cx, normalized_rhs);
1407
1408     Some(match rel {
1409         Rel::Lt => {
1410             match (lx, rx) {
1411                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1412                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1413                 _ => return None,
1414             }
1415         },
1416         Rel::Le => {
1417             match (lx, rx) {
1418                 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1419                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1420                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1421                 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1422                 _ => return None,
1423             }
1424         },
1425         Rel::Ne | Rel::Eq => return None,
1426     })
1427 }
1428
1429 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<ExtremeExpr<'tcx>> {
1430     use crate::types::ExtremeType::*;
1431
1432     let ty = cx.tables.expr_ty(expr);
1433
1434     let cv = constant(cx, cx.tables, expr)?.0;
1435
1436     let which = match (&ty.sty, cv) {
1437         (&ty::TyBool, Constant::Bool(false)) |
1438         (&ty::TyUint(_), Constant::Int(0)) => Minimum,
1439         (&ty::TyInt(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) => Minimum,
1440
1441         (&ty::TyBool, Constant::Bool(true)) => Maximum,
1442         (&ty::TyInt(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) => Maximum,
1443         (&ty::TyUint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1444
1445         _ => return None,
1446     };
1447     Some(ExtremeExpr {
1448         which,
1449         expr,
1450     })
1451 }
1452
1453 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1454     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1455         use crate::types::ExtremeType::*;
1456         use crate::types::AbsurdComparisonResult::*;
1457
1458         if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1459             if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1460                 if !in_macro(expr.span) {
1461                     let msg = "this comparison involving the minimum or maximum element for this \
1462                                type contains a case that is always true or always false";
1463
1464                     let conclusion = match result {
1465                         AlwaysFalse => "this comparison is always false".to_owned(),
1466                         AlwaysTrue => "this comparison is always true".to_owned(),
1467                         InequalityImpossible => format!(
1468                             "the case where the two sides are not equal never occurs, consider using {} == {} \
1469                              instead",
1470                             snippet(cx, lhs.span, "lhs"),
1471                             snippet(cx, rhs.span, "rhs")
1472                         ),
1473                     };
1474
1475                     let help = format!(
1476                         "because {} is the {} value for this type, {}",
1477                         snippet(cx, culprit.expr.span, "x"),
1478                         match culprit.which {
1479                             Minimum => "minimum",
1480                             Maximum => "maximum",
1481                         },
1482                         conclusion
1483                     );
1484
1485                     span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1486                 }
1487             }
1488         }
1489     }
1490 }
1491
1492 /// **What it does:** Checks for comparisons where the relation is always either
1493 /// true or false, but where one side has been upcast so that the comparison is
1494 /// necessary. Only integer types are checked.
1495 ///
1496 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1497 /// will mistakenly imply that it is possible for `x` to be outside the range of
1498 /// `u8`.
1499 ///
1500 /// **Known problems:**
1501 /// https://github.com/rust-lang-nursery/rust-clippy/issues/886
1502 ///
1503 /// **Example:**
1504 /// ```rust
1505 /// let x : u8 = ...; (x as u32) > 300
1506 /// ```
1507 declare_clippy_lint! {
1508     pub INVALID_UPCAST_COMPARISONS,
1509     pedantic,
1510     "a comparison involving an upcast which is always true or false"
1511 }
1512
1513 pub struct InvalidUpcastComparisons;
1514
1515 impl LintPass for InvalidUpcastComparisons {
1516     fn get_lints(&self) -> LintArray {
1517         lint_array!(INVALID_UPCAST_COMPARISONS)
1518     }
1519 }
1520
1521 #[derive(Copy, Clone, Debug, Eq)]
1522 enum FullInt {
1523     S(i128),
1524     U(u128),
1525 }
1526
1527 impl FullInt {
1528     #[allow(cast_sign_loss)]
1529     fn cmp_s_u(s: i128, u: u128) -> Ordering {
1530         if s < 0 {
1531             Ordering::Less
1532         } else if u > (i128::max_value() as u128) {
1533             Ordering::Greater
1534         } else {
1535             (s as u128).cmp(&u)
1536         }
1537     }
1538 }
1539
1540 impl PartialEq for FullInt {
1541     fn eq(&self, other: &Self) -> bool {
1542         self.partial_cmp(other)
1543             .expect("partial_cmp only returns Some(_)") == Ordering::Equal
1544     }
1545 }
1546
1547 impl PartialOrd for FullInt {
1548     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1549         Some(match (self, other) {
1550             (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1551             (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1552             (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1553             (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1554         })
1555     }
1556 }
1557 impl Ord for FullInt {
1558     fn cmp(&self, other: &Self) -> Ordering {
1559         self.partial_cmp(other)
1560             .expect("partial_cmp for FullInt can never return None")
1561     }
1562 }
1563
1564
1565 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1566     use syntax::ast::{IntTy, UintTy};
1567     use std::*;
1568
1569     if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1570         let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1571         let cast_ty = cx.tables.expr_ty(expr);
1572         // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1573         if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1574             return None;
1575         }
1576         match pre_cast_ty.sty {
1577             ty::TyInt(int_ty) => Some(match int_ty {
1578                 IntTy::I8 => (FullInt::S(i128::from(i8::min_value())), FullInt::S(i128::from(i8::max_value()))),
1579                 IntTy::I16 => (
1580                     FullInt::S(i128::from(i16::min_value())),
1581                     FullInt::S(i128::from(i16::max_value())),
1582                 ),
1583                 IntTy::I32 => (
1584                     FullInt::S(i128::from(i32::min_value())),
1585                     FullInt::S(i128::from(i32::max_value())),
1586                 ),
1587                 IntTy::I64 => (
1588                     FullInt::S(i128::from(i64::min_value())),
1589                     FullInt::S(i128::from(i64::max_value())),
1590                 ),
1591                 IntTy::I128 => (FullInt::S(i128::min_value() as i128), FullInt::S(i128::max_value() as i128)),
1592                 IntTy::Isize => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)),
1593             }),
1594             ty::TyUint(uint_ty) => Some(match uint_ty {
1595                 UintTy::U8 => (FullInt::U(u128::from(u8::min_value())), FullInt::U(u128::from(u8::max_value()))),
1596                 UintTy::U16 => (
1597                     FullInt::U(u128::from(u16::min_value())),
1598                     FullInt::U(u128::from(u16::max_value())),
1599                 ),
1600                 UintTy::U32 => (
1601                     FullInt::U(u128::from(u32::min_value())),
1602                     FullInt::U(u128::from(u32::max_value())),
1603                 ),
1604                 UintTy::U64 => (
1605                     FullInt::U(u128::from(u64::min_value())),
1606                     FullInt::U(u128::from(u64::max_value())),
1607                 ),
1608                 UintTy::U128 => (FullInt::U(u128::min_value() as u128), FullInt::U(u128::max_value() as u128)),
1609                 UintTy::Usize => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
1610             }),
1611             _ => None,
1612         }
1613     } else {
1614         None
1615     }
1616 }
1617
1618 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<FullInt> {
1619     let val = constant(cx, cx.tables, expr)?.0;
1620     if let Constant::Int(const_int) = val {
1621         match cx.tables.expr_ty(expr).sty {
1622             ty::TyInt(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
1623             ty::TyUint(_) => Some(FullInt::U(const_int)),
1624             _ => None,
1625         }
1626     } else {
1627         None
1628     }
1629 }
1630
1631 fn err_upcast_comparison(cx: &LateContext, span: Span, expr: &Expr, always: bool) {
1632     if let ExprKind::Cast(ref cast_val, _) = expr.node {
1633         span_lint(
1634             cx,
1635             INVALID_UPCAST_COMPARISONS,
1636             span,
1637             &format!(
1638                 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1639                 snippet(cx, cast_val.span, "the expression"),
1640                 if always { "true" } else { "false" },
1641             ),
1642         );
1643     }
1644 }
1645
1646 fn upcast_comparison_bounds_err<'a, 'tcx>(
1647     cx: &LateContext<'a, 'tcx>,
1648     span: Span,
1649     rel: comparisons::Rel,
1650     lhs_bounds: Option<(FullInt, FullInt)>,
1651     lhs: &'tcx Expr,
1652     rhs: &'tcx Expr,
1653     invert: bool,
1654 ) {
1655     use crate::utils::comparisons::*;
1656
1657     if let Some((lb, ub)) = lhs_bounds {
1658         if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1659             if rel == Rel::Eq || rel == Rel::Ne {
1660                 if norm_rhs_val < lb || norm_rhs_val > ub {
1661                     err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1662                 }
1663             } else if match rel {
1664                 Rel::Lt => if invert {
1665                     norm_rhs_val < lb
1666                 } else {
1667                     ub < norm_rhs_val
1668                 },
1669                 Rel::Le => if invert {
1670                     norm_rhs_val <= lb
1671                 } else {
1672                     ub <= norm_rhs_val
1673                 },
1674                 Rel::Eq | Rel::Ne => unreachable!(),
1675             } {
1676                 err_upcast_comparison(cx, span, lhs, true)
1677             } else if match rel {
1678                 Rel::Lt => if invert {
1679                     norm_rhs_val >= ub
1680                 } else {
1681                     lb >= norm_rhs_val
1682                 },
1683                 Rel::Le => if invert {
1684                     norm_rhs_val > ub
1685                 } else {
1686                     lb > norm_rhs_val
1687                 },
1688                 Rel::Eq | Rel::Ne => unreachable!(),
1689             } {
1690                 err_upcast_comparison(cx, span, lhs, false)
1691             }
1692         }
1693     }
1694 }
1695
1696 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1697     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1698         if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1699             let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1700             let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1701                 val
1702             } else {
1703                 return;
1704             };
1705
1706             let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1707             let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1708
1709             upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1710             upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
1711         }
1712     }
1713 }
1714
1715 /// **What it does:** Checks for public `impl` or `fn` missing generalization
1716 /// over different hashers and implicitly defaulting to the default hashing
1717 /// algorithm (SipHash).
1718 ///
1719 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
1720 /// used with them.
1721 ///
1722 /// **Known problems:** Suggestions for replacing constructors can contain
1723 /// false-positives. Also applying suggestions can require modification of other
1724 /// pieces of code, possibly including external crates.
1725 ///
1726 /// **Example:**
1727 /// ```rust
1728 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { ... }
1729 ///
1730 /// pub foo(map: &mut HashMap<i32, i32>) { .. }
1731 /// ```
1732 declare_clippy_lint! {
1733     pub IMPLICIT_HASHER,
1734     style,
1735     "missing generalization over different hashers"
1736 }
1737
1738 pub struct ImplicitHasher;
1739
1740 impl LintPass for ImplicitHasher {
1741     fn get_lints(&self) -> LintArray {
1742         lint_array!(IMPLICIT_HASHER)
1743     }
1744 }
1745
1746 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
1747     #[allow(cast_possible_truncation)]
1748     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1749         use syntax_pos::BytePos;
1750
1751         fn suggestion<'a, 'tcx>(
1752             cx: &LateContext<'a, 'tcx>,
1753             db: &mut DiagnosticBuilder,
1754             generics_span: Span,
1755             generics_suggestion_span: Span,
1756             target: &ImplicitHasherType,
1757             vis: ImplicitHasherConstructorVisitor,
1758         ) {
1759             let generics_snip = snippet(cx, generics_span, "");
1760             // trim `<` `>`
1761             let generics_snip = if generics_snip.is_empty() {
1762                 ""
1763             } else {
1764                 &generics_snip[1..generics_snip.len() - 1]
1765             };
1766
1767             multispan_sugg(
1768                 db,
1769                 "consider adding a type parameter".to_string(),
1770                 vec![
1771                     (
1772                         generics_suggestion_span,
1773                         format!(
1774                             "<{}{}S: ::std::hash::BuildHasher{}>",
1775                             generics_snip,
1776                             if generics_snip.is_empty() { "" } else { ", " },
1777                             if vis.suggestions.is_empty() {
1778                                 ""
1779                             } else {
1780                                 // request users to add `Default` bound so that generic constructors can be used
1781                                 " + Default"
1782                             },
1783                         ),
1784                     ),
1785                     (
1786                         target.span(),
1787                         format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
1788                     ),
1789                 ],
1790             );
1791
1792             if !vis.suggestions.is_empty() {
1793                 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
1794             }
1795         }
1796
1797         if !cx.access_levels.is_exported(item.id) {
1798             return;
1799         }
1800
1801         match item.node {
1802             ItemKind::Impl(_, _, _, ref generics, _, ref ty, ref items) => {
1803                 let mut vis = ImplicitHasherTypeVisitor::new(cx);
1804                 vis.visit_ty(ty);
1805
1806                 for target in &vis.found {
1807                     if differing_macro_contexts(item.span, target.span()) {
1808                         return;
1809                     }
1810
1811                     let generics_suggestion_span = generics.span.substitute_dummy({
1812                         let pos = snippet_opt(cx, item.span.until(target.span()))
1813                             .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)))
1814                             .expect("failed to create span for type arguments");
1815                         Span::new(pos, pos, item.span.data().ctxt)
1816                     });
1817
1818                     let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
1819                     for item in items.iter().map(|item| cx.tcx.hir.impl_item(item.id)) {
1820                         ctr_vis.visit_impl_item(item);
1821                     }
1822
1823                     span_lint_and_then(
1824                         cx,
1825                         IMPLICIT_HASHER,
1826                         target.span(),
1827                         &format!("impl for `{}` should be generalized over different hashers", target.type_name()),
1828                         move |db| {
1829                             suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
1830                         },
1831                     );
1832                 }
1833             },
1834             ItemKind::Fn(ref decl, .., ref generics, body_id) => {
1835                 let body = cx.tcx.hir.body(body_id);
1836
1837                 for ty in &decl.inputs {
1838                     let mut vis = ImplicitHasherTypeVisitor::new(cx);
1839                     vis.visit_ty(ty);
1840
1841                     for target in &vis.found {
1842                         let generics_suggestion_span = generics.span.substitute_dummy({
1843                             let pos = snippet_opt(cx, item.span.until(body.arguments[0].pat.span))
1844                                 .and_then(|snip| {
1845                                     let i = snip.find("fn")?;
1846                                     Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
1847                                 })
1848                                 .expect("failed to create span for type parameters");
1849                             Span::new(pos, pos, item.span.data().ctxt)
1850                         });
1851
1852                         let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
1853                         ctr_vis.visit_body(body);
1854
1855                         span_lint_and_then(
1856                             cx,
1857                             IMPLICIT_HASHER,
1858                             target.span(),
1859                             &format!(
1860                                 "parameter of type `{}` should be generalized over different hashers",
1861                                 target.type_name()
1862                             ),
1863                             move |db| {
1864                                 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
1865                             },
1866                         );
1867                     }
1868                 }
1869             },
1870             _ => {},
1871         }
1872     }
1873 }
1874
1875 enum ImplicitHasherType<'tcx> {
1876     HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
1877     HashSet(Span, Ty<'tcx>, Cow<'static, str>),
1878 }
1879
1880 impl<'tcx> ImplicitHasherType<'tcx> {
1881     /// Checks that `ty` is a target type without a BuildHasher.
1882     fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty) -> Option<Self> {
1883         if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.node {
1884             let params: Vec<_> = path.segments.last().as_ref()?.args.as_ref()?
1885                 .args.iter().filter_map(|arg| match arg {
1886                     GenericArg::Type(ty) => Some(ty),
1887                     GenericArg::Lifetime(_) => None,
1888                 }).collect();
1889             let params_len = params.len();
1890
1891             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1892
1893             if match_path(path, &paths::HASHMAP) && params_len == 2 {
1894                 Some(ImplicitHasherType::HashMap(
1895                     hir_ty.span,
1896                     ty,
1897                     snippet(cx, params[0].span, "K"),
1898                     snippet(cx, params[1].span, "V"),
1899                 ))
1900             } else if match_path(path, &paths::HASHSET) && params_len == 1 {
1901                 Some(ImplicitHasherType::HashSet(hir_ty.span, ty, snippet(cx, params[0].span, "T")))
1902             } else {
1903                 None
1904             }
1905         } else {
1906             None
1907         }
1908     }
1909
1910     fn type_name(&self) -> &'static str {
1911         match *self {
1912             ImplicitHasherType::HashMap(..) => "HashMap",
1913             ImplicitHasherType::HashSet(..) => "HashSet",
1914         }
1915     }
1916
1917     fn type_arguments(&self) -> String {
1918         match *self {
1919             ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
1920             ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
1921         }
1922     }
1923
1924     fn ty(&self) -> Ty<'tcx> {
1925         match *self {
1926             ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
1927         }
1928     }
1929
1930     fn span(&self) -> Span {
1931         match *self {
1932             ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
1933         }
1934     }
1935 }
1936
1937 struct ImplicitHasherTypeVisitor<'a, 'tcx: 'a> {
1938     cx: &'a LateContext<'a, 'tcx>,
1939     found: Vec<ImplicitHasherType<'tcx>>,
1940 }
1941
1942 impl<'a, 'tcx: 'a> ImplicitHasherTypeVisitor<'a, 'tcx> {
1943     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
1944         Self { cx, found: vec![] }
1945     }
1946 }
1947
1948 impl<'a, 'tcx: 'a> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
1949     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1950         if let Some(target) = ImplicitHasherType::new(self.cx, t) {
1951             self.found.push(target);
1952         }
1953
1954         walk_ty(self, t);
1955     }
1956
1957     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1958         NestedVisitorMap::None
1959     }
1960 }
1961
1962 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
1963 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx: 'a + 'b> {
1964     cx: &'a LateContext<'a, 'tcx>,
1965     body: &'a TypeckTables<'tcx>,
1966     target: &'b ImplicitHasherType<'tcx>,
1967     suggestions: BTreeMap<Span, String>,
1968 }
1969
1970 impl<'a, 'b, 'tcx: 'a + 'b> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1971     fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
1972         Self {
1973             cx,
1974             body: cx.tables,
1975             target,
1976             suggestions: BTreeMap::new(),
1977         }
1978     }
1979 }
1980
1981 impl<'a, 'b, 'tcx: 'a + 'b> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1982     fn visit_body(&mut self, body: &'tcx Body) {
1983         self.body = self.cx.tcx.body_tables(body.id());
1984         walk_body(self, body);
1985     }
1986
1987     fn visit_expr(&mut self, e: &'tcx Expr) {
1988         if_chain! {
1989             if let ExprKind::Call(ref fun, ref args) = e.node;
1990             if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.node;
1991             if let TyKind::Path(QPath::Resolved(None, ref ty_path)) = ty.node;
1992             then {
1993                 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
1994                     return;
1995                 }
1996
1997                 if match_path(ty_path, &paths::HASHMAP) {
1998                     if method.ident.name == "new" {
1999                         self.suggestions
2000                             .insert(e.span, "HashMap::default()".to_string());
2001                     } else if method.ident.name == "with_capacity" {
2002                         self.suggestions.insert(
2003                             e.span,
2004                             format!(
2005                                 "HashMap::with_capacity_and_hasher({}, Default::default())",
2006                                 snippet(self.cx, args[0].span, "capacity"),
2007                             ),
2008                         );
2009                     }
2010                 } else if match_path(ty_path, &paths::HASHSET) {
2011                     if method.ident.name == "new" {
2012                         self.suggestions
2013                             .insert(e.span, "HashSet::default()".to_string());
2014                     } else if method.ident.name == "with_capacity" {
2015                         self.suggestions.insert(
2016                             e.span,
2017                             format!(
2018                                 "HashSet::with_capacity_and_hasher({}, Default::default())",
2019                                 snippet(self.cx, args[0].span, "capacity"),
2020                             ),
2021                         );
2022                     }
2023                 }
2024             }
2025         }
2026
2027         walk_expr(self, e);
2028     }
2029
2030     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2031         NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir)
2032     }
2033 }