X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=clippy_lints%2Fsrc%2Fneedless_pass_by_value.rs;h=060037ed496910f714e114d130bf25b9f0af1f93;hb=93cc616a3eba891dc917243466c28647edfeff97;hp=57fd03f4e12a68afd6fc8b322cd0b69cf7d599db;hpb=a9e9b7f9b2ad52035fe7b57bb0fc8ba62d649c33;p=rust.git diff --git a/clippy_lints/src/needless_pass_by_value.rs b/clippy_lints/src/needless_pass_by_value.rs index 57fd03f4e12..060037ed496 100644 --- a/clippy_lints/src/needless_pass_by_value.rs +++ b/clippy_lints/src/needless_pass_by_value.rs @@ -6,14 +6,16 @@ use if_chain::if_chain; use rustc_ast::ast::Attribute; use rustc_data_structures::fx::FxHashSet; -use rustc_errors::{Applicability, DiagnosticBuilder}; +use rustc_errors::{Applicability, Diagnostic}; use rustc_hir::intravisit::FnKind; -use rustc_hir::{BindingAnnotation, Body, FnDecl, GenericArg, HirId, Impl, ItemKind, Node, PatKind, QPath, TyKind}; +use rustc_hir::{ + BindingAnnotation, Body, FnDecl, GenericArg, HirId, Impl, ItemKind, Mutability, Node, PatKind, QPath, TyKind, +}; use rustc_hir::{HirIdMap, HirIdSet}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::FakeReadCause; -use rustc_middle::ty::{self, TypeFoldable}; +use rustc_middle::ty::{self, TypeVisitable}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::kw; use rustc_span::{sym, Span}; @@ -24,20 +26,22 @@ use std::borrow::Cow; declare_clippy_lint! { - /// **What it does:** Checks for functions taking arguments by value, but not + /// ### What it does + /// Checks for functions taking arguments by value, but not /// consuming them in its /// body. /// - /// **Why is this bad?** Taking arguments by reference is more flexible and can + /// ### Why is this bad? + /// Taking arguments by reference is more flexible and can /// sometimes avoid /// unnecessary allocations. /// - /// **Known problems:** + /// ### Known problems /// * This lint suggests taking an argument by reference, /// however sometimes it is better to let users decide the argument type /// (by using `Borrow` trait, for example), depending on how the function is used. /// - /// **Example:** + /// ### Example /// ```rust /// fn foo(v: Vec) { /// assert_eq!(v.len(), 42); @@ -49,6 +53,7 @@ /// assert_eq!(v.len(), 42); /// } /// ``` + #[clippy::version = "pre 1.29.0"] pub NEEDLESS_PASS_BY_VALUE, pedantic, "functions taking arguments by value, but not consuming them in its body" @@ -67,7 +72,7 @@ macro_rules! need { } impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { - #[allow(clippy::too_many_lines)] + #[expect(clippy::too_many_lines)] fn check_fn( &mut self, cx: &LateContext<'tcx>, @@ -82,7 +87,7 @@ fn check_fn( } match kind { - FnKind::ItemFn(.., header, _) => { + FnKind::ItemFn(.., header) => { let attrs = cx.tcx.hir().attrs(hir_id); if header.abi != Abi::Rust || requires_exact_signature(attrs) { return; @@ -103,7 +108,6 @@ 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 allowed_traits = [ need!(cx.tcx.lang_items().fn_trait()), need!(cx.tcx.lang_items().fn_once_trait()), @@ -120,7 +124,7 @@ fn check_fn( .filter_map(|obligation| { // Note that we do not want to deal with qualified predicates here. match obligation.predicate.kind().no_bound_vars() { - Some(ty::PredicateKind::Trait(pred, _)) if pred.def_id() != sized_trait => Some(pred), + Some(ty::PredicateKind::Trait(pred)) if pred.def_id() != sized_trait => Some(pred), _ => None, } }) @@ -167,9 +171,9 @@ fn check_fn( let preds = preds.iter().filter(|t| t.self_ty() == ty).collect::>(); ( - preds.iter().any(|t| t.def_id() == borrow_trait), + preds.iter().any(|t| cx.tcx.is_diagnostic_item(sym::Borrow, t.def_id())), !preds.is_empty() && { - let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty); + let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_erased, ty); preds.iter().all(|t| { let ty_params = t.trait_ref.substs.iter().skip(1).collect::>(); implements_trait(cx, ty_empty_region, t.def_id(), &ty_params) @@ -186,18 +190,19 @@ fn check_fn( if !implements_borrow_trait; if !all_borrowable_trait; - if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.kind; + if let PatKind::Binding(BindingAnnotation(_, Mutability::Not), canonical_id, ..) = arg.pat.kind; if !moved_vars.contains(&canonical_id); then { - if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut { - continue; - } - // Dereference suggestion - let sugg = |diag: &mut DiagnosticBuilder<'_>| { + let sugg = |diag: &mut Diagnostic| { 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() { + if let Some(span) = cx.tcx.hir().span_if_local(def.did()) { + if can_type_implement_copy( + cx.tcx, + cx.param_env, + ty, + traits::ObligationCause::dummy_with_span(span), + ).is_ok() { diag.span_help(span, "consider marking this type as `Copy`"); } } @@ -205,7 +210,7 @@ fn check_fn( let deref_span = spans_need_deref.get(&canonical_id); if_chain! { - if is_type_diagnostic_item(cx, ty, sym::vec_type); + if is_type_diagnostic_item(cx, ty, sym::Vec); if let Some(clone_spans) = get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]); if let TyKind::Path(QPath::Resolved(_, path)) = input.kind; @@ -228,12 +233,13 @@ fn check_fn( for (span, suggestion) in clone_spans { diag.span_suggestion( span, - &snippet_opt(cx, span) + snippet_opt(cx, span) .map_or( "change the call to".into(), |x| Cow::from(format!("change `{}` to", x)), - ), - suggestion.into(), + ) + .as_ref(), + suggestion, Applicability::Unspecified, ); } @@ -244,25 +250,26 @@ fn check_fn( } } - if is_type_diagnostic_item(cx, ty, sym::string_type) { + if is_type_diagnostic_item(cx, ty, sym::String) { if let Some(clone_spans) = get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) { diag.span_suggestion( input.span, "consider changing the type to", - "&str".to_string(), + "&str", Applicability::Unspecified, ); for (span, suggestion) in clone_spans { diag.span_suggestion( span, - &snippet_opt(cx, span) + snippet_opt(cx, span) .map_or( "change the call to".into(), |x| Cow::from(format!("change `{}` to", x)) - ), - suggestion.into(), + ) + .as_ref(), + suggestion, Applicability::Unspecified, ); } @@ -334,5 +341,5 @@ fn borrow(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId) {} - fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {} + fn fake_read(&mut self, _: &rustc_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} }