1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir::intravisit::FnKind;
11 use crate::rustc::hir::{def_id, Body, FnDecl};
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::mir::{
15 visit::{MutatingUseContext, NonUseContext, PlaceContext, Visitor},
19 use crate::rustc::{declare_tool_lint, lint_array};
20 use crate::rustc_errors::Applicability;
23 source_map::{BytePos, Span},
26 in_macro, is_copy, match_def_path, match_type, paths, snippet_opt, span_lint_node, span_lint_node_and_then,
29 use if_chain::if_chain;
30 use std::convert::TryFrom;
32 macro_rules! unwrap_or_continue {
41 /// **What it does:** Checks for a redudant `clone()` (and its relatives) which clones an owned
42 /// value that is going to be dropped without further use.
44 /// **Why is this bad?** It is not always possible for the compiler to eliminate useless
45 /// allocations and deallocations generated by redundant `clone()`s.
47 /// **Known problems:**
49 /// * Suggestions made by this lint could require NLL to be enabled.
50 /// * False-positive if there is a borrow preventing the value from moving out.
53 /// let x = String::new();
57 /// foo(x.clone()); // This lint suggests to remove this `clone()`
63 /// let x = Foo::new();
65 /// call(x.clone()); // this can just pass `x`
68 /// ["lorem", "ipsum"].join(" ").to_string()
70 /// Path::new("/a/b").join("c").to_path_buf()
72 declare_clippy_lint! {
75 "`clone()` of an owned value that is going to be dropped immediately"
78 pub struct RedundantClone;
80 impl LintPass for RedundantClone {
81 fn get_lints(&self) -> LintArray {
82 lint_array!(REDUNDANT_CLONE)
86 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone {
89 cx: &LateContext<'a, 'tcx>,
96 let def_id = cx.tcx.hir.body_owner_def_id(body.id());
97 let mir = cx.tcx.optimized_mir(def_id);
99 for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
100 let terminator = bbdata.terminator();
102 if in_macro(terminator.source_info.span) {
107 if terminator.successors().any(|s| *s == bb) {
111 let (fn_def_id, arg, arg_ty, _) = unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
113 let from_borrow = match_def_path(cx.tcx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
114 || match_def_path(cx.tcx, fn_def_id, &paths::TO_OWNED_METHOD)
115 || (match_def_path(cx.tcx, fn_def_id, &paths::TO_STRING_METHOD)
116 && match_type(cx, arg_ty, &paths::STRING));
118 let from_deref = !from_borrow
119 && (match_def_path(cx.tcx, fn_def_id, &paths::PATH_TO_PATH_BUF)
120 || match_def_path(cx.tcx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
122 if !from_borrow && !from_deref {
126 // _1 in MIR `{ _2 = &_1; clone(move _2); }` or `{ _2 = _1; to_path_buf(_2); } (from_deref)
127 // In case of `from_deref`, `arg` is already a reference since it is `deref`ed in the previous
129 let cloned = unwrap_or_continue!(find_stmt_assigns_to(arg, from_borrow, bbdata.statements.iter().rev()));
131 // _1 in MIR `{ _2 = &_1; _3 = deref(move _2); } -> { _4 = _3; to_path_buf(move _4); }`
132 let referent = if from_deref {
133 let ps = mir.predecessors_for(bb);
137 let pred_terminator = mir[ps[0]].terminator();
139 let pred_arg = if_chain! {
140 if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, Some(res))) =
141 is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
142 if *res == mir::Place::Local(cloned);
143 if match_def_path(cx.tcx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
144 if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
145 || match_type(cx, pred_arg_ty, &paths::OS_STRING);
153 unwrap_or_continue!(find_stmt_assigns_to(pred_arg, true, mir[ps[0]].statements.iter().rev()))
158 let used_later = traversal::ReversePostorder::new(&mir, bb).skip(1).any(|(tbb, tdata)| {
160 if tdata.terminator().successors().any(|s| *s == bb) {
164 let mut vis = LocalUseVisitor {
166 used_other_than_drop: false,
168 vis.visit_basic_block_data(tbb, tdata);
169 vis.used_other_than_drop
173 let span = terminator.source_info.span;
174 let node = if let mir::ClearCrossCrate::Set(scope_local_data) = &mir.source_scope_local_data {
175 scope_local_data[terminator.source_info.scope].lint_root
181 if let Some(snip) = snippet_opt(cx, span);
182 if let Some(dot) = snip.rfind('.');
184 let sugg_span = span.with_lo(
185 span.lo() + BytePos(u32::try_from(dot).unwrap())
188 span_lint_node_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |db| {
189 db.span_suggestion_with_applicability(
193 Applicability::MaybeIncorrect,
196 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
197 "this value is dropped without further use",
201 span_lint_node(cx, REDUNDANT_CLONE, node, span, "redundant clone");
209 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
210 fn is_call_with_ref_arg<'tcx>(
211 cx: &LateContext<'_, 'tcx>,
212 mir: &'tcx mir::Mir<'tcx>,
213 kind: &'tcx mir::TerminatorKind<'tcx>,
214 ) -> Option<(def_id::DefId, mir::Local, ty::Ty<'tcx>, Option<&'tcx mir::Place<'tcx>>)> {
216 if let TerminatorKind::Call { func, args, destination, .. } = kind;
218 if let mir::Operand::Move(mir::Place::Local(local)) = &args[0];
219 if let ty::FnDef(def_id, _) = func.ty(&*mir, cx.tcx).sty;
220 if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
221 if !is_copy(cx, inner_ty);
223 Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)))
230 /// Finds the first `to = (&)from`, and returns `Some(from)`.
231 fn find_stmt_assigns_to<'a, 'tcx: 'a>(
234 mut stmts: impl Iterator<Item = &'a mir::Statement<'tcx>>,
235 ) -> Option<mir::Local> {
236 stmts.find_map(|stmt| {
237 if let mir::StatementKind::Assign(mir::Place::Local(local), v) = &stmt.kind {
240 if let mir::Rvalue::Ref(_, _, mir::Place::Local(r)) = **v {
243 } else if let mir::Rvalue::Use(mir::Operand::Copy(mir::Place::Local(r))) = **v {
253 struct LocalUseVisitor {
255 used_other_than_drop: bool,
258 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
259 fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
260 let statements = &data.statements;
261 for (statement_index, statement) in statements.iter().enumerate() {
262 self.visit_statement(block, statement, mir::Location { block, statement_index });
264 // Once flagged, skip remaining statements
265 if self.used_other_than_drop {
270 self.visit_terminator(
275 statement_index: statements.len(),
280 fn visit_local(&mut self, local: &mir::Local, ctx: PlaceContext<'tcx>, _: mir::Location) {
282 PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(NonUseContext::StorageDead) => return,
286 if *local == self.local {
287 self.used_other_than_drop = true;