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