]>
Commit | Line | Data |
---|---|---|
cdc7bbd5 XL |
1 | use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then}; |
2 | use clippy_utils::ptr::get_spans; | |
3 | use clippy_utils::source::{snippet, snippet_opt}; | |
4 | use clippy_utils::ty::{implements_trait, is_copy, is_type_diagnostic_item}; | |
5 | use clippy_utils::{get_trait_def_id, is_self, paths}; | |
f20569fa XL |
6 | use if_chain::if_chain; |
7 | use rustc_ast::ast::Attribute; | |
cdc7bbd5 | 8 | use rustc_data_structures::fx::FxHashSet; |
f20569fa XL |
9 | use rustc_errors::{Applicability, DiagnosticBuilder}; |
10 | use rustc_hir::intravisit::FnKind; | |
11 | use rustc_hir::{BindingAnnotation, Body, FnDecl, GenericArg, HirId, Impl, ItemKind, Node, PatKind, QPath, TyKind}; | |
cdc7bbd5 | 12 | use rustc_hir::{HirIdMap, HirIdSet}; |
f20569fa XL |
13 | use rustc_infer::infer::TyCtxtInferExt; |
14 | use rustc_lint::{LateContext, LateLintPass}; | |
15 | use rustc_middle::mir::FakeReadCause; | |
16 | use rustc_middle::ty::{self, TypeFoldable}; | |
17 | use rustc_session::{declare_lint_pass, declare_tool_lint}; | |
18 | use rustc_span::symbol::kw; | |
19 | use rustc_span::{sym, Span}; | |
20 | use rustc_target::spec::abi::Abi; | |
21 | use rustc_trait_selection::traits; | |
22 | use rustc_trait_selection::traits::misc::can_type_implement_copy; | |
23 | use rustc_typeck::expr_use_visitor as euv; | |
24 | use std::borrow::Cow; | |
25 | ||
26 | declare_clippy_lint! { | |
94222f64 XL |
27 | /// ### What it does |
28 | /// Checks for functions taking arguments by value, but not | |
f20569fa XL |
29 | /// consuming them in its |
30 | /// body. | |
31 | /// | |
94222f64 XL |
32 | /// ### Why is this bad? |
33 | /// Taking arguments by reference is more flexible and can | |
f20569fa XL |
34 | /// sometimes avoid |
35 | /// unnecessary allocations. | |
36 | /// | |
94222f64 | 37 | /// ### Known problems |
f20569fa XL |
38 | /// * This lint suggests taking an argument by reference, |
39 | /// however sometimes it is better to let users decide the argument type | |
40 | /// (by using `Borrow` trait, for example), depending on how the function is used. | |
41 | /// | |
94222f64 | 42 | /// ### Example |
f20569fa XL |
43 | /// ```rust |
44 | /// fn foo(v: Vec<i32>) { | |
45 | /// assert_eq!(v.len(), 42); | |
46 | /// } | |
47 | /// ``` | |
48 | /// should be | |
49 | /// ```rust | |
50 | /// fn foo(v: &[i32]) { | |
51 | /// assert_eq!(v.len(), 42); | |
52 | /// } | |
53 | /// ``` | |
54 | pub NEEDLESS_PASS_BY_VALUE, | |
55 | pedantic, | |
56 | "functions taking arguments by value, but not consuming them in its body" | |
57 | } | |
58 | ||
59 | declare_lint_pass!(NeedlessPassByValue => [NEEDLESS_PASS_BY_VALUE]); | |
60 | ||
61 | macro_rules! need { | |
62 | ($e: expr) => { | |
63 | if let Some(x) = $e { | |
64 | x | |
65 | } else { | |
66 | return; | |
67 | } | |
68 | }; | |
69 | } | |
70 | ||
71 | impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { | |
72 | #[allow(clippy::too_many_lines)] | |
73 | fn check_fn( | |
74 | &mut self, | |
75 | cx: &LateContext<'tcx>, | |
76 | kind: FnKind<'tcx>, | |
77 | decl: &'tcx FnDecl<'_>, | |
78 | body: &'tcx Body<'_>, | |
79 | span: Span, | |
80 | hir_id: HirId, | |
81 | ) { | |
82 | if span.from_expansion() { | |
83 | return; | |
84 | } | |
85 | ||
86 | match kind { | |
87 | FnKind::ItemFn(.., header, _) => { | |
88 | let attrs = cx.tcx.hir().attrs(hir_id); | |
89 | if header.abi != Abi::Rust || requires_exact_signature(attrs) { | |
90 | return; | |
91 | } | |
92 | }, | |
93 | FnKind::Method(..) => (), | |
94 | FnKind::Closure => return, | |
95 | } | |
96 | ||
97 | // Exclude non-inherent impls | |
98 | if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) { | |
99 | if matches!( | |
100 | item.kind, | |
101 | ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..) | |
102 | ) { | |
103 | return; | |
104 | } | |
105 | } | |
106 | ||
107 | // Allow `Borrow` or functions to be taken by value | |
f20569fa XL |
108 | let allowed_traits = [ |
109 | need!(cx.tcx.lang_items().fn_trait()), | |
110 | need!(cx.tcx.lang_items().fn_once_trait()), | |
111 | need!(cx.tcx.lang_items().fn_mut_trait()), | |
112 | need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT)), | |
113 | ]; | |
114 | ||
115 | let sized_trait = need!(cx.tcx.lang_items().sized_trait()); | |
116 | ||
117 | let fn_def_id = cx.tcx.hir().local_def_id(hir_id); | |
118 | ||
119 | let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds().iter()) | |
94222f64 | 120 | .filter(|p| !p.is_global(cx.tcx)) |
f20569fa XL |
121 | .filter_map(|obligation| { |
122 | // Note that we do not want to deal with qualified predicates here. | |
123 | match obligation.predicate.kind().no_bound_vars() { | |
94222f64 | 124 | Some(ty::PredicateKind::Trait(pred)) if pred.def_id() != sized_trait => Some(pred), |
f20569fa XL |
125 | _ => None, |
126 | } | |
127 | }) | |
128 | .collect::<Vec<_>>(); | |
129 | ||
130 | // Collect moved variables and spans which will need dereferencings from the | |
131 | // function body. | |
132 | let MovedVariablesCtxt { | |
133 | moved_vars, | |
134 | spans_need_deref, | |
135 | .. | |
136 | } = { | |
137 | let mut ctx = MovedVariablesCtxt::default(); | |
138 | cx.tcx.infer_ctxt().enter(|infcx| { | |
139 | euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.typeck_results()) | |
140 | .consume_body(body); | |
141 | }); | |
142 | ctx | |
143 | }; | |
144 | ||
145 | let fn_sig = cx.tcx.fn_sig(fn_def_id); | |
146 | let fn_sig = cx.tcx.erase_late_bound_regions(fn_sig); | |
147 | ||
148 | for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() { | |
149 | // All spans generated from a proc-macro invocation are the same... | |
150 | if span == input.span { | |
151 | return; | |
152 | } | |
153 | ||
154 | // Ignore `self`s. | |
155 | if idx == 0 { | |
156 | if let PatKind::Binding(.., ident, _) = arg.pat.kind { | |
157 | if ident.name == kw::SelfLower { | |
158 | continue; | |
159 | } | |
160 | } | |
161 | } | |
162 | ||
163 | // | |
164 | // * Exclude a type that is specifically bounded by `Borrow`. | |
165 | // * Exclude a type whose reference also fulfills its bound. (e.g., `std::convert::AsRef`, | |
166 | // `serde::Serialize`) | |
167 | let (implements_borrow_trait, all_borrowable_trait) = { | |
168 | let preds = preds.iter().filter(|t| t.self_ty() == ty).collect::<Vec<_>>(); | |
169 | ||
170 | ( | |
94222f64 | 171 | preds.iter().any(|t| cx.tcx.is_diagnostic_item(sym::Borrow, t.def_id())), |
f20569fa XL |
172 | !preds.is_empty() && { |
173 | let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty); | |
174 | preds.iter().all(|t| { | |
175 | let ty_params = t.trait_ref.substs.iter().skip(1).collect::<Vec<_>>(); | |
176 | implements_trait(cx, ty_empty_region, t.def_id(), &ty_params) | |
177 | }) | |
178 | }, | |
179 | ) | |
180 | }; | |
181 | ||
182 | if_chain! { | |
183 | if !is_self(arg); | |
184 | if !ty.is_mutable_ptr(); | |
185 | if !is_copy(cx, ty); | |
186 | if !allowed_traits.iter().any(|&t| implements_trait(cx, ty, t, &[])); | |
187 | if !implements_borrow_trait; | |
188 | if !all_borrowable_trait; | |
189 | ||
190 | if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.kind; | |
191 | if !moved_vars.contains(&canonical_id); | |
192 | then { | |
193 | if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut { | |
194 | continue; | |
195 | } | |
196 | ||
197 | // Dereference suggestion | |
198 | let sugg = |diag: &mut DiagnosticBuilder<'_>| { | |
199 | if let ty::Adt(def, ..) = ty.kind() { | |
200 | if let Some(span) = cx.tcx.hir().span_if_local(def.did) { | |
201 | if can_type_implement_copy(cx.tcx, cx.param_env, ty).is_ok() { | |
202 | diag.span_help(span, "consider marking this type as `Copy`"); | |
203 | } | |
204 | } | |
205 | } | |
206 | ||
207 | let deref_span = spans_need_deref.get(&canonical_id); | |
208 | if_chain! { | |
209 | if is_type_diagnostic_item(cx, ty, sym::vec_type); | |
210 | if let Some(clone_spans) = | |
211 | get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]); | |
cdc7bbd5 | 212 | if let TyKind::Path(QPath::Resolved(_, path)) = input.kind; |
f20569fa XL |
213 | if let Some(elem_ty) = path.segments.iter() |
214 | .find(|seg| seg.ident.name == sym::Vec) | |
215 | .and_then(|ps| ps.args.as_ref()) | |
216 | .map(|params| params.args.iter().find_map(|arg| match arg { | |
217 | GenericArg::Type(ty) => Some(ty), | |
218 | _ => None, | |
219 | }).unwrap()); | |
220 | then { | |
221 | let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_")); | |
222 | diag.span_suggestion( | |
223 | input.span, | |
224 | "consider changing the type to", | |
225 | slice_ty, | |
226 | Applicability::Unspecified, | |
227 | ); | |
228 | ||
229 | for (span, suggestion) in clone_spans { | |
230 | diag.span_suggestion( | |
231 | span, | |
232 | &snippet_opt(cx, span) | |
233 | .map_or( | |
234 | "change the call to".into(), | |
235 | |x| Cow::from(format!("change `{}` to", x)), | |
236 | ), | |
237 | suggestion.into(), | |
238 | Applicability::Unspecified, | |
239 | ); | |
240 | } | |
241 | ||
242 | // cannot be destructured, no need for `*` suggestion | |
243 | assert!(deref_span.is_none()); | |
244 | return; | |
245 | } | |
246 | } | |
247 | ||
248 | if is_type_diagnostic_item(cx, ty, sym::string_type) { | |
249 | if let Some(clone_spans) = | |
250 | get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) { | |
251 | diag.span_suggestion( | |
252 | input.span, | |
253 | "consider changing the type to", | |
254 | "&str".to_string(), | |
255 | Applicability::Unspecified, | |
256 | ); | |
257 | ||
258 | for (span, suggestion) in clone_spans { | |
259 | diag.span_suggestion( | |
260 | span, | |
261 | &snippet_opt(cx, span) | |
262 | .map_or( | |
263 | "change the call to".into(), | |
264 | |x| Cow::from(format!("change `{}` to", x)) | |
265 | ), | |
266 | suggestion.into(), | |
267 | Applicability::Unspecified, | |
268 | ); | |
269 | } | |
270 | ||
271 | assert!(deref_span.is_none()); | |
272 | return; | |
273 | } | |
274 | } | |
275 | ||
276 | let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))]; | |
277 | ||
278 | // Suggests adding `*` to dereference the added reference. | |
279 | if let Some(deref_span) = deref_span { | |
280 | spans.extend( | |
281 | deref_span | |
282 | .iter() | |
cdc7bbd5 | 283 | .copied() |
f20569fa XL |
284 | .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))), |
285 | ); | |
286 | spans.sort_by_key(|&(span, _)| span); | |
287 | } | |
288 | multispan_sugg(diag, "consider taking a reference instead", spans); | |
289 | }; | |
290 | ||
291 | span_lint_and_then( | |
292 | cx, | |
293 | NEEDLESS_PASS_BY_VALUE, | |
294 | input.span, | |
295 | "this argument is passed by value, but not consumed in the function body", | |
296 | sugg, | |
297 | ); | |
298 | } | |
299 | } | |
300 | } | |
301 | } | |
302 | } | |
303 | ||
304 | /// Functions marked with these attributes must have the exact signature. | |
305 | fn requires_exact_signature(attrs: &[Attribute]) -> bool { | |
306 | attrs.iter().any(|attr| { | |
307 | [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive] | |
308 | .iter() | |
309 | .any(|&allow| attr.has_name(allow)) | |
310 | }) | |
311 | } | |
312 | ||
313 | #[derive(Default)] | |
314 | struct MovedVariablesCtxt { | |
cdc7bbd5 | 315 | moved_vars: HirIdSet, |
f20569fa XL |
316 | /// Spans which need to be prefixed with `*` for dereferencing the |
317 | /// suggested additional reference. | |
cdc7bbd5 | 318 | spans_need_deref: HirIdMap<FxHashSet<Span>>, |
f20569fa XL |
319 | } |
320 | ||
321 | impl MovedVariablesCtxt { | |
322 | fn move_common(&mut self, cmt: &euv::PlaceWithHirId<'_>) { | |
323 | if let euv::PlaceBase::Local(vid) = cmt.place.base { | |
324 | self.moved_vars.insert(vid); | |
325 | } | |
326 | } | |
327 | } | |
328 | ||
329 | impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt { | |
136023e0 XL |
330 | fn consume(&mut self, cmt: &euv::PlaceWithHirId<'tcx>, _: HirId) { |
331 | self.move_common(cmt); | |
f20569fa XL |
332 | } |
333 | ||
334 | fn borrow(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {} | |
335 | ||
336 | fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId) {} | |
337 | ||
cdc7bbd5 | 338 | fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {} |
f20569fa | 339 | } |