2 has_drop, in_macro, is_copy, match_def_path, match_type, paths, snippet_opt, span_lint_node,
3 span_lint_node_and_then, walk_ptrs_ty_depth,
5 use if_chain::if_chain;
7 use rustc::hir::intravisit::FnKind;
8 use rustc::hir::{def_id, Body, FnDecl, HirId};
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 visit::{MutatingUseContext, PlaceContext, Visitor},
16 use rustc::{declare_tool_lint, lint_array};
17 use rustc_errors::Applicability;
18 use std::convert::TryFrom;
20 source_map::{BytePos, Span},
23 macro_rules! unwrap_or_continue {
32 /// **What it does:** Checks for a redudant `clone()` (and its relatives) which clones an owned
33 /// value that is going to be dropped without further use.
35 /// **Why is this bad?** It is not always possible for the compiler to eliminate useless
36 /// allocations and deallocations generated by redundant `clone()`s.
38 /// **Known problems:**
40 /// * Suggestions made by this lint could require NLL to be enabled.
41 /// * False-positive if there is a borrow preventing the value from moving out.
44 /// let x = String::new();
48 /// foo(x.clone()); // This lint suggests to remove this `clone()`
54 /// let x = Foo::new();
56 /// call(x.clone()); // this can just pass `x`
59 /// ["lorem", "ipsum"].join(" ").to_string()
61 /// Path::new("/a/b").join("c").to_path_buf()
63 declare_clippy_lint! {
66 "`clone()` of an owned value that is going to be dropped immediately"
69 pub struct RedundantClone;
71 impl LintPass for RedundantClone {
72 fn get_lints(&self) -> LintArray {
73 lint_array!(REDUNDANT_CLONE)
76 fn name(&self) -> &'static str {
81 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone {
82 #[allow(clippy::too_many_lines)]
85 cx: &LateContext<'a, 'tcx>,
92 let def_id = cx.tcx.hir().body_owner_def_id(body.id());
93 let mir = cx.tcx.optimized_mir(def_id);
95 for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
96 let terminator = bbdata.terminator();
98 if in_macro(terminator.source_info.span) {
103 if terminator.successors().any(|s| *s == bb) {
107 let (fn_def_id, arg, arg_ty, _) = unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
109 let from_borrow = match_def_path(cx.tcx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
110 || match_def_path(cx.tcx, fn_def_id, &paths::TO_OWNED_METHOD)
111 || (match_def_path(cx.tcx, fn_def_id, &paths::TO_STRING_METHOD)
112 && match_type(cx, arg_ty, &paths::STRING));
114 let from_deref = !from_borrow
115 && (match_def_path(cx.tcx, fn_def_id, &paths::PATH_TO_PATH_BUF)
116 || match_def_path(cx.tcx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
118 if !from_borrow && !from_deref {
122 // _1 in MIR `{ _2 = &_1; clone(move _2); }` or `{ _2 = _1; to_path_buf(_2); } (from_deref)
123 // In case of `from_deref`, `arg` is already a reference since it is `deref`ed in the previous
125 let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(
130 bbdata.statements.iter()
133 if from_borrow && cannot_move_out {
137 // _1 in MIR `{ _2 = &_1; _3 = deref(move _2); } -> { _4 = _3; to_path_buf(move _4); }`
138 let referent = if from_deref {
139 let ps = mir.predecessors_for(bb);
143 let pred_terminator = mir[ps[0]].terminator();
145 let pred_arg = if_chain! {
146 if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, Some(res))) =
147 is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
148 if *res == mir::Place::Local(cloned);
149 if match_def_path(cx.tcx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
150 if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
151 || match_type(cx, pred_arg_ty, &paths::OS_STRING);
159 let (local, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(
164 mir[ps[0]].statements.iter()
174 let used_later = traversal::ReversePostorder::new(&mir, bb).skip(1).any(|(tbb, tdata)| {
176 if tdata.terminator().successors().any(|s| *s == bb) {
180 let mut vis = LocalUseVisitor {
182 used_other_than_drop: false,
184 vis.visit_basic_block_data(tbb, tdata);
185 vis.used_other_than_drop
189 let span = terminator.source_info.span;
190 let node = if let mir::ClearCrossCrate::Set(scope_local_data) = &mir.source_scope_local_data {
191 scope_local_data[terminator.source_info.scope].lint_root
197 if let Some(snip) = snippet_opt(cx, span);
198 if let Some(dot) = snip.rfind('.');
200 let sugg_span = span.with_lo(
201 span.lo() + BytePos(u32::try_from(dot).unwrap())
204 span_lint_node_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |db| {
209 Applicability::MaybeIncorrect,
212 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
213 "this value is dropped without further use",
217 span_lint_node(cx, REDUNDANT_CLONE, node, span, "redundant clone");
225 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
226 fn is_call_with_ref_arg<'tcx>(
227 cx: &LateContext<'_, 'tcx>,
228 mir: &'tcx mir::Mir<'tcx>,
229 kind: &'tcx mir::TerminatorKind<'tcx>,
230 ) -> Option<(def_id::DefId, mir::Local, ty::Ty<'tcx>, Option<&'tcx mir::Place<'tcx>>)> {
232 if let TerminatorKind::Call { func, args, destination, .. } = kind;
234 if let mir::Operand::Move(mir::Place::Local(local)) = &args[0];
235 if let ty::FnDef(def_id, _) = func.ty(&*mir, cx.tcx).sty;
236 if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
237 if !is_copy(cx, inner_ty);
239 Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)))
246 type CannotMoveOut = bool;
248 /// Finds the first `to = (&)from`, and returns
249 /// ``Some((from, [`true` if `from` cannot be moved out]))``.
250 fn find_stmt_assigns_to<'a, 'tcx: 'a>(
251 cx: &LateContext<'_, 'tcx>,
252 mir: &mir::Mir<'tcx>,
255 stmts: impl DoubleEndedIterator<Item = &'a mir::Statement<'tcx>>,
256 ) -> Option<(mir::Local, CannotMoveOut)> {
260 if let mir::StatementKind::Assign(mir::Place::Local(local), v) = &stmt.kind {
270 if let mir::Rvalue::Ref(_, _, ref place) = **v {
271 return base_local_and_movability(cx, mir, place);
273 } else if let mir::Rvalue::Use(mir::Operand::Copy(ref place)) = **v {
274 return base_local_and_movability(cx, mir, place);
280 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
281 /// if it is already a `Local`.
283 /// Also reports whether given `place` cannot be moved out.
284 fn base_local_and_movability<'tcx>(
285 cx: &LateContext<'_, 'tcx>,
286 mir: &mir::Mir<'tcx>,
287 mut place: &mir::Place<'tcx>,
288 ) -> Option<(mir::Local, CannotMoveOut)> {
289 use rustc::mir::Place::*;
291 // Dereference. You cannot move things out from a borrowed value.
292 let mut deref = false;
293 // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
294 let mut field = false;
298 Local(local) => return Some((*local, deref || field)),
299 Projection(proj) => {
301 deref = deref || matches!(proj.elem, mir::ProjectionElem::Deref);
302 if !field && matches!(proj.elem, mir::ProjectionElem::Field(..)) {
303 field = has_drop(cx, place.ty(&mir.local_decls, cx.tcx).to_ty(cx.tcx));
311 struct LocalUseVisitor {
313 used_other_than_drop: bool,
316 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
317 fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
318 let statements = &data.statements;
319 for (statement_index, statement) in statements.iter().enumerate() {
320 self.visit_statement(block, statement, mir::Location { block, statement_index });
322 // Once flagged, skip remaining statements
323 if self.used_other_than_drop {
328 self.visit_terminator(
333 statement_index: statements.len(),
338 fn visit_local(&mut self, local: &mir::Local, ctx: PlaceContext<'tcx>, _: mir::Location) {
340 PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_) => return,
344 if *local == self.local {
345 self.used_other_than_drop = true;