]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/methods.rs
Merge branch 'macro-use' into HEAD
[rust.git] / clippy_lints / src / methods.rs
index 8a92e49340f4e3f60d7f1899330144d6b6683fb3..3ebad1d705b940ecae8750ab3341f3390470f2d7 100644 (file)
@@ -1,22 +1,22 @@
+use matches::matches;
 use rustc::hir;
 use rustc::lint::*;
-use rustc::middle::const_val::ConstVal;
+use rustc::{declare_lint, lint_array};
+use if_chain::if_chain;
 use rustc::ty::{self, Ty};
 use rustc::hir::def::Def;
-use rustc::ty::subst::Substs;
-use rustc_const_eval::ConstContext;
 use std::borrow::Cow;
 use std::fmt;
 use std::iter;
 use syntax::ast;
-use syntax::codemap::Span;
-use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_self, is_self_ty,
-            iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
-            match_type, method_chain_args, return_ty, same_tys, single_segment_path, snippet, span_lint,
-            span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
-use utils::paths;
-use utils::sugg;
-use utils::const_to_u64;
+use syntax::codemap::{Span, BytePos};
+use crate::utils::{get_arg_name, get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_expn_of, is_self,
+            is_self_ty, iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
+            match_type, method_chain_args, match_var, return_ty, remove_blocks, same_tys, single_segment_path, snippet,
+            span_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq};
+use crate::utils::paths;
+use crate::utils::sugg;
+use crate::consts::{constant, Constant};
 
 #[derive(Clone)]
 pub struct Pass;
@@ -34,9 +34,9 @@
 /// ```rust
 /// x.unwrap()
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub OPTION_UNWRAP_USED,
-    Allow,
+    restriction,
     "using `Option.unwrap()`, which should at least get a better message using `expect()`"
 }
 
@@ -56,9 +56,9 @@
 /// ```rust
 /// x.unwrap()
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub RESULT_UNWRAP_USED,
-    Allow,
+    restriction,
     "using `Result.unwrap()`, which might be better handled"
 }
 
@@ -82,9 +82,9 @@
 ///    fn add(&self, other: &X) -> X { .. }
 /// }
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub SHOULD_IMPLEMENT_TRAIT,
-    Warn,
+    style,
     "defining a method that should be implementing a std trait"
 }
 
 ///     fn as_str(self) -> &str { .. }
 /// }
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub WRONG_SELF_CONVENTION,
-    Warn,
+    style,
     "defining a method named with an established prefix (like \"into_\") that takes \
      `self` with the wrong convention"
 }
 ///     pub fn as_str(self) -> &str { .. }
 /// }
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub WRONG_PUB_SELF_CONVENTION,
-    Allow,
+    restriction,
     "defining a public method named with an established prefix (like \"into_\") that takes \
      `self` with the wrong convention"
 }
 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
 /// directly to get a better error message.
 ///
-/// **Known problems:** None.
+/// **Known problems:** The error type needs to implement `Debug`
 ///
 /// **Example:**
 /// ```rust
 /// x.ok().expect("why did I do this again?")
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub OK_EXPECT,
-    Warn,
+    style,
     "using `ok().expect()`, which gives worse error messages than \
      calling `expect` directly on the Result"
 }
 /// **Why is this bad?** Readability, this can be written more concisely as
 /// `_.map_or(_, _)`.
 ///
-/// **Known problems:** None.
+/// **Known problems:** The order of the arguments is not in execution order
 ///
 /// **Example:**
 /// ```rust
 /// x.map(|a| a + 1).unwrap_or(0)
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub OPTION_MAP_UNWRAP_OR,
-    Allow,
+    pedantic,
     "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
      `map_or(a, f)`"
 }
 /// **Why is this bad?** Readability, this can be written more concisely as
 /// `_.map_or_else(_, _)`.
 ///
-/// **Known problems:** None.
+/// **Known problems:** The order of the arguments is not in execution order.
 ///
 /// **Example:**
 /// ```rust
 /// x.map(|a| a + 1).unwrap_or_else(some_function)
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub OPTION_MAP_UNWRAP_OR_ELSE,
-    Allow,
+    pedantic,
     "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
      `map_or_else(g, f)`"
 }
 /// ```rust
 /// x.map(|a| a + 1).unwrap_or_else(some_function)
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub RESULT_MAP_UNWRAP_OR_ELSE,
-    Allow,
+    pedantic,
     "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
      `.ok().map_or_else(g, f)`"
 }
 /// **Why is this bad?** Readability, this can be written more concisely as
 /// `_.and_then(_)`.
 ///
-/// **Known problems:** None.
+/// **Known problems:** The order of the arguments is not in execution order.
 ///
 /// **Example:**
 /// ```rust
 /// opt.map_or(None, |a| a + 1)
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub OPTION_MAP_OR_NONE,
-    Warn,
+    style,
     "using `Option.map_or(None, f)`, which is more succinctly expressed as \
      `and_then(f)`"
 }
 /// ```rust
 /// iter.filter(|x| x == 0).next()
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub FILTER_NEXT,
-    Warn,
+    complexity,
     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
 }
 
 /// ```rust
 /// iter.filter(|x| x == 0).map(|x| x * 2)
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub FILTER_MAP,
-    Allow,
+    pedantic,
     "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can \
      usually be written as a single method call"
 }
 /// ```rust
 /// iter.find(|x| x == 0).is_some()
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub SEARCH_IS_SOME,
-    Warn,
+    complexity,
     "using an iterator search followed by `is_some()`, which is more succinctly \
      expressed as a call to `any()`"
 }
 /// ```rust
 /// name.chars().next() == Some('_')
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub CHARS_NEXT_CMP,
-    Warn,
+    complexity,
     "using `.chars().next()` to check if a string starts with a char"
 }
 
 /// ```rust
 /// foo.unwrap_or_default()
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub OR_FUN_CALL,
-    Warn,
+    perf,
     "using any `*or` method with a function call, which suggests `*or_else`"
 }
 
+/// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
+/// etc., and suggests to use `unwrap_or_else` instead
+///
+/// **Why is this bad?** The function will always be called.
+///
+/// **Known problems:** If the function has side-effects, not calling it will
+/// change the semantic of the program, but you shouldn't rely on that anyway.
+///
+/// **Example:**
+/// ```rust
+/// foo.expect(&format("Err {}: {}", err_code, err_msg))
+/// ```
+/// or
+/// ```rust
+/// foo.expect(format("Err {}: {}", err_code, err_msg).as_str())
+/// ```
+/// this can instead be written:
+/// ```rust
+/// foo.unwrap_or_else(|_| panic!("Err {}: {}", err_code, err_msg))
+/// ```
+/// or
+/// ```rust
+/// foo.unwrap_or_else(|_| panic!(format("Err {}: {}", err_code, err_msg).as_str()))
+/// ```
+declare_clippy_lint! {
+    pub EXPECT_FUN_CALL,
+    perf,
+    "using any `expect` method with a function call"
+}
+
 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
 ///
 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
 /// ```rust
 /// 42u64.clone()
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub CLONE_ON_COPY,
-    Warn,
+    complexity,
     "using `clone` on a `Copy` type"
 }
 
 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
-/// (Rc, Arc, rc::Weak, or sync::Weak), and suggests calling Clone on
-/// the corresponding trait instead.
+/// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
+/// function syntax instead (e.g. `Rc::clone(foo)`).
 ///
 /// **Why is this bad?**: Calling '.clone()' on an Rc, Arc, or Weak
 /// can obscure the fact that only the pointer is being cloned, not the underlying
 /// ```rust
 /// x.clone()
 /// ```
-declare_restriction_lint! {
+declare_clippy_lint! {
     pub CLONE_ON_REF_PTR,
+    restriction,
     "using 'clone' on a ref-counted pointer"
 }
 
 ///    println!("{:p} {:p}",*y, z); // prints out the same pointer
 /// }
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub CLONE_DOUBLE_REF,
-    Warn,
+    correctness,
     "using `clone` on `&&T`"
 }
 
 ///     }
 /// }
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub NEW_RET_NO_SELF,
-    Warn,
+    style,
     "not returning `Self` in a `new` method"
 }
 
 ///
 /// **Example:**
 /// `_.split("x")` could be `_.split('x')
-declare_lint! {
+declare_clippy_lint! {
     pub SINGLE_CHAR_PATTERN,
-    Warn,
+    perf,
     "using a single-character str where a char could be used, e.g. \
      `_.split(\"x\")`"
 }
 ///     call_some_ffi_func(c_str.as_ptr());
 /// }
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub TEMPORARY_CSTRING_AS_PTR,
-    Warn,
+    correctness,
     "getting the inner pointer of a temporary `CString`"
 }
 
 /// let bad_vec = some_vec.get(3);
 /// let bad_slice = &some_vec[..].get(3);
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub ITER_NTH,
-    Warn,
+    perf,
     "using `.iter().nth()` on a standard library type with O(1) element access"
 }
 
 /// let bad_vec = some_vec.iter().nth(3);
 /// let bad_slice = &some_vec[..].iter().nth(3);
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub ITER_SKIP_NEXT,
-    Warn,
+    style,
     "using `.skip(x).next()` on an iterator"
 }
 
 /// let last = some_vec[3];
 /// some_vec[0] = 1;
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub GET_UNWRAP,
-    Warn,
+    style,
     "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
 }
 
 /// s.push_str(abc);
 /// s.push_str(&def));
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub STRING_EXTEND_CHARS,
-    Warn,
+    style,
     "using `x.extend(s.chars())` where s is a `&str` or `String`"
 }
 
 /// let s = [1,2,3,4,5];
 /// let s2 : Vec<isize> = s.to_vec();
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub ITER_CLONED_COLLECT,
-    Warn,
+    style,
     "using `.cloned().collect()` on slice to create a `Vec`"
 }
 
 /// ```rust
 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub CHARS_LAST_CMP,
-    Warn,
+    style,
     "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
 }
 
 /// let x: &[i32] = &[1,2,3,4,5];
 /// do_stuff(x);
 /// ```
-declare_lint! {
+declare_clippy_lint! {
     pub USELESS_ASREF,
-    Warn,
+    complexity,
     "using `as_ref` where the types before and after the call are the same"
 }
 
+
+/// **What it does:** Checks for using `fold` when a more succinct alternative exists.
+/// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
+/// `sum` or `product`.
+///
+/// **Why is this bad?** Readability.
+///
+/// **Known problems:** None.
+///
+/// **Example:**
+/// ```rust
+/// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
+/// ```
+/// This could be written as:
+/// ```rust
+/// let _ = (0..3).any(|x| x > 2);
+/// ```
+declare_clippy_lint! {
+    pub UNNECESSARY_FOLD,
+    style,
+    "using `fold` when a more succinct alternative exists"
+}
+
 impl LintPass for Pass {
     fn get_lints(&self) -> LintArray {
         lint_array!(
@@ -636,6 +690,7 @@ fn get_lints(&self) -> LintArray {
             RESULT_MAP_UNWRAP_OR_ELSE,
             OPTION_MAP_OR_NONE,
             OR_FUN_CALL,
+            EXPECT_FUN_CALL,
             CHARS_NEXT_CMP,
             CHARS_LAST_CMP,
             CLONE_ON_COPY,
@@ -652,22 +707,21 @@ fn get_lints(&self) -> LintArray {
             GET_UNWRAP,
             STRING_EXTEND_CHARS,
             ITER_CLONED_COLLECT,
-            USELESS_ASREF
+            USELESS_ASREF,
+            UNNECESSARY_FOLD
         )
     }
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
-    #[allow(unused_attributes)]
-    // ^ required because `cyclomatic_complexity` attribute shows up as unused
-    #[cyclomatic_complexity = "30"]
+    #[allow(cyclomatic_complexity)]
     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
         if in_macro(expr.span) {
             return;
         }
 
         match expr.node {
-            hir::ExprMethodCall(ref method_call, _, ref args) => {
+            hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
                 // Chain calls
                 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
                 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
@@ -716,31 +770,34 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
                     lint_asref(cx, expr, "as_ref", arglists[0]);
                 } else if let Some(arglists) = method_chain_args(expr, &["as_mut"]) {
                     lint_asref(cx, expr, "as_mut", arglists[0]);
+                } else if let Some(arglists) = method_chain_args(expr, &["fold"]) {
+                    lint_unnecessary_fold(cx, expr, arglists[0]);
                 }
 
-                lint_or_fun_call(cx, expr, &method_call.name.as_str(), args);
+                lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
+                lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
 
                 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
-                if args.len() == 1 && method_call.name == "clone" {
+                if args.len() == 1 && method_call.ident.name == "clone" {
                     lint_clone_on_copy(cx, expr, &args[0], self_ty);
                     lint_clone_on_ref_ptr(cx, expr, &args[0]);
                 }
 
                 match self_ty.sty {
-                    ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
-                        if method_call.name == method && args.len() > pos {
+                    ty::TyRef(_, ty, _) if ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
+                        if method_call.ident.name == method && args.len() > pos {
                             lint_single_char_pattern(cx, expr, &args[pos]);
                         }
                     },
                     _ => (),
                 }
             },
-            hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
+            hir::ExprKind::Binary(op, ref lhs, ref rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
                 let mut info = BinaryExprInfo {
-                    expr: expr,
+                    expr,
                     chain: lhs,
                     other: rhs,
-                    eq: op.node == hir::BiEq,
+                    eq: op.node == hir::BinOpKind::Eq,
                 };
                 lint_binary_expr_with_method_call(cx, &mut info);
             },
@@ -752,22 +809,22 @@ fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::I
         if in_external_macro(cx, implitem.span) {
             return;
         }
-        let name = implitem.name;
+        let name = implitem.ident.name;
         let parent = cx.tcx.hir.get_parent(implitem.id);
         let item = cx.tcx.hir.expect_item(parent);
         if_chain! {
             if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
             if let Some(first_arg_ty) = sig.decl.inputs.get(0);
             if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next();
-            if let hir::ItemImpl(_, _, _, _, None, ref self_ty, _) = item.node;
+            if let hir::ItemKind::Impl(_, _, _, _, None, ref self_ty, _) = item.node;
             then {
                 if cx.access_levels.is_exported(implitem.id) {
                 // check missing trait implementations
                     for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
                         if name == method_name &&
                         sig.decl.inputs.len() == n_args &&
-                        out_type.matches(&sig.decl.output) &&
-                        self_kind.matches(first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
+                        out_type.matches(cx, &sig.decl.output) &&
+                        self_kind.matches(cx, first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
                             span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
                                 "defining a method called `{}` on this type; consider implementing \
                                 the `{}` trait or choosing a less ambiguous name", name, trait_name));
@@ -784,9 +841,9 @@ fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::I
                         if conv.check(&name.as_str());
                         if !self_kinds
                             .iter()
-                            .any(|k| k.matches(first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics));
+                            .any(|k| k.matches(cx, first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics));
                         then {
-                            let lint = if item.vis == hir::Visibility::Public {
+                            let lint = if item.vis.node.is_pub() {
                                 WRONG_PUB_SELF_CONVENTION
                             } else {
                                 WRONG_SELF_CONVENTION
@@ -819,7 +876,7 @@ fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::I
 }
 
 /// Checks for the `OR_FUN_CALL` lint.
-fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[hir::Expr]) {
+fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
     /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
     fn check_unwrap_or_default(
         cx: &LateContext,
@@ -835,8 +892,8 @@ fn check_unwrap_or_default(
         }
 
         if name == "unwrap_or" {
-            if let hir::ExprPath(ref qpath) = fun.node {
-                let path = &*last_path_segment(qpath).name.as_str();
+            if let hir::ExprKind::Path(ref qpath) = fun.node {
+                let path = &*last_path_segment(qpath).ident.as_str();
 
                 if ["default", "new"].contains(&path) {
                     let arg_ty = cx.tables.expr_ty(arg);
@@ -865,9 +922,11 @@ fn check_unwrap_or_default(
     }
 
     /// Check for `*or(foo())`.
+    #[allow(too_many_arguments)]
     fn check_general_case(
         cx: &LateContext,
         name: &str,
+        method_span: Span,
         fun_span: Span,
         self_expr: &hir::Expr,
         arg: &hir::Expr,
@@ -913,38 +972,138 @@ fn check_general_case(
             (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
             (false, true) => snippet(cx, fun_span, ".."),
         };
-
+        let span_replace_word = method_span.with_hi(span.hi());
         span_lint_and_sugg(
             cx,
             OR_FUN_CALL,
-            span,
+            span_replace_word,
             &format!("use of `{}` followed by a function call", name),
             "try this",
-            format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg),
+            format!("{}_{}({})", name, suffix, sugg),
         );
     }
 
     if args.len() == 2 {
         match args[1].node {
-            hir::ExprCall(ref fun, ref or_args) => {
+            hir::ExprKind::Call(ref fun, ref or_args) => {
                 let or_has_args = !or_args.is_empty();
                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
-                    check_general_case(cx, name, fun.span, &args[0], &args[1], or_has_args, expr.span);
+                    check_general_case(cx, name, method_span, fun.span, &args[0], &args[1], or_has_args, expr.span);
                 }
             },
-            hir::ExprMethodCall(_, span, ref or_args) => {
-                check_general_case(cx, name, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
+            hir::ExprKind::MethodCall(_, span, ref or_args) => {
+                check_general_case(cx, name, method_span, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
             },
             _ => {},
         }
     }
 }
 
+/// Checks for the `EXPECT_FUN_CALL` lint.
+fn lint_expect_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
+    fn extract_format_args(arg: &hir::Expr) -> Option<&hir::HirVec<hir::Expr>> {
+        if let hir::ExprKind::AddrOf(_, ref addr_of) = arg.node {
+            if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = addr_of.node {
+                if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1 {
+                    if let hir::ExprKind::Call(_, ref format_args) = inner_args[0].node {
+                        return Some(format_args);
+                    }
+                }
+            }
+        }
+
+        None
+    }
+
+    fn generate_format_arg_snippet(cx: &LateContext, a: &hir::Expr) -> String {
+        if let hir::ExprKind::AddrOf(_, ref format_arg) = a.node {
+            if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.node {
+                if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.node {
+                    return snippet(cx, format_arg_expr_tup[0].span, "..").into_owned();
+                }
+            }
+        };
+
+        snippet(cx, a.span, "..").into_owned()
+    }
+
+    fn check_general_case(
+        cx: &LateContext,
+        name: &str,
+        method_span: Span,
+        self_expr: &hir::Expr,
+        arg: &hir::Expr,
+        span: Span,
+    ) {
+        if name != "expect" {
+            return;
+        }
+
+        let self_type = cx.tables.expr_ty(self_expr);
+        let known_types = &[&paths::OPTION, &paths::RESULT];
+
+        // if not a known type, return early
+        if known_types.iter().all(|&k| !match_type(cx, self_type, k)) {
+            return;
+        }
+
+        // don't lint for constant values
+        let owner_def = cx.tcx.hir.get_parent_did(arg.id);
+        let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
+        if promotable {
+            return;
+        }
+
+        let closure = if match_type(cx, self_type, &paths::OPTION) { "||" } else { "|_|" };
+        let span_replace_word = method_span.with_hi(span.hi());
+
+        if let Some(format_args) = extract_format_args(arg) {
+            let args_len = format_args.len();
+            let args: Vec<String> = format_args
+                .into_iter()
+                .take(args_len - 1)
+                .map(|a| generate_format_arg_snippet(cx, a))
+                .collect();
+
+            let sugg = args.join(", ");
+
+            span_lint_and_sugg(
+                cx,
+                EXPECT_FUN_CALL,
+                span_replace_word,
+                &format!("use of `{}` followed by a function call", name),
+                "try this",
+                format!("unwrap_or_else({} panic!({}))", closure, sugg),
+            );
+
+            return;
+        }
+
+        let sugg: Cow<_> = snippet(cx, arg.span, "..");
+
+        span_lint_and_sugg(
+            cx,
+            EXPECT_FUN_CALL,
+            span_replace_word,
+            &format!("use of `{}` followed by a function call", name),
+            "try this",
+            format!("unwrap_or_else({} panic!({}))", closure, sugg),
+        );
+    }
+
+    if args.len() == 2 {
+        match args[1].node {
+            hir::ExprKind::Lit(_) => {},
+            _ => check_general_case(cx, name, method_span, &args[0], &args[1], expr.span),
+        }
+    }
+}
+
 /// Checks for the `CLONE_ON_COPY` lint.
 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty) {
     let ty = cx.tables.expr_ty(expr);
-    if let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = arg_ty.sty {
-        if let ty::TyRef(_, ty::TypeAndMut { ty: innermost, .. }) = inner.sty {
+    if let ty::TyRef(_, inner, _) = arg_ty.sty {
+        if let ty::TyRef(_, innermost, _) = inner.sty {
             span_lint_and_then(
                 cx,
                 CLONE_DOUBLE_REF,
@@ -954,7 +1113,7 @@ fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_t
                 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
                     let mut ty = innermost;
                     let mut n = 0;
-                    while let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = ty.sty {
+                    while let ty::TyRef(_, inner, _) = ty.sty {
                         ty = inner;
                         n += 1;
                     }
@@ -977,14 +1136,14 @@ fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_t
                 match cx.tcx.hir.get(parent) {
                     hir::map::NodeExpr(parent) => match parent.node {
                         // &*x is a nop, &x.clone() is not
-                        hir::ExprAddrOf(..) |
+                        hir::ExprKind::AddrOf(..) |
                         // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
-                        hir::ExprMethodCall(..) => return,
+                        hir::ExprKind::MethodCall(..) => return,
                         _ => {},
                     }
                     hir::map::NodeStmt(stmt) => {
-                        if let hir::StmtDecl(ref decl, _) = stmt.node {
-                            if let hir::DeclLocal(ref loc) = decl.node {
+                        if let hir::StmtKind::Decl(ref decl, _) = stmt.node {
+                            if let hir::DeclKind::Local(ref loc) = decl.node {
                                 if let hir::PatKind::Ref(..) = loc.pat.node {
                                     // let ref y = *x borrows x, let ref y = x.clone() does not
                                     return;
@@ -1010,7 +1169,7 @@ fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_t
 }
 
 fn lint_clone_on_ref_ptr(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
-    let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(arg));
+    let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
 
     if let ty::TyAdt(_, subst) = obj_ty.sty {
         let caller_type = if match_type(cx, obj_ty, &paths::RC) {
@@ -1039,7 +1198,7 @@ fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
     let arg = &args[1];
     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
         let target = &arglists[0][0];
-        let (self_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(target));
+        let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
         let ref_str = if self_ty.sty == ty::TyStr {
             ""
         } else if match_type(cx, self_ty, &paths::STRING) {
@@ -1065,7 +1224,7 @@ fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
 }
 
 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
-    let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&args[0]));
+    let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
     if match_type(cx, obj_ty, &paths::STRING) {
         lint_string_extend(cx, expr, args);
     }
@@ -1073,9 +1232,9 @@ fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
 
 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
     if_chain! {
-        if let hir::ExprCall(ref fun, ref args) = new.node;
+        if let hir::ExprKind::Call(ref fun, ref args) = new.node;
         if args.len() == 1;
-        if let hir::ExprPath(ref path) = fun.node;
+        if let hir::ExprKind::Path(ref path) = fun.node;
         if let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id);
         if match_def_path(cx.tcx, did, &paths::CSTRING_NEW);
         then {
@@ -1106,6 +1265,94 @@ fn lint_iter_cloned_collect(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir
     }
 }
 
+fn lint_unnecessary_fold(cx: &LateContext, expr: &hir::Expr, fold_args: &[hir::Expr]) {
+    // Check that this is a call to Iterator::fold rather than just some function called fold
+    if !match_trait_method(cx, expr, &paths::ITERATOR) {
+        return;
+    }
+
+    assert!(fold_args.len() == 3,
+        "Expected fold_args to have three entries - the receiver, the initial value and the closure");
+
+    fn check_fold_with_op(
+        cx: &LateContext,
+        fold_args: &[hir::Expr],
+        op: hir::BinOpKind,
+        replacement_method_name: &str,
+        replacement_has_args: bool) {
+
+        if_chain! {
+            // Extract the body of the closure passed to fold
+            if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].node;
+            let closure_body = cx.tcx.hir.body(body_id);
+            let closure_expr = remove_blocks(&closure_body.value);
+
+            // Check if the closure body is of the form `acc <op> some_expr(x)`
+            if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
+            if bin_op.node == op;
+
+            // Extract the names of the two arguments to the closure
+            if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
+            if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
+
+            if match_var(&*left_expr, first_arg_ident);
+            if replacement_has_args || match_var(&*right_expr, second_arg_ident);
+
+            then {
+                // Span containing `.fold(...)`
+                let next_point = cx.sess().codemap().next_point(fold_args[0].span);
+                let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
+
+                let sugg = if replacement_has_args {
+                    format!(
+                        ".{replacement}(|{s}| {r})",
+                        replacement = replacement_method_name,
+                        s = second_arg_ident,
+                        r = snippet(cx, right_expr.span, "EXPR"),
+                    )
+                } else {
+                    format!(
+                        ".{replacement}()",
+                        replacement = replacement_method_name,
+                    )
+                };
+
+                span_lint_and_sugg(
+                    cx,
+                    UNNECESSARY_FOLD,
+                    fold_span,
+                    // TODO #2371 don't suggest e.g. .any(|x| f(x)) if we can suggest .any(f)
+                    "this `.fold` can be written more succinctly using another method",
+                    "try",
+                    sugg,
+                );
+            }
+        }
+    }
+
+    // Check if the first argument to .fold is a suitable literal
+    match fold_args[1].node {
+        hir::ExprKind::Lit(ref lit) => {
+            match lit.node {
+                ast::LitKind::Bool(false) => check_fold_with_op(
+                    cx, fold_args, hir::BinOpKind::Or, "any", true
+                ),
+                ast::LitKind::Bool(true) => check_fold_with_op(
+                    cx, fold_args, hir::BinOpKind::And, "all", true
+                ),
+                ast::LitKind::Int(0, _) => check_fold_with_op(
+                    cx, fold_args, hir::BinOpKind::Add, "sum", false
+                ),
+                ast::LitKind::Int(1, _) => check_fold_with_op(
+                    cx, fold_args, hir::BinOpKind::Mul, "product", false
+                ),
+                _ => return
+            }
+        }
+        _ => return
+    };
+}
+
 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
     let mut_str = if is_mut { "_mut" } else { "" };
     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
@@ -1187,14 +1434,14 @@ fn may_slice(cx: &LateContext, ty: Ty) -> bool {
             ty::TySlice(_) => true,
             ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
             ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
-            ty::TyArray(_, size) => const_to_u64(size) < 32,
-            ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => may_slice(cx, inner),
+            ty::TyArray(_, size) => size.assert_usize(cx.tcx).expect("array length") < 32,
+            ty::TyRef(_, inner, _) => may_slice(cx, inner),
             _ => false,
         }
     }
 
-    if let hir::ExprMethodCall(ref path, _, ref args) = expr.node {
-        if path.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
+    if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.node {
+        if path.ident.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
             sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
         } else {
             None
@@ -1203,7 +1450,7 @@ fn may_slice(cx: &LateContext, ty: Ty) -> bool {
         match ty.sty {
             ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
             ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
-            ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => if may_slice(cx, inner) {
+            ty::TyRef(_, inner, _) => if may_slice(cx, inner) {
                 sugg::Sugg::hir_opt(cx, expr)
             } else {
                 None
@@ -1215,7 +1462,7 @@ fn may_slice(cx: &LateContext, ty: Ty) -> bool {
 
 /// lint use of `unwrap()` for `Option`s and `Result`s
 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
-    let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&unwrap_args[0]));
+    let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
 
     let mess = if match_type(cx, obj_ty, &paths::OPTION) {
         Some((OPTION_UNWRAP_USED, "an Option", "None"))
@@ -1371,7 +1618,7 @@ fn lint_map_unwrap_or_else<'a, 'tcx>(
 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
     if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
         // check if the first non-self argument to map_or() is None
-        let map_or_arg_is_none = if let hir::Expr_::ExprPath(ref qpath) = map_or_args[1].node {
+        let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].node {
             match_qpath(qpath, &paths::OPTION_NONE)
         } else {
             false
@@ -1546,11 +1793,11 @@ fn lint_chars_cmp<'a, 'tcx>(
 ) -> bool {
     if_chain! {
         if let Some(args) = method_chain_args(info.chain, chain_methods);
-        if let hir::ExprCall(ref fun, ref arg_char) = info.other.node;
+        if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.node;
         if arg_char.len() == 1;
-        if let hir::ExprPath(ref qpath) = fun.node;
+        if let hir::ExprKind::Path(ref qpath) = fun.node;
         if let Some(segment) = single_segment_path(qpath);
-        if segment.name == "Some";
+        if segment.ident.name == "Some";
         then {
             let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
 
@@ -1600,7 +1847,7 @@ fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
 ) -> bool {
     if_chain! {
         if let Some(args) = method_chain_args(info.chain, chain_methods);
-        if let hir::ExprLit(ref lit) = info.other.node;
+        if let hir::ExprKind::Lit(ref lit) = info.other.node;
         if let ast::LitKind::Char(c) = lit.node;
         then {
             span_lint_and_sugg(
@@ -1639,16 +1886,13 @@ fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &
 
 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
-    let parent_item = cx.tcx.hir.get_parent(arg.id);
-    let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
-    let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
-    if let Ok(&ty::Const {
-        val: ConstVal::Str(r),
-        ..
-    }) = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(arg)
-    {
+    if let Some((Constant::Str(r), _)) = constant(cx, cx.tables, arg) {
         if r.len() == 1 {
-            let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
+            let c = r.chars().next().unwrap();
+            let snip = snippet(cx, expr.span, "..");
+            let hint = snip.replace(
+                &format!("\"{}\"", c.escape_default()),
+                &format!("'{}'", c.escape_default()));
             span_lint_and_then(
                 cx,
                 SINGLE_CHAR_PATTERN,
@@ -1789,6 +2033,7 @@ enum SelfKind {
 impl SelfKind {
     fn matches(
         self,
+        cx: &LateContext,
         ty: &hir::Ty,
         arg: &hir::Arg,
         self_ty: &hir::Ty,
@@ -1806,7 +2051,7 @@ fn matches(
         // `Self`, `&mut Self`,
         // and `Box<Self>`, including the equivalent types with `Foo`.
 
-        let is_actually_self = |ty| is_self_ty(ty) || ty == self_ty;
+        let is_actually_self = |ty| is_self_ty(ty) || SpanlessEq::new(cx).eq_ty(ty, self_ty);
         if is_self(arg) {
             match self {
                 SelfKind::Value => is_actually_self(ty),
@@ -1815,7 +2060,7 @@ fn matches(
                         return true;
                     }
                     match ty.node {
-                        hir::TyRptr(_, ref mt_ty) => {
+                        hir::TyKind::Rptr(_, ref mt_ty) => {
                             let mutability_match = if self == SelfKind::Ref {
                                 mt_ty.mutbl == hir::MutImmutable
                             } else {
@@ -1838,8 +2083,8 @@ fn matches(
         }
     }
 
-    fn description(&self) -> &'static str {
-        match *self {
+    fn description(self) -> &'static str {
+        match self {
             SelfKind::Value => "self by value",
             SelfKind::Ref => "self by reference",
             SelfKind::RefMut => "self by mutable reference",
@@ -1850,26 +2095,35 @@ fn description(&self) -> &'static str {
 
 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
     single_segment_ty(ty).map_or(false, |seg| {
-        generics.ty_params().any(|param| {
-            param.name == seg.name && param.bounds.iter().any(|bound| {
-                if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
-                    let path = &ptr.trait_ref.path;
-                    match_path(path, name) && path.segments.last().map_or(false, |s| {
-                        if let Some(ref params) = s.parameters {
-                            if params.parenthesized {
-                                false
+        generics.params.iter().any(|param| match param.kind {
+            hir::GenericParamKind::Type { .. } => {
+                param.name.ident().name == seg.ident.name && param.bounds.iter().any(|bound| {
+                    if let hir::GenericBound::Trait(ref ptr, ..) = *bound {
+                        let path = &ptr.trait_ref.path;
+                        match_path(path, name) && path.segments.last().map_or(false, |s| {
+                            if let Some(ref params) = s.args {
+                                if params.parenthesized {
+                                    false
+                                } else {
+                                    // FIXME(flip1995): messy, improve if there is a better option
+                                    // in the compiler
+                                    let types: Vec<_> = params.args.iter().filter_map(|arg| match arg {
+                                        hir::GenericArg::Type(ty) => Some(ty),
+                                        _ => None,
+                                    }).collect();
+                                    types.len() == 1
+                                        && (is_self_ty(&types[0]) || is_ty(&*types[0], self_ty))
+                                }
                             } else {
-                                params.types.len() == 1
-                                    && (is_self_ty(&params.types[0]) || is_ty(&*params.types[0], self_ty))
+                                false
                             }
-                        } else {
-                            false
-                        }
-                    })
-                } else {
-                    false
-                }
-            })
+                        })
+                    } else {
+                        false
+                    }
+                })
+            },
+            _ => false,
         })
     })
 }
@@ -1877,19 +2131,19 @@ fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Gener
 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
     match (&ty.node, &self_ty.node) {
         (
-            &hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
-            &hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path)),
+            &hir::TyKind::Path(hir::QPath::Resolved(_, ref ty_path)),
+            &hir::TyKind::Path(hir::QPath::Resolved(_, ref self_ty_path)),
         ) => ty_path
             .segments
             .iter()
-            .map(|seg| seg.name)
-            .eq(self_ty_path.segments.iter().map(|seg| seg.name)),
+            .map(|seg| seg.ident.name)
+            .eq(self_ty_path.segments.iter().map(|seg| seg.ident.name)),
         _ => false,
     }
 }
 
 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
-    if let hir::TyPath(ref path) = ty.node {
+    if let hir::TyKind::Path(ref path) = ty.node {
         single_segment_path(path)
     } else {
         None
@@ -1923,20 +2177,21 @@ enum OutType {
 }
 
 impl OutType {
-    fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
+    fn matches(self, cx: &LateContext, ty: &hir::FunctionRetTy) -> bool {
+        let is_unit = |ty: &hir::Ty| SpanlessEq::new(cx).eq_ty_kind(&ty.node, &hir::TyKind::Tup(vec![].into()));
         match (self, ty) {
-            (&OutType::Unit, &hir::DefaultReturn(_)) => true,
-            (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
-            (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
-            (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
-            (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
+            (OutType::Unit, &hir::DefaultReturn(_)) => true,
+            (OutType::Unit, &hir::Return(ref ty)) if is_unit(ty) => true,
+            (OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
+            (OutType::Any, &hir::Return(ref ty)) if !is_unit(ty) => true,
+            (OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyKind::Rptr(_, _)),
             _ => false,
         }
     }
 }
 
 fn is_bool(ty: &hir::Ty) -> bool {
-    if let hir::TyPath(ref p) = ty.node {
+    if let hir::TyKind::Path(ref p) = ty.node {
         match_qpath(p, &["bool"])
     } else {
         false