]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/types.rs
Make vec_box MachineApplicable
[rust.git] / clippy_lints / src / types.rs
index 035ca2b04964b7d8ee4c16841999ee9c16e2e346..6ee7d10155cd602d96fcd1489d1462c4ec29b447 100644 (file)
@@ -1,40 +1,33 @@
-// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-
 #![allow(clippy::default_hash_types)]
 
+use crate::consts::{constant, Constant};
 use crate::reexport::*;
-use crate::rustc::hir;
-use crate::rustc::hir::*;
-use crate::rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
-use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, LintContext};
-use crate::rustc::{declare_tool_lint, lint_array};
+use crate::utils::paths;
+use crate::utils::{
+    clip, comparisons, differing_macro_contexts, higher, in_constant, in_macro, int_bits, last_path_segment,
+    match_def_path, match_path, multispan_sugg, opt_def_id, same_tys, sext, snippet, snippet_opt,
+    snippet_with_applicability, span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then, unsext,
+    AbsolutePathBuffer,
+};
 use if_chain::if_chain;
-use crate::rustc::ty::{self, Ty, TyCtxt, TypeckTables};
-use crate::rustc::ty::layout::LayoutOf;
-use crate::rustc_typeck::hir_ty_to_ty;
+use rustc::hir;
+use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
+use rustc::hir::*;
+use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
+use rustc::ty::layout::LayoutOf;
+use rustc::ty::{self, Ty, TyCtxt, TypeckTables};
+use rustc::{declare_tool_lint, lint_array};
+use rustc_errors::Applicability;
+use rustc_target::spec::abi::Abi;
+use rustc_typeck::hir_ty_to_ty;
+use std::borrow::Cow;
 use std::cmp::Ordering;
 use std::collections::BTreeMap;
-use std::borrow::Cow;
-use crate::syntax::ast::{FloatTy, IntTy, UintTy};
-use crate::syntax::source_map::Span;
-use crate::syntax::errors::DiagnosticBuilder;
-use crate::rustc_target::spec::abi::Abi;
-use crate::utils::{comparisons, differing_macro_contexts, higher, in_constant, in_macro, last_path_segment, match_def_path, match_path,
-            match_type, multispan_sugg, opt_def_id, same_tys, snippet, snippet_opt, span_help_and_lint, span_lint,
-            span_lint_and_sugg, span_lint_and_then, clip, unsext, sext, int_bits};
-use crate::utils::paths;
-use crate::consts::{constant, Constant};
+use syntax::ast::{FloatTy, IntTy, UintTy};
+use syntax::errors::DiagnosticBuilder;
+use syntax::source_map::Span;
 
 /// Handles all the linting of funky types
-#[allow(missing_copy_implementations)]
 pub struct TypePass;
 
 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
     "usage of `Box<Vec<T>>`, vector elements are already on the heap"
 }
 
+/// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
+///
+/// **Why is this bad?** `Vec` already keeps its contents in a separate area on
+/// the heap. So if you `Box` its contents, you just add another level of indirection.
+///
+/// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
+/// 1st comment).
+///
+/// **Example:**
+/// ```rust
+/// struct X {
+///     values: Vec<Box<i32>>,
+/// }
+/// ```
+///
+/// Better:
+///
+/// ```rust
+/// struct X {
+///     values: Vec<i32>,
+/// }
+/// ```
+declare_clippy_lint! {
+    pub VEC_BOX,
+    complexity,
+    "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
+}
+
 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
 /// definitions
 ///
 declare_clippy_lint! {
     pub LINKEDLIST,
     pedantic,
-    "usage of LinkedList, usually a vector is faster, or a more specialized data \
-     structure like a VecDeque"
+    "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a VecDeque"
 }
 
 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
 
 impl LintPass for TypePass {
     fn get_lints(&self) -> LintArray {
-        lint_array!(BOX_VEC, OPTION_OPTION, LINKEDLIST, BORROWED_BOX)
+        lint_array!(BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX)
+    }
+
+    fn name(&self) -> &'static str {
+        "Types"
     }
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypePass {
     fn check_fn(&mut self, cx: &LateContext<'_, '_>, _: FnKind<'_>, decl: &FnDecl, _: &Body, _: Span, id: NodeId) {
         // skip trait implementations, see #605
-        if let Some(hir::Node::Item(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(id)) {
+        if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent(id)) {
             if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
                 return;
             }
@@ -162,7 +186,7 @@ fn check_fn(&mut self, cx: &LateContext<'_, '_>, _: FnKind<'_>, decl: &FnDecl, _
         check_fn_decl(cx, decl);
     }
 
-    fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &StructField) {
+    fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) {
         check_ty(cx, &field.ty, false);
     }
 
@@ -202,7 +226,7 @@ fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath, path: &[&str])
             GenericArg::Lifetime(_) => None,
         });
         if let TyKind::Path(ref qpath) = ty.node;
-        if let Some(did) = opt_def_id(cx.tables.qpath_def(qpath, cx.tcx.hir.node_to_hir_id(ty.id)));
+        if let Some(did) = opt_def_id(cx.tables.qpath_def(qpath, cx.tcx.hir().node_to_hir_id(ty.id)));
         if match_def_path(cx.tcx, did, path);
         then {
             return true;
@@ -216,13 +240,13 @@ fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath, path: &[&str])
 ///
 /// The parameter `is_local` distinguishes the context of the type; types from
 /// local bindings should only be checked for the `BORROWED_BOX` lint.
-fn check_ty(cx: &LateContext<'_, '_>, ast_ty: &hir::Ty, is_local: bool) {
-    if in_macro(ast_ty.span) {
+fn check_ty(cx: &LateContext<'_, '_>, hir_ty: &hir::Ty, is_local: bool) {
+    if in_macro(hir_ty.span) {
         return;
     }
-    match ast_ty.node {
+    match hir_ty.node {
         TyKind::Path(ref qpath) if !is_local => {
-            let hir_id = cx.tcx.hir.node_to_hir_id(ast_ty.id);
+            let hir_id = cx.tcx.hir().node_to_hir_id(hir_ty.id);
             let def = cx.tables.qpath_def(qpath, hir_id);
             if let Some(def_id) = opt_def_id(def) {
                 if Some(def_id) == cx.tcx.lang_items().owned_box() {
@@ -230,20 +254,55 @@ fn check_ty(cx: &LateContext<'_, '_>, ast_ty: &hir::Ty, is_local: bool) {
                         span_help_and_lint(
                             cx,
                             BOX_VEC,
-                            ast_ty.span,
+                            hir_ty.span,
                             "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
                             "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
                         );
                         return; // don't recurse into the type
                     }
+                } else if match_def_path(cx.tcx, def_id, &paths::VEC) {
+                    if_chain! {
+                        // Get the _ part of Vec<_>
+                        if let Some(ref last) = last_path_segment(qpath).args;
+                        if let Some(ty) = last.args.iter().find_map(|arg| match arg {
+                            GenericArg::Type(ty) => Some(ty),
+                            GenericArg::Lifetime(_) => None,
+                        });
+                        // ty is now _ at this point
+                        if let TyKind::Path(ref ty_qpath) = ty.node;
+                        let def = cx.tables.qpath_def(ty_qpath, ty.hir_id);
+                        if let Some(def_id) = opt_def_id(def);
+                        if Some(def_id) == cx.tcx.lang_items().owned_box();
+                        // At this point, we know ty is Box<T>, now get T
+                        if let Some(ref last) = last_path_segment(ty_qpath).args;
+                        if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
+                            GenericArg::Type(ty) => Some(ty),
+                            GenericArg::Lifetime(_) => None,
+                        });
+                        then {
+                            let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
+                            if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env) {
+                                span_lint_and_sugg(
+                                    cx,
+                                    VEC_BOX,
+                                    hir_ty.span,
+                                    "`Vec<T>` is already on the heap, the boxing is unnecessary.",
+                                    "try",
+                                    format!("Vec<{}>", ty_ty),
+                                    Applicability::MachineApplicable,
+                                );
+                                return; // don't recurse into the type
+                            }
+                        }
+                    }
                 } else if match_def_path(cx.tcx, def_id, &paths::OPTION) {
                     if match_type_parameter(cx, qpath, &paths::OPTION) {
                         span_lint(
                             cx,
                             OPTION_OPTION,
-                            ast_ty.span,
+                            hir_ty.span,
                             "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
-                            enum if you need to distinguish all 3 cases",
+                             enum if you need to distinguish all 3 cases",
                         );
                         return; // don't recurse into the type
                     }
@@ -251,7 +310,7 @@ enum if you need to distinguish all 3 cases",
                     span_help_and_lint(
                         cx,
                         LINKEDLIST,
-                        ast_ty.span,
+                        hir_ty.span,
                         "I see you're using a LinkedList! Perhaps you meant some other data structure?",
                         "a VecDeque might work",
                     );
@@ -273,16 +332,18 @@ enum if you need to distinguish all 3 cases",
                         check_ty(cx, ty, is_local);
                     }
                 },
-                QPath::Resolved(None, ref p) => for ty in p.segments.iter().flat_map(|seg| {
-                    seg.args
-                        .as_ref()
-                        .map_or_else(|| [].iter(), |params| params.args.iter())
-                        .filter_map(|arg| match arg {
-                            GenericArg::Type(ty) => Some(ty),
-                            GenericArg::Lifetime(_) => None,
-                        })
-                }) {
-                    check_ty(cx, ty, is_local);
+                QPath::Resolved(None, ref p) => {
+                    for ty in p.segments.iter().flat_map(|seg| {
+                        seg.args
+                            .as_ref()
+                            .map_or_else(|| [].iter(), |params| params.args.iter())
+                            .filter_map(|arg| match arg {
+                                GenericArg::Type(ty) => Some(ty),
+                                GenericArg::Lifetime(_) => None,
+                            })
+                    }) {
+                        check_ty(cx, ty, is_local);
+                    }
                 },
                 QPath::TypeRelative(ref ty, ref seg) => {
                     check_ty(cx, ty, is_local);
@@ -297,20 +358,24 @@ enum if you need to distinguish all 3 cases",
                 },
             }
         },
-        TyKind::Rptr(ref lt, ref mut_ty) => check_ty_rptr(cx, ast_ty, is_local, lt, mut_ty),
+        TyKind::Rptr(ref lt, ref mut_ty) => check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
         // recurse
-        TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
-        TyKind::Tup(ref tys) => for ty in tys {
-            check_ty(cx, ty, is_local);
+        TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
+            check_ty(cx, ty, is_local)
+        },
+        TyKind::Tup(ref tys) => {
+            for ty in tys {
+                check_ty(cx, ty, is_local);
+            }
         },
         _ => {},
     }
 }
 
-fn check_ty_rptr(cx: &LateContext<'_, '_>, ast_ty: &hir::Ty, is_local: bool, lt: &Lifetime, mut_ty: &MutTy) {
+fn check_ty_rptr(cx: &LateContext<'_, '_>, hir_ty: &hir::Ty, is_local: bool, lt: &Lifetime, mut_ty: &MutTy) {
     match mut_ty.ty.node {
         TyKind::Path(ref qpath) => {
-            let hir_id = cx.tcx.hir.node_to_hir_id(mut_ty.ty.id);
+            let hir_id = cx.tcx.hir().node_to_hir_id(mut_ty.ty.id);
             let def = cx.tables.qpath_def(qpath, hir_id);
             if_chain! {
                 if let Some(def_id) = opt_def_id(def);
@@ -332,19 +397,27 @@ fn check_ty_rptr(cx: &LateContext<'_, '_>, ast_ty: &hir::Ty, is_local: bool, lt:
                     let ltopt = if lt.is_elided() {
                         String::new()
                     } else {
-                        format!("{} ", lt.name.ident().name.as_str())
+                        format!("{} ", lt.name.ident().as_str())
                     };
                     let mutopt = if mut_ty.mutbl == Mutability::MutMutable {
                         "mut "
                     } else {
                         ""
                     };
-                    span_lint_and_sugg(cx,
+                    let mut applicability = Applicability::MachineApplicable;
+                    span_lint_and_sugg(
+                        cx,
                         BORROWED_BOX,
-                        ast_ty.span,
+                        hir_ty.span,
                         "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
                         "try",
-                        format!("&{}{}{}", ltopt, mutopt, &snippet(cx, inner.span, ".."))
+                        format!(
+                            "&{}{}{}",
+                            ltopt,
+                            mutopt,
+                            &snippet_with_applicability(cx, inner.span, "..", &mut applicability)
+                        ),
+                        Applicability::Unspecified,
                     );
                     return; // don't recurse into the type
                 }
@@ -371,7 +444,6 @@ fn is_any_trait(t: &hir::Ty) -> bool {
     false
 }
 
-#[allow(missing_copy_implementations)]
 pub struct LetPass;
 
 /// **What it does:** Checks for binding a unit value.
@@ -383,7 +455,9 @@ fn is_any_trait(t: &hir::Ty) -> bool {
 ///
 /// **Example:**
 /// ```rust
-/// let x = { 1; };
+/// let x = {
+///     1;
+/// };
 /// ```
 declare_clippy_lint! {
     pub LET_UNIT_VALUE,
@@ -391,37 +465,37 @@ fn is_any_trait(t: &hir::Ty) -> bool {
     "creating a let binding to a value of unit type, which usually can't be used afterwards"
 }
 
-fn check_let_unit(cx: &LateContext<'_, '_>, decl: &Decl) {
-    if let DeclKind::Local(ref local) = decl.node {
-        if is_unit(cx.tables.pat_ty(&local.pat)) {
-            if in_external_macro(cx.sess(), decl.span) || in_macro(local.pat.span) {
-                return;
-            }
-            if higher::is_from_for_desugar(decl) {
-                return;
-            }
-            span_lint(
-                cx,
-                LET_UNIT_VALUE,
-                decl.span,
-                &format!(
-                    "this let-binding has unit value. Consider omitting `let {} =`",
-                    snippet(cx, local.pat.span, "..")
-                ),
-            );
-        }
-    }
-}
-
 impl LintPass for LetPass {
     fn get_lints(&self) -> LintArray {
         lint_array!(LET_UNIT_VALUE)
     }
+
+    fn name(&self) -> &'static str {
+        "LetUnitValue"
+    }
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetPass {
-    fn check_decl(&mut self, cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl) {
-        check_let_unit(cx, decl)
+    fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
+        if let StmtKind::Local(ref local) = stmt.node {
+            if is_unit(cx.tables.pat_ty(&local.pat)) {
+                if in_external_macro(cx.sess(), stmt.span) || in_macro(local.pat.span) {
+                    return;
+                }
+                if higher::is_from_for_desugar(local) {
+                    return;
+                }
+                span_lint(
+                    cx,
+                    LET_UNIT_VALUE,
+                    stmt.span,
+                    &format!(
+                        "this let-binding has unit value. Consider omitting `let {} =`",
+                        snippet(cx, local.pat.span, "..")
+                    ),
+                );
+            }
+        }
     }
 }
 
@@ -435,11 +509,21 @@ fn check_decl(&mut self, cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl) {
 ///
 /// **Example:**
 /// ```rust
-/// if { foo(); } == { bar(); } { baz(); }
+/// if {
+///     foo();
+/// } == {
+///     bar();
+/// } {
+///     baz();
+/// }
 /// ```
 /// is equal to
 /// ```rust
-/// { foo(); bar(); baz(); }
+/// {
+///     foo();
+///     bar();
+///     baz();
+/// }
 /// ```
 declare_clippy_lint! {
     pub UNIT_CMP,
@@ -447,13 +531,16 @@ fn check_decl(&mut self, cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl) {
     "comparing unit values"
 }
 
-#[allow(missing_copy_implementations)]
 pub struct UnitCmp;
 
 impl LintPass for UnitCmp {
     fn get_lints(&self) -> LintArray {
         lint_array!(UNIT_CMP)
     }
+
+    fn name(&self) -> &'static str {
+        "UnicCmp"
+    }
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
@@ -483,7 +570,8 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
     }
 }
 
-/// **What it does:** Checks for passing a unit value as an argument to a function without using a unit literal (`()`).
+/// **What it does:** Checks for passing a unit value as an argument to a function without using a
+/// unit literal (`()`).
 ///
 /// **Why is this bad?** This is likely the result of an accidental semicolon.
 ///
@@ -492,8 +580,8 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
 /// **Example:**
 /// ```rust
 /// foo({
-///   let a = bar();
-///   baz(a);
+///     let a = bar();
+///     baz(a);
 /// })
 /// ```
 declare_clippy_lint! {
@@ -508,6 +596,10 @@ impl LintPass for UnitArg {
     fn get_lints(&self) -> LintArray {
         lint_array!(UNIT_ARG)
     }
+
+    fn name(&self) -> &'static str {
+        "UnitArg"
+    }
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
@@ -515,35 +607,43 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
         if in_macro(expr.span) {
             return;
         }
+
+        // apparently stuff in the desugaring of `?` can trigger this
+        // so check for that here
+        // only the calls to `Try::from_error` is marked as desugared,
+        // so we need to check both the current Expr and its parent.
+        if is_questionmark_desugar_marked_call(expr) {
+            return;
+        }
+        if_chain! {
+            let map = &cx.tcx.hir();
+            let opt_parent_node = map.find(map.get_parent_node(expr.id));
+            if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
+            if is_questionmark_desugar_marked_call(parent_expr);
+            then {
+                return;
+            }
+        }
+
         match expr.node {
             ExprKind::Call(_, ref args) | ExprKind::MethodCall(_, _, ref args) => {
                 for arg in args {
                     if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
-                        let map = &cx.tcx.hir;
-                        // apparently stuff in the desugaring of `?` can trigger this
-                        // so check for that here
-                        // only the calls to `Try::from_error` is marked as desugared,
-                        // so we need to check both the current Expr and its parent.
-                        if !is_questionmark_desugar_marked_call(expr) {
-                            if_chain!{
-                                let opt_parent_node = map.find(map.get_parent_node(expr.id));
-                                if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
-                                if is_questionmark_desugar_marked_call(parent_expr);
-                                then {}
-                                else {
-                                    // `expr` and `parent_expr` where _both_ not from
-                                    // desugaring `?`, so lint
-                                    span_lint_and_sugg(
-                                        cx,
-                                        UNIT_ARG,
-                                        arg.span,
-                                        "passing a unit value to a function",
-                                        "if you intended to pass a unit value, use a unit literal instead",
-                                        "()".to_string(),
-                                    );
-                                }
+                        if let ExprKind::Match(.., match_source) = &arg.node {
+                            if *match_source == MatchSource::TryDesugar {
+                                continue;
                             }
                         }
+
+                        span_lint_and_sugg(
+                            cx,
+                            UNIT_ARG,
+                            arg.span,
+                            "passing a unit value to a function",
+                            "if you intended to pass a unit value, use a unit literal instead",
+                            "()".to_string(),
+                            Applicability::MachineApplicable,
+                        );
                     }
                 }
             },
@@ -553,7 +653,7 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
 }
 
 fn is_questionmark_desugar_marked_call(expr: &Expr) -> bool {
-    use crate::syntax_pos::hygiene::CompilerDesugaringKind;
+    use syntax_pos::hygiene::CompilerDesugaringKind;
     if let ExprKind::Call(ref callee, _) = expr.node {
         callee.span.is_compiler_desugaring(CompilerDesugaringKind::QuestionMark)
     } else {
@@ -593,7 +693,8 @@ fn is_unit_literal(expr: &Expr) -> bool {
 ///
 /// **Example:**
 /// ```rust
-/// let x = u64::MAX; x as f64
+/// let x = u64::MAX;
+/// x as f64
 /// ```
 declare_clippy_lint! {
     pub CAST_PRECISION_LOSS,
@@ -614,7 +715,7 @@ fn is_unit_literal(expr: &Expr) -> bool {
 /// **Example:**
 /// ```rust
 /// let y: i8 = -1;
-/// y as u128  // will return 18446744073709551615
+/// y as u128 // will return 18446744073709551615
 /// ```
 declare_clippy_lint! {
     pub CAST_SIGN_LOSS,
@@ -634,13 +735,14 @@ fn is_unit_literal(expr: &Expr) -> bool {
 ///
 /// **Example:**
 /// ```rust
-/// fn as_u8(x: u64) -> u8 { x as u8 }
+/// fn as_u8(x: u64) -> u8 {
+///     x as u8
+/// }
 /// ```
 declare_clippy_lint! {
     pub CAST_POSSIBLE_TRUNCATION,
     pedantic,
-    "casts that may cause truncation of the value, e.g. `x as u8` where `x: u32`, \
-     or `x as i32` where `x: f32`"
+    "casts that may cause truncation of the value, e.g. `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
 }
 
 /// **What it does:** Checks for casts from an unsigned type to a signed type of
@@ -658,13 +760,12 @@ fn is_unit_literal(expr: &Expr) -> bool {
 ///
 /// **Example:**
 /// ```rust
-/// u32::MAX as i32  // will yield a value of `-1`
+/// u32::MAX as i32 // will yield a value of `-1`
 /// ```
 declare_clippy_lint! {
     pub CAST_POSSIBLE_WRAP,
     pedantic,
-    "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` \
-     and `x > i32::MAX`"
+    "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` and `x > i32::MAX`"
 }
 
 /// **What it does:** Checks for on casts between numerical types that may
@@ -681,13 +782,17 @@ fn is_unit_literal(expr: &Expr) -> bool {
 ///
 /// **Example:**
 /// ```rust
-/// fn as_u64(x: u8) -> u64 { x as u64 }
+/// fn as_u64(x: u8) -> u64 {
+///     x as u64
+/// }
 /// ```
 ///
 /// Using `::from` would look like this:
 ///
 /// ```rust
-/// fn as_u64(x: u8) -> u64 { u64::from(x) }
+/// fn as_u64(x: u8) -> u64 {
+///     u64::from(x)
+/// }
 /// ```
 declare_clippy_lint! {
     pub CAST_LOSSLESS,
@@ -769,11 +874,15 @@ fn is_unit_literal(expr: &Expr) -> bool {
 ///
 /// ```rust
 /// // Bad
-/// fn fn1() -> i16 { 1 };
+/// fn fn1() -> i16 {
+///     1
+/// };
 /// let _ = fn1 as i32;
 ///
 /// // Better: Cast to usize first, then comment with the reason for the truncation
-/// fn fn2() -> i16 { 1 };
+/// fn fn2() -> i16 {
+///     1
+/// };
 /// let fn_ptr = fn2 as usize;
 /// let fn_ptr_truncated = fn_ptr as i32;
 /// ```
@@ -834,11 +943,7 @@ fn span_precision_loss_lint(cx: &LateContext<'_, '_>, expr: &Expr, cast_from: Ty
              is only {4} bits wide)",
             cast_from,
             if cast_to_f64 { "f64" } else { "f32" },
-            if arch_dependent {
-                arch_dependent_str
-            } else {
-                ""
-            },
+            if arch_dependent { arch_dependent_str } else { "" },
             from_nbits_str,
             mantissa_nbits
         ),
@@ -856,9 +961,12 @@ fn should_strip_parens(op: &Expr, snip: &str) -> bool {
 
 fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr, op: &Expr, cast_from: Ty<'_>, cast_to: Ty<'_>) {
     // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
-    if in_constant(cx, expr.id) { return }
+    if in_constant(cx, expr.id) {
+        return;
+    }
     // The suggestion is to use a function call, so if the original expression
     // has parens on the outside, they are no longer needed.
+    let mut applicability = Applicability::MachineApplicable;
     let opt = snippet_opt(cx, op.span);
     let sugg = if let Some(ref snip) = opt {
         if should_strip_parens(op, snip) {
@@ -867,6 +975,7 @@ fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr, op: &Expr, cast_fro
             snip.as_str()
         }
     } else {
+        applicability = Applicability::HasPlaceholders;
         ".."
     };
 
@@ -874,9 +983,13 @@ fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr, op: &Expr, cast_fro
         cx,
         CAST_LOSSLESS,
         expr.span,
-        &format!("casting {} to {} may become silently lossy if types change", cast_from, cast_to),
+        &format!(
+            "casting {} to {} may become silently lossy if types change",
+            cast_from, cast_to
+        ),
         "try",
         format!("{}::from({})", cast_to, sugg),
+        applicability,
     );
 }
 
@@ -981,6 +1094,27 @@ fn get_lints(&self) -> LintArray {
             FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
         )
     }
+
+    fn name(&self) -> &'static str {
+        "Casts"
+    }
+}
+
+// Check if the given type is either `core::ffi::c_void` or
+// one of the platform specific `libc::<platform>::c_void` of libc.
+fn is_c_void(tcx: TyCtxt<'_, '_, '_>, ty: Ty<'_>) -> bool {
+    if let ty::Adt(adt, _) = ty.sty {
+        let mut apb = AbsolutePathBuffer { names: vec![] };
+        tcx.push_item_path(&mut apb, adt.did, false);
+
+        if apb.names.is_empty() {
+            return false;
+        }
+        if apb.names[0] == "libc" || apb.names[0] == "core" && *apb.names.last().unwrap() == "c_void" {
+            return true;
+        }
+    }
+    false
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
@@ -989,16 +1123,21 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
             let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
             lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
             if let ExprKind::Lit(ref lit) = ex.node {
-                use crate::syntax::ast::{LitIntType, LitKind};
+                use syntax::ast::{LitIntType, LitKind};
                 match lit.node {
                     LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
-                    _ => if cast_from.sty == cast_to.sty && !in_external_macro(cx.sess(), expr.span) {
-                        span_lint(
-                            cx,
-                            UNNECESSARY_CAST,
-                            expr.span,
-                            &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
-                        );
+                    _ => {
+                        if cast_from.sty == cast_to.sty && !in_external_macro(cx.sess(), expr.span) {
+                            span_lint(
+                                cx,
+                                UNNECESSARY_CAST,
+                                expr.span,
+                                &format!(
+                                    "casting to the same type is unnecessary (`{}` -> `{}`)",
+                                    cast_from, cast_to
+                                ),
+                            );
+                        }
                     },
                 }
             }
@@ -1047,8 +1186,7 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
                         check_lossless(cx, expr, ex, cast_from, cast_to);
                     },
                     (false, false) => {
-                        if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty)
-                        {
+                        if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty) {
                             span_lint(
                                 cx,
                                 CAST_POSSIBLE_TRUNCATION,
@@ -1056,25 +1194,21 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
                                 "casting f64 to f32 may truncate the value",
                             );
                         }
-                        if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty)
-                        {
+                        if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty) {
                             span_lossless_lint(cx, expr, ex, cast_from, cast_to);
                         }
                     },
                 }
             }
 
-            if_chain!{
+            if_chain! {
                 if let ty::RawPtr(from_ptr_ty) = &cast_from.sty;
                 if let ty::RawPtr(to_ptr_ty) = &cast_to.sty;
-                if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi());
-                if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi());
+                if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi);
+                if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi);
                 if from_align < to_align;
                 // with c_void, we inherently need to trust the user
-                if ! (
-                    match_type(cx, from_ptr_ty.ty, &paths::C_VOID)
-                    || match_type(cx, from_ptr_ty.ty, &paths::C_VOID_LIBC)
-                );
+                if !is_c_void(cx.tcx, from_ptr_ty.ty);
                 then {
                     span_lint(
                         cx,
@@ -1088,15 +1222,22 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
     }
 }
 
-fn lint_fn_to_numeric_cast(cx: &LateContext<'_, '_>, expr: &Expr, cast_expr: &Expr, cast_from: Ty<'_>, cast_to: Ty<'_>) {
+fn lint_fn_to_numeric_cast(
+    cx: &LateContext<'_, '_>,
+    expr: &Expr,
+    cast_expr: &Expr,
+    cast_from: Ty<'_>,
+    cast_to: Ty<'_>,
+) {
     // We only want to check casts to `ty::Uint` or `ty::Int`
     match cast_to.sty {
         ty::Uint(_) | ty::Int(..) => { /* continue on */ },
-        _ => return
+        _ => return,
     }
     match cast_from.sty {
         ty::FnDef(..) | ty::FnPtr(_) => {
-            let from_snippet = snippet(cx, cast_expr.span, "x");
+            let mut applicability = Applicability::MachineApplicable;
+            let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
 
             let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
             if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
@@ -1104,11 +1245,14 @@ fn lint_fn_to_numeric_cast(cx: &LateContext<'_, '_>, expr: &Expr, cast_expr: &Ex
                     cx,
                     FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
                     expr.span,
-                    &format!("casting function pointer `{}` to `{}`, which truncates the value", from_snippet, cast_to),
+                    &format!(
+                        "casting function pointer `{}` to `{}`, which truncates the value",
+                        from_snippet, cast_to
+                    ),
                     "try",
-                    format!("{} as usize", from_snippet)
+                    format!("{} as usize", from_snippet),
+                    applicability,
                 );
-
             } else if cast_to.sty != ty::Uint(UintTy::Usize) {
                 span_lint_and_sugg(
                     cx,
@@ -1116,11 +1260,12 @@ fn lint_fn_to_numeric_cast(cx: &LateContext<'_, '_>, expr: &Expr, cast_expr: &Ex
                     expr.span,
                     &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
                     "try",
-                    format!("{} as usize", from_snippet)
+                    format!("{} as usize", from_snippet),
+                    applicability,
                 );
             }
         },
-        _ => {}
+        _ => {},
     }
 }
 
@@ -1134,7 +1279,9 @@ fn lint_fn_to_numeric_cast(cx: &LateContext<'_, '_>, expr: &Expr, cast_expr: &Ex
 ///
 /// **Example:**
 /// ```rust
-/// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
+/// struct Foo {
+///     inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
+/// }
 /// ```
 declare_clippy_lint! {
     pub TYPE_COMPLEXITY,
@@ -1142,16 +1289,13 @@ fn lint_fn_to_numeric_cast(cx: &LateContext<'_, '_>, expr: &Expr, cast_expr: &Ex
     "usage of very complex types that might be better factored into `type` definitions"
 }
 
-#[allow(missing_copy_implementations)]
 pub struct TypeComplexityPass {
     threshold: u64,
 }
 
 impl TypeComplexityPass {
     pub fn new(threshold: u64) -> Self {
-        Self {
-            threshold,
-        }
+        Self { threshold }
     }
 }
 
@@ -1159,6 +1303,10 @@ impl LintPass for TypeComplexityPass {
     fn get_lints(&self) -> LintArray {
         lint_array!(TYPE_COMPLEXITY)
     }
+
+    fn name(&self) -> &'static str {
+        "TypeComplexityPass"
+    }
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
@@ -1174,7 +1322,7 @@ fn check_fn(
         self.check_fndecl(cx, decl);
     }
 
-    fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx StructField) {
+    fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
         // enum variants are also struct fields now
         self.check_type(cx, &field.ty);
     }
@@ -1263,12 +1411,12 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
             TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
 
             TyKind::TraitObject(ref param_bounds, _) => {
-                let has_lifetime_parameters = param_bounds
-                    .iter()
-                    .any(|bound| bound.bound_generic_params.iter().any(|gen| match gen.kind {
+                let has_lifetime_parameters = param_bounds.iter().any(|bound| {
+                    bound.bound_generic_params.iter().any(|gen| match gen.kind {
                         GenericParamKind::Lifetime { .. } => true,
                         _ => false,
-                    }));
+                    })
+                });
                 if has_lifetime_parameters {
                     // complex trait bounds like A<'a, 'b>
                     (50 * self.nest, 1)
@@ -1323,11 +1471,15 @@ impl LintPass for CharLitAsU8 {
     fn get_lints(&self) -> LintArray {
         lint_array!(CHAR_LIT_AS_U8)
     }
+
+    fn name(&self) -> &'static str {
+        "CharLiteralAsU8"
+    }
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
-        use crate::syntax::ast::{LitKind, UintTy};
+        use syntax::ast::{LitKind, UintTy};
 
         if let ExprKind::Cast(ref e, _) = expr.node {
             if let ExprKind::Lit(ref l) = e.node {
@@ -1336,7 +1488,10 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
                         let msg = "casting character literal to u8. `char`s \
                                    are 4 bytes wide in rust, so casting to u8 \
                                    truncates them";
-                        let help = format!("Consider using a byte literal instead:\nb{}", snippet(cx, e.span, "'x'"));
+                        let help = format!(
+                            "Consider using a byte literal instead:\nb{}",
+                            snippet(cx, e.span, "'x'")
+                        );
                         span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
                     }
                 }
@@ -1378,6 +1533,10 @@ impl LintPass for AbsurdExtremeComparisons {
     fn get_lints(&self) -> LintArray {
         lint_array!(ABSURD_EXTREME_COMPARISONS)
     }
+
+    fn name(&self) -> &'static str {
+        "AbsurdExtremeComparisons"
+    }
 }
 
 enum ExtremeType {
@@ -1396,17 +1555,12 @@ enum AbsurdComparisonResult {
     InequalityImpossible,
 }
 
-
-fn is_cast_between_fixed_and_target<'a, 'tcx>(
-    cx: &LateContext<'a, 'tcx>,
-    expr: &'tcx Expr
-) -> bool {
-
+fn is_cast_between_fixed_and_target<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
     if let ExprKind::Cast(ref cast_exp, _) = expr.node {
         let precast_ty = cx.tables.expr_ty(cast_exp);
         let cast_ty = cx.tables.expr_ty(expr);
 
-        return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty)
+        return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
     }
 
     false
@@ -1418,8 +1572,8 @@ fn detect_absurd_comparison<'a, 'tcx>(
     lhs: &'tcx Expr,
     rhs: &'tcx Expr,
 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
-    use crate::types::ExtremeType::*;
     use crate::types::AbsurdComparisonResult::*;
+    use crate::types::ExtremeType::*;
     use crate::utils::comparisons::*;
 
     // absurd comparison only makes sense on primitive types
@@ -1472,26 +1626,30 @@ fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -
     let cv = constant(cx, cx.tables, expr)?.0;
 
     let which = match (&ty.sty, cv) {
-        (&ty::Bool, Constant::Bool(false)) |
-        (&ty::Uint(_), Constant::Int(0)) => Minimum,
-        (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) => Minimum,
+        (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
+        (&ty::Int(ity), Constant::Int(i))
+            if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
+        {
+            Minimum
+        },
 
         (&ty::Bool, Constant::Bool(true)) => Maximum,
-        (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) => Maximum,
+        (&ty::Int(ity), Constant::Int(i))
+            if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
+        {
+            Maximum
+        },
         (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
 
         _ => return None,
     };
-    Some(ExtremeExpr {
-        which,
-        expr,
-    })
+    Some(ExtremeExpr { which, expr })
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
-        use crate::types::ExtremeType::*;
         use crate::types::AbsurdComparisonResult::*;
+        use crate::types::ExtremeType::*;
 
         if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
             if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
@@ -1536,7 +1694,7 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
 /// `u8`.
 ///
 /// **Known problems:**
-/// https://github.com/rust-lang-nursery/rust-clippy/issues/886
+/// https://github.com/rust-lang/rust-clippy/issues/886
 ///
 /// **Example:**
 /// ```rust
@@ -1554,6 +1712,10 @@ impl LintPass for InvalidUpcastComparisons {
     fn get_lints(&self) -> LintArray {
         lint_array!(INVALID_UPCAST_COMPARISONS)
     }
+
+    fn name(&self) -> &'static str {
+        "InvalidUpcastComparisons"
+    }
 }
 
 #[derive(Copy, Clone, Debug, Eq)]
@@ -1577,8 +1739,7 @@ fn cmp_s_u(s: i128, u: u128) -> Ordering {
 
 impl PartialEq for FullInt {
     fn eq(&self, other: &Self) -> bool {
-        self.partial_cmp(other)
-            .expect("partial_cmp only returns Some(_)") == Ordering::Equal
+        self.partial_cmp(other).expect("partial_cmp only returns Some(_)") == Ordering::Equal
     }
 }
 
@@ -1599,10 +1760,9 @@ fn cmp(&self, other: &Self) -> Ordering {
     }
 }
 
-
 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
-    use crate::syntax::ast::{IntTy, UintTy};
     use std::*;
+    use syntax::ast::{IntTy, UintTy};
 
     if let ExprKind::Cast(ref cast_exp, _) = expr.node {
         let pre_cast_ty = cx.tables.expr_ty(cast_exp);
@@ -1613,7 +1773,10 @@ fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) ->
         }
         match pre_cast_ty.sty {
             ty::Int(int_ty) => Some(match int_ty {
-                IntTy::I8 => (FullInt::S(i128::from(i8::min_value())), FullInt::S(i128::from(i8::max_value()))),
+                IntTy::I8 => (
+                    FullInt::S(i128::from(i8::min_value())),
+                    FullInt::S(i128::from(i8::max_value())),
+                ),
                 IntTy::I16 => (
                     FullInt::S(i128::from(i16::min_value())),
                     FullInt::S(i128::from(i16::max_value())),
@@ -1627,10 +1790,16 @@ fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) ->
                     FullInt::S(i128::from(i64::max_value())),
                 ),
                 IntTy::I128 => (FullInt::S(i128::min_value()), FullInt::S(i128::max_value())),
-                IntTy::Isize => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)),
+                IntTy::Isize => (
+                    FullInt::S(isize::min_value() as i128),
+                    FullInt::S(isize::max_value() as i128),
+                ),
             }),
             ty::Uint(uint_ty) => Some(match uint_ty {
-                UintTy::U8 => (FullInt::U(u128::from(u8::min_value())), FullInt::U(u128::from(u8::max_value()))),
+                UintTy::U8 => (
+                    FullInt::U(u128::from(u8::min_value())),
+                    FullInt::U(u128::from(u8::max_value())),
+                ),
                 UintTy::U16 => (
                     FullInt::U(u128::from(u16::min_value())),
                     FullInt::U(u128::from(u16::max_value())),
@@ -1644,7 +1813,10 @@ fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) ->
                     FullInt::U(u128::from(u64::max_value())),
                 ),
                 UintTy::U128 => (FullInt::U(u128::min_value()), FullInt::U(u128::max_value())),
-                UintTy::Usize => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
+                UintTy::Usize => (
+                    FullInt::U(usize::min_value() as u128),
+                    FullInt::U(usize::max_value() as u128),
+                ),
             }),
             _ => None,
         }
@@ -1699,29 +1871,37 @@ fn upcast_comparison_bounds_err<'a, 'tcx>(
                     err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
                 }
             } else if match rel {
-                Rel::Lt => if invert {
-                    norm_rhs_val < lb
-                } else {
-                    ub < norm_rhs_val
+                Rel::Lt => {
+                    if invert {
+                        norm_rhs_val < lb
+                    } else {
+                        ub < norm_rhs_val
+                    }
                 },
-                Rel::Le => if invert {
-                    norm_rhs_val <= lb
-                } else {
-                    ub <= norm_rhs_val
+                Rel::Le => {
+                    if invert {
+                        norm_rhs_val <= lb
+                    } else {
+                        ub <= norm_rhs_val
+                    }
                 },
                 Rel::Eq | Rel::Ne => unreachable!(),
             } {
                 err_upcast_comparison(cx, span, lhs, true)
             } else if match rel {
-                Rel::Lt => if invert {
-                    norm_rhs_val >= ub
-                } else {
-                    lb >= norm_rhs_val
+                Rel::Lt => {
+                    if invert {
+                        norm_rhs_val >= ub
+                    } else {
+                        lb >= norm_rhs_val
+                    }
                 },
-                Rel::Le => if invert {
-                    norm_rhs_val > ub
-                } else {
-                    lb > norm_rhs_val
+                Rel::Le => {
+                    if invert {
+                        norm_rhs_val > ub
+                    } else {
+                        lb > norm_rhs_val
+                    }
                 },
                 Rel::Eq | Rel::Ne => unreachable!(),
             } {
@@ -1779,12 +1959,16 @@ impl LintPass for ImplicitHasher {
     fn get_lints(&self) -> LintArray {
         lint_array!(IMPLICIT_HASHER)
     }
+
+    fn name(&self) -> &'static str {
+        "ImplicitHasher"
+    }
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
     #[allow(clippy::cast_possible_truncation)]
     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
-        use crate::syntax_pos::BytePos;
+        use syntax_pos::BytePos;
 
         fn suggestion<'a, 'tcx>(
             cx: &LateContext<'a, 'tcx>,
@@ -1857,7 +2041,7 @@ fn suggestion<'a, 'tcx>(
                     });
 
                     let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
-                    for item in items.iter().map(|item| cx.tcx.hir.impl_item(item.id)) {
+                    for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
                         ctr_vis.visit_impl_item(item);
                     }
 
@@ -1865,7 +2049,10 @@ fn suggestion<'a, 'tcx>(
                         cx,
                         IMPLICIT_HASHER,
                         target.span(),
-                        &format!("impl for `{}` should be generalized over different hashers", target.type_name()),
+                        &format!(
+                            "impl for `{}` should be generalized over different hashers",
+                            target.type_name()
+                        ),
                         move |db| {
                             suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
                         },
@@ -1873,7 +2060,7 @@ fn suggestion<'a, 'tcx>(
                 }
             },
             ItemKind::Fn(ref decl, .., ref generics, body_id) => {
-                let body = cx.tcx.hir.body(body_id);
+                let body = cx.tcx.hir().body(body_id);
 
                 for ty in &decl.inputs {
                     let mut vis = ImplicitHasherTypeVisitor::new(cx);
@@ -1922,11 +2109,19 @@ impl<'tcx> ImplicitHasherType<'tcx> {
     /// Checks that `ty` is a target type without a BuildHasher.
     fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty) -> Option<Self> {
         if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.node {
-            let params: Vec<_> = path.segments.last().as_ref()?.args.as_ref()?
-                .args.iter().filter_map(|arg| match arg {
+            let params: Vec<_> = path
+                .segments
+                .last()
+                .as_ref()?
+                .args
+                .as_ref()?
+                .args
+                .iter()
+                .filter_map(|arg| match arg {
                     GenericArg::Type(ty) => Some(ty),
                     GenericArg::Lifetime(_) => None,
-                }).collect();
+                })
+                .collect();
             let params_len = params.len();
 
             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
@@ -1939,7 +2134,11 @@ fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty) -> Option<Self> {
                     snippet(cx, params[1].span, "V"),
                 ))
             } else if match_path(path, &paths::HASHSET) && params_len == 1 {
-                Some(ImplicitHasherType::HashSet(hir_ty.span, ty, snippet(cx, params[0].span, "T")))
+                Some(ImplicitHasherType::HashSet(
+                    hir_ty.span,
+                    ty,
+                    snippet(cx, params[0].span, "T"),
+                ))
             } else {
                 None
             }
@@ -2069,6 +2268,71 @@ fn visit_expr(&mut self, e: &'tcx Expr) {
     }
 
     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
-        NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir)
+        NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
+    }
+}
+
+/// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
+///
+/// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
+/// `UnsafeCell` is the only way to obtain aliasable data that is considered
+/// mutable.
+///
+/// **Known problems:** None.
+///
+/// **Example:**
+/// ```rust
+/// fn x(r: &i32) {
+///     unsafe {
+///         *(r as *const _ as *mut _) += 1;
+///     }
+/// }
+/// ```
+///
+/// Instead consider using interior mutability types.
+///
+/// ```rust
+/// fn x(r: &UnsafeCell<i32>) {
+///     unsafe {
+///         *r.get() += 1;
+///     }
+/// }
+/// ```
+declare_clippy_lint! {
+    pub CAST_REF_TO_MUT,
+    correctness,
+    "a cast of reference to a mutable pointer"
+}
+
+pub struct RefToMut;
+
+impl LintPass for RefToMut {
+    fn get_lints(&self) -> LintArray {
+        lint_array!(CAST_REF_TO_MUT)
+    }
+
+    fn name(&self) -> &'static str {
+        "RefToMut"
+    }
+}
+
+impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
+    fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
+        if_chain! {
+            if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.node;
+            if let ExprKind::Cast(e, t) = &e.node;
+            if let TyKind::Ptr(MutTy { mutbl: Mutability::MutMutable, .. }) = t.node;
+            if let ExprKind::Cast(e, t) = &e.node;
+            if let TyKind::Ptr(MutTy { mutbl: Mutability::MutImmutable, .. }) = t.node;
+            if let ty::Ref(..) = cx.tables.node_id_to_type(e.hir_id).sty;
+            then {
+                span_lint(
+                    cx,
+                    CAST_REF_TO_MUT,
+                    expr.span,
+                    "casting &T to &mut T may cause undefined behaviour, consider instead using an UnsafeCell",
+                );
+            }
+        }
     }
 }