]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/needless_pass_by_value.rs
clippy
[rust.git] / clippy_lints / src / needless_pass_by_value.rs
index b23e26b7558621baf2f5bbab4a39cd5f548a7046..e39fb23365a27a9cadb3c29d48d619529895f2ee 100644 (file)
@@ -1,24 +1,24 @@
 use crate::utils::ptr::get_spans;
 use crate::utils::{
-    get_trait_def_id, implements_trait, is_copy, is_self, is_type_diagnostic_item, match_type, multispan_sugg, paths,
-    snippet, snippet_opt, span_lint_and_then,
+    get_trait_def_id, implements_trait, is_copy, is_self, is_type_diagnostic_item, multispan_sugg, paths, snippet,
+    snippet_opt, span_lint_and_then,
 };
 use if_chain::if_chain;
-use matches::matches;
-use rustc::traits;
-use rustc::traits::misc::can_type_implement_copy;
-use rustc::ty::{self, RegionKind, TypeFoldable};
+use rustc_ast::ast::Attribute;
 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
 use rustc_errors::{Applicability, DiagnosticBuilder};
 use rustc_hir::intravisit::FnKind;
-use rustc_hir::*;
+use rustc_hir::{BindingAnnotation, Body, FnDecl, GenericArg, HirId, ItemKind, Node, PatKind, QPath, TyKind};
+use rustc_infer::infer::TyCtxtInferExt;
 use rustc_lint::{LateContext, LateLintPass};
+use rustc_middle::ty::{self, TypeFoldable};
 use rustc_session::{declare_lint_pass, declare_tool_lint};
-use rustc_span::{Span, Symbol};
+use rustc_span::Span;
 use rustc_target::spec::abi::Abi;
+use rustc_trait_selection::traits;
+use rustc_trait_selection::traits::misc::can_type_implement_copy;
 use rustc_typeck::expr_use_visitor as euv;
 use std::borrow::Cow;
-use syntax::ast::Attribute;
 
 declare_clippy_lint! {
     /// **What it does:** Checks for functions taking arguments by value, but not
@@ -64,11 +64,11 @@ macro_rules! need {
     };
 }
 
-impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
+impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue {
     #[allow(clippy::too_many_lines)]
     fn check_fn(
         &mut self,
-        cx: &LateContext<'a, 'tcx>,
+        cx: &LateContext<'tcx>,
         kind: FnKind<'tcx>,
         decl: &'tcx FnDecl<'_>,
         body: &'tcx Body<'_>,
@@ -86,7 +86,7 @@ fn check_fn(
                 }
             },
             FnKind::Method(..) => (),
-            _ => return,
+            FnKind::Closure(..) => return,
         }
 
         // Exclude non-inherent impls
@@ -100,7 +100,7 @@ fn check_fn(
 
         // Allow `Borrow` or functions to be taken by value
         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
-        let whitelisted_traits = [
+        let allowed_traits = [
             need!(cx.tcx.lang_items().fn_trait()),
             need!(cx.tcx.lang_items().fn_once_trait()),
             need!(cx.tcx.lang_items().fn_mut_trait()),
@@ -111,15 +111,15 @@ fn check_fn(
 
         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
 
-        let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
+        let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds().iter())
             .filter(|p| !p.is_global())
-            .filter_map(|pred| {
-                if let ty::Predicate::Trait(poly_trait_ref, _) = pred {
-                    if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_bound_vars()
-                    {
+            .filter_map(|obligation| {
+                // Note that we do not want to deal with qualified predicates here.
+                if let ty::PredicateKind::Trait(pred, _) = obligation.predicate.kind() {
+                    if pred.def_id() == sized_trait {
                         return None;
                     }
-                    Some(poly_trait_ref)
+                    Some(pred)
                 } else {
                     None
                 }
@@ -135,7 +135,8 @@ fn check_fn(
         } = {
             let mut ctx = MovedVariablesCtxt::default();
             cx.tcx.infer_ctxt().enter(|infcx| {
-                euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.tables).consume_body(body);
+                euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
+                    .consume_body(body);
             });
             ctx
         };
@@ -158,30 +159,29 @@ fn check_fn(
                 }
             }
 
-            //
             // * Exclude a type that is specifically bounded by `Borrow`.
             // * Exclude a type whose reference also fulfills its bound. (e.g., `std::convert::AsRef`,
             //   `serde::Serialize`)
             let (implements_borrow_trait, all_borrowable_trait) = {
                 let preds = preds
                     .iter()
-                    .filter(|t| t.skip_binder().self_ty() == ty)
+                    .filter(|t| t.self_ty() == ty)
                     .collect::<Vec<_>>();
 
                 (
                     preds.iter().any(|t| t.def_id() == borrow_trait),
-                    !preds.is_empty()
-                        && preds.iter().all(|t| {
-                            let ty_params = &t
-                                .skip_binder()
+                    !preds.is_empty() && {
+                        let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty);
+                        preds.iter().all(|t| {
+                            let ty_params = t
                                 .trait_ref
                                 .substs
                                 .iter()
                                 .skip(1)
-                                .cloned()
                                 .collect::<Vec<_>>();
-                            implements_trait(cx, cx.tcx.mk_imm_ref(&RegionKind::ReEmpty, ty), t.def_id(), ty_params)
-                        }),
+                            implements_trait(cx, ty_empty_region, t.def_id(), &ty_params)
+                        })
+                    },
                 )
             };
 
@@ -189,7 +189,7 @@ fn check_fn(
                 if !is_self(arg);
                 if !ty.is_mutable_ptr();
                 if !is_copy(cx, ty);
-                if !whitelisted_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
+                if !allowed_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
                 if !implements_borrow_trait;
                 if !all_borrowable_trait;
 
@@ -201,18 +201,18 @@ fn check_fn(
                     }
 
                     // Dereference suggestion
-                    let sugg = |db: &mut DiagnosticBuilder<'_>| {
+                    let sugg = |diag: &mut DiagnosticBuilder<'_>| {
                         if let ty::Adt(def, ..) = ty.kind {
                             if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
                                 if can_type_implement_copy(cx.tcx, cx.param_env, ty).is_ok() {
-                                    db.span_help(span, "consider marking this type as `Copy`");
+                                    diag.span_help(span, "consider marking this type as `Copy`");
                                 }
                             }
                         }
 
                         let deref_span = spans_need_deref.get(&canonical_id);
                         if_chain! {
-                            if is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type"));
+                            if is_type_diagnostic_item(cx, ty, sym!(vec_type));
                             if let Some(clone_spans) =
                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
                             if let TyKind::Path(QPath::Resolved(_, ref path)) = input.kind;
@@ -225,7 +225,7 @@ fn check_fn(
                                 }).unwrap());
                             then {
                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
-                                db.span_suggestion(
+                                diag.span_suggestion(
                                     input.span,
                                     "consider changing the type to",
                                     slice_ty,
@@ -233,7 +233,7 @@ fn check_fn(
                                 );
 
                                 for (span, suggestion) in clone_spans {
-                                    db.span_suggestion(
+                                    diag.span_suggestion(
                                         span,
                                         &snippet_opt(cx, span)
                                             .map_or(
@@ -251,10 +251,10 @@ fn check_fn(
                             }
                         }
 
-                        if match_type(cx, ty, &paths::STRING) {
+                        if is_type_diagnostic_item(cx, ty, sym!(string_type)) {
                             if let Some(clone_spans) =
                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
-                                db.span_suggestion(
+                                diag.span_suggestion(
                                     input.span,
                                     "consider changing the type to",
                                     "&str".to_string(),
@@ -262,7 +262,7 @@ fn check_fn(
                                 );
 
                                 for (span, suggestion) in clone_spans {
-                                    db.span_suggestion(
+                                    diag.span_suggestion(
                                         span,
                                         &snippet_opt(cx, span)
                                             .map_or(
@@ -291,7 +291,7 @@ fn check_fn(
                             );
                             spans.sort_by_key(|&(span, _)| span);
                         }
-                        multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
+                        multispan_sugg(diag, "consider taking a reference instead", spans);
                     };
 
                     span_lint_and_then(
@@ -325,21 +325,21 @@ struct MovedVariablesCtxt {
 }
 
 impl MovedVariablesCtxt {
-    fn move_common(&mut self, cmt: &euv::Place<'_>) {
-        if let euv::PlaceBase::Local(vid) = cmt.base {
+    fn move_common(&mut self, cmt: &euv::PlaceWithHirId<'_>) {
+        if let euv::PlaceBase::Local(vid) = cmt.place.base {
             self.moved_vars.insert(vid);
         }
     }
 }
 
 impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt {
-    fn consume(&mut self, cmt: &euv::Place<'tcx>, mode: euv::ConsumeMode) {
+    fn consume(&mut self, cmt: &euv::PlaceWithHirId<'tcx>, mode: euv::ConsumeMode) {
         if let euv::ConsumeMode::Move = mode {
             self.move_common(cmt);
         }
     }
 
-    fn borrow(&mut self, _: &euv::Place<'tcx>, _: ty::BorrowKind) {}
+    fn borrow(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: ty::BorrowKind) {}
 
-    fn mutate(&mut self, _: &euv::Place<'tcx>) {}
+    fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>) {}
 }