-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Add fn_param_ref_cloned lint
#17281
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Add fn_param_ref_cloned lint
#17281
Changes from all commits
9575f3d
baf03af
62d9003
df73be9
48e4d12
bf1e901
7594503
7a44d1c
469f9d2
3d70a0a
04c2144
37d0a7c
f6399ce
e89fc70
e9fd465
da54958
45e325e
e195cec
68ac28c
4478482
c3882ee
f35bacf
742a577
db49bce
b4c5cc6
efd2728
9193dc8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,180 @@ | ||||||||||||||||
| use clippy_utils::res::MaybeResPath as _; | ||||||||||||||||
| use clippy_utils::ty::{implements_trait, ty_from_hir_ty}; | ||||||||||||||||
| use clippy_utils::visitors::{Descend, for_each_expr}; | ||||||||||||||||
| use rustc_hir::PatKind; | ||||||||||||||||
| use rustc_lint::{LateContext, LateLintPass, declare_lint_pass}; | ||||||||||||||||
| use rustc_middle::ty::{Ref, Ty}; | ||||||||||||||||
| use rustc_span::Span; | ||||||||||||||||
| use rustc_span::def_id::DefId; | ||||||||||||||||
| use std::ops::ControlFlow; | ||||||||||||||||
|
|
||||||||||||||||
| declare_clippy_lint! { | ||||||||||||||||
| /// ### Example | ||||||||||||||||
| /// ```norun | ||||||||||||||||
| /// #[derive(Clone)] | ||||||||||||||||
| /// struct A; | ||||||||||||||||
| /// | ||||||||||||||||
| /// pub fn foo(item: &A) { | ||||||||||||||||
| /// let cloned_ref = item.clone(); | ||||||||||||||||
| /// } | ||||||||||||||||
| /// ``` | ||||||||||||||||
| /// Instead, take it by value, to demand the ownership of the data right away. | ||||||||||||||||
| /// Or try reworking the function to use another type. | ||||||||||||||||
| /// ```norun | ||||||||||||||||
| /// #[derive(Clone)] | ||||||||||||||||
| /// struct A; | ||||||||||||||||
| /// | ||||||||||||||||
| /// pub fn foo_by_value(item: A) { | ||||||||||||||||
| /// let cloned_ref = item.clone(); | ||||||||||||||||
| /// } | ||||||||||||||||
| /// | ||||||||||||||||
| /// pub fn foo_with_arc(item: &A) { | ||||||||||||||||
| /// // Turns out we don't actually need ownership! | ||||||||||||||||
| /// } | ||||||||||||||||
| /// ``` | ||||||||||||||||
| #[clippy::version = "1.98.0"] | ||||||||||||||||
| pub FN_PARAM_REF_CLONED, | ||||||||||||||||
| pedantic, | ||||||||||||||||
| "you should pass by value instead of cloning a passed reference" | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| declare_lint_pass!(FnParamRefCloned => [FN_PARAM_REF_CLONED]); | ||||||||||||||||
|
|
||||||||||||||||
| type Candidates = Vec<((rustc_hir::HirId, Span), Vec<(rustc_hir::HirId, Span)>)>; | ||||||||||||||||
|
|
||||||||||||||||
| /// Returns true if `ty` is `&T` where `T` implements any trait in `must_impl_trait` | ||||||||||||||||
| pub fn is_candidate_ty<'a>(cx: &LateContext<'a>, ty: Ty<'a>, must_impl_trait: &[DefId]) -> bool { | ||||||||||||||||
|
medzernik marked this conversation as resolved.
|
||||||||||||||||
| if let Ref(_, ty_ref, mutability) = ty.kind() { | ||||||||||||||||
| must_impl_trait | ||||||||||||||||
| .iter() | ||||||||||||||||
| .any(|def_id| implements_trait(cx, *ty_ref, *def_id, &[])) | ||||||||||||||||
| && mutability.is_not() | ||||||||||||||||
| } else { | ||||||||||||||||
| false | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| pub fn get_param_id_span(param: &rustc_hir::Param<'_>) -> Option<(rustc_hir::HirId, Span)> { | ||||||||||||||||
| if let PatKind::Binding(_, hir_id, ident, _) = param.pat.kind | ||||||||||||||||
| && !ident.span.from_expansion() | ||||||||||||||||
| && !ident.is_reserved() | ||||||||||||||||
| { | ||||||||||||||||
| Some((hir_id, param.ty_span)) | ||||||||||||||||
| } else { | ||||||||||||||||
| None | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| impl<'tcx> LateLintPass<'tcx> for FnParamRefCloned { | ||||||||||||||||
| fn check_fn( | ||||||||||||||||
| &mut self, | ||||||||||||||||
| cx: &LateContext<'tcx>, | ||||||||||||||||
| fn_kind: rustc_hir::intravisit::FnKind<'tcx>, | ||||||||||||||||
| fn_decl: &'tcx rustc_hir::FnDecl<'tcx>, | ||||||||||||||||
| fn_body: &'tcx rustc_hir::Body<'tcx>, | ||||||||||||||||
| _: Span, | ||||||||||||||||
| _: rustc_span::def_id::LocalDefId, | ||||||||||||||||
| ) { | ||||||||||||||||
| let mut candidates: Candidates; | ||||||||||||||||
|
|
||||||||||||||||
| if let rustc_hir::intravisit::FnKind::Closure = fn_kind { | ||||||||||||||||
| return; | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| // Define which traits must be implemented for the lint to work | ||||||||||||||||
| let must_impl_trait = [ | ||||||||||||||||
| cx.tcx.lang_items().clone_trait().unwrap(), | ||||||||||||||||
| cx.tcx.lang_items().drop_trait().unwrap(), | ||||||||||||||||
|
Comment on lines
+86
to
+87
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should
Suggested change
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I didn't know about that, it's a fairly used pattern |
||||||||||||||||
| ]; | ||||||||||||||||
|
medzernik marked this conversation as resolved.
|
||||||||||||||||
|
|
||||||||||||||||
| // Get all candidates of params that implement said traits and zip them with function signature | ||||||||||||||||
| // params | ||||||||||||||||
| candidates = fn_decl | ||||||||||||||||
| .inputs | ||||||||||||||||
| .iter() | ||||||||||||||||
| .zip(fn_body.params) | ||||||||||||||||
| .filter_map(|(ty, param)| { | ||||||||||||||||
| if let Some((id, span)) = get_param_id_span(param) | ||||||||||||||||
| && is_candidate_ty(cx, ty_from_hir_ty(cx, ty), &must_impl_trait) | ||||||||||||||||
| { | ||||||||||||||||
| Some(((id, span), Vec::default())) | ||||||||||||||||
| } else { | ||||||||||||||||
| None | ||||||||||||||||
| } | ||||||||||||||||
| }) | ||||||||||||||||
| .collect(); | ||||||||||||||||
|
|
||||||||||||||||
| // Find all rebinds of param values in the function and add them to the original candidates (tuple) | ||||||||||||||||
| let rustc_hir::ExprKind::Block(block, _) = fn_body.value.kind else { | ||||||||||||||||
| return; | ||||||||||||||||
| }; | ||||||||||||||||
|
|
||||||||||||||||
| for statement in block.stmts { | ||||||||||||||||
| if let rustc_hir::StmtKind::Let(let_stmt) = statement.kind | ||||||||||||||||
| && let Some(expr) = let_stmt.init | ||||||||||||||||
| && let rustc_hir::ExprKind::Path(qpath) = expr.kind | ||||||||||||||||
| && let Some(hir_id) = qpath.res_local_id() | ||||||||||||||||
| { | ||||||||||||||||
| for (cand, rebinds) in &mut candidates { | ||||||||||||||||
| if cand.0 == hir_id { | ||||||||||||||||
| rebinds.push((let_stmt.pat.hir_id, let_stmt.span)); | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| // Look whether the candidates call the `.clone()` method anywhere | ||||||||||||||||
| _ = for_each_expr(cx.tcx, fn_body.value, move |expr| match expr.kind { | ||||||||||||||||
| rustc_hir::ExprKind::If(_, _, _) | rustc_hir::ExprKind::Match(_, _, _) => { | ||||||||||||||||
| ControlFlow::<(), Descend>::Continue(Descend::No) | ||||||||||||||||
| }, | ||||||||||||||||
| rustc_hir::ExprKind::MethodCall(method_name, receiver, args, span) | ||||||||||||||||
| if method_name.ident.as_str() == "clone" | ||||||||||||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could we use
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. rustc_hir::ExprKind::MethodCall(name, receiver, args, span)
if args.is_empty()
&& let rustc_hir::ExprKind::Path(qpath) = receiver.kind
&& let Some(hir_id) = qpath.res_local_id()
&& clippy_utils::is_lang_item_or_ctor(cx, hir_id.owner.to_def_id(), LangItem::Clone) =>I also tried this: if args.is_empty()
&& let rustc_hir::ExprKind::Path(qpath) = receiver.kind
&& let Some(hir_id) = qpath.res_local_id()
&& let def_id = cx.tcx.hir_owner_node(cx.tcx.hir_get_parent_item(expr.hir_id))
&& clippy_utils::is_lang_item_or_ctor(cx, def_id.def_id().to_def_id(), LangItem::Clone) =>I tried something like this (experimented with
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What I'm talking about is, this code would turn out #[derive(Clone)]
struct A;
struct B;
trait MyClone {
fn clone(&self) -> Self;
}
impl MyClone for B {
// ...
}
pub fn foo(item: &A) { // <- We save &A as candidate
let x: B = B;
x.clone(); // <- Technically called "clone"
}Now, if I'm reading the |
||||||||||||||||
| && args.is_empty() | ||||||||||||||||
| && let rustc_hir::ExprKind::Path(qpath) = receiver.kind | ||||||||||||||||
| && let Some(hir_id) = qpath.res_local_id() => | ||||||||||||||||
| { | ||||||||||||||||
| for (original_candidate, rebinds) in &candidates { | ||||||||||||||||
| emit_lint(cx, span, original_candidate, rebinds, hir_id); | ||||||||||||||||
| } | ||||||||||||||||
| ControlFlow::<(), Descend>::Continue(Descend::Yes) | ||||||||||||||||
| }, | ||||||||||||||||
|
|
||||||||||||||||
| _ => ControlFlow::<(), Descend>::Continue(Descend::Yes), | ||||||||||||||||
| }); | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| fn emit_lint( | ||||||||||||||||
| cx: &LateContext<'_>, | ||||||||||||||||
| span: Span, | ||||||||||||||||
| original_candidate: &(rustc_hir::HirId, Span), | ||||||||||||||||
| rebinds: &Vec<(rustc_hir::HirId, Span)>, | ||||||||||||||||
| hir_id: rustc_hir::HirId, | ||||||||||||||||
| ) { | ||||||||||||||||
| if original_candidate.0 == hir_id { | ||||||||||||||||
| clippy_utils::diagnostics::span_lint_and_note( | ||||||||||||||||
| cx, | ||||||||||||||||
| FN_PARAM_REF_CLONED, | ||||||||||||||||
| span, | ||||||||||||||||
| "function gets a parameter by reference, but you later unconditionally clone it", | ||||||||||||||||
| Some(original_candidate.1), | ||||||||||||||||
| "consider passing the reference by value instead", | ||||||||||||||||
| ); | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| for rebind in rebinds { | ||||||||||||||||
| if rebind.0 == hir_id { | ||||||||||||||||
| clippy_utils::diagnostics::span_lint_and_then( | ||||||||||||||||
| cx, | ||||||||||||||||
| FN_PARAM_REF_CLONED, | ||||||||||||||||
| span, | ||||||||||||||||
| "function gets a parameter by reference, but you later rebind and unconditionally clone it", | ||||||||||||||||
| |diag| { | ||||||||||||||||
| diag.span_note(rebind.1, "you bind the parameter into a new binding here") | ||||||||||||||||
| .span_note(original_candidate.1, "the parameter is passed by reference..."); | ||||||||||||||||
| }, | ||||||||||||||||
| ); | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
Uh oh!
There was an error while loading. Please reload this page.