]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
Merge pull request #3278 from d-dorazio/fix-contributing-manual-test-command
[rust.git] / clippy_lints / src / lifetimes.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
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.
9
10
11 use crate::reexport::*;
12 use matches::matches;
13 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, LintContext};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc::hir::def::Def;
16 use crate::rustc::hir::*;
17 use crate::rustc::hir::intravisit::*;
18 use crate::rustc_data_structures::fx::{FxHashMap, FxHashSet};
19 use crate::syntax::source_map::Span;
20 use crate::utils::{last_path_segment, span_lint};
21 use crate::syntax::symbol::keywords;
22
23 /// **What it does:** Checks for lifetime annotations which can be removed by
24 /// relying on lifetime elision.
25 ///
26 /// **Why is this bad?** The additional lifetimes make the code look more
27 /// complicated, while there is nothing out of the ordinary going on. Removing
28 /// them leads to more readable code.
29 ///
30 /// **Known problems:** Potential false negatives: we bail out if the function
31 /// has a `where` clause where lifetimes are mentioned.
32 ///
33 /// **Example:**
34 /// ```rust
35 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 { x }
36 /// ```
37 declare_clippy_lint! {
38     pub NEEDLESS_LIFETIMES,
39     complexity,
40     "using explicit lifetimes for references in function arguments when elision rules \
41      would allow omitting them"
42 }
43
44 /// **What it does:** Checks for lifetimes in generics that are never used
45 /// anywhere else.
46 ///
47 /// **Why is this bad?** The additional lifetimes make the code look more
48 /// complicated, while there is nothing out of the ordinary going on. Removing
49 /// them leads to more readable code.
50 ///
51 /// **Known problems:** None.
52 ///
53 /// **Example:**
54 /// ```rust
55 /// fn unused_lifetime<'a>(x: u8) { .. }
56 /// ```
57 declare_clippy_lint! {
58     pub EXTRA_UNUSED_LIFETIMES,
59     complexity,
60     "unused lifetimes in function definitions"
61 }
62
63 #[derive(Copy, Clone)]
64 pub struct LifetimePass;
65
66 impl LintPass for LifetimePass {
67     fn get_lints(&self) -> LintArray {
68         lint_array!(NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES)
69     }
70 }
71
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LifetimePass {
73     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
74         if let ItemKind::Fn(ref decl, _, ref generics, id) = item.node {
75             check_fn_inner(cx, decl, Some(id), generics, item.span);
76         }
77     }
78
79     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
80         if let ImplItemKind::Method(ref sig, id) = item.node {
81             check_fn_inner(cx, &sig.decl, Some(id), &item.generics, item.span);
82         }
83     }
84
85     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
86         if let TraitItemKind::Method(ref sig, ref body) = item.node {
87             let body = match *body {
88                 TraitMethod::Required(_) => None,
89                 TraitMethod::Provided(id) => Some(id),
90             };
91             check_fn_inner(cx, &sig.decl, body, &item.generics, item.span);
92         }
93     }
94 }
95
96 /// The lifetime of a &-reference.
97 #[derive(PartialEq, Eq, Hash, Debug)]
98 enum RefLt {
99     Unnamed,
100     Static,
101     Named(Name),
102 }
103
104 fn check_fn_inner<'a, 'tcx>(
105     cx: &LateContext<'a, 'tcx>,
106     decl: &'tcx FnDecl,
107     body: Option<BodyId>,
108     generics: &'tcx Generics,
109     span: Span,
110 ) {
111     if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
112         return;
113     }
114
115     let mut bounds_lts = Vec::new();
116     let types = generics.params.iter().filter(|param| match param.kind {
117         GenericParamKind::Type { .. } => true,
118         GenericParamKind::Lifetime { .. } => false,
119     });
120     for typ in types {
121         for bound in &typ.bounds {
122             let mut visitor = RefVisitor::new(cx);
123             walk_param_bound(&mut visitor, bound);
124             if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
125                 return;
126             }
127             if let GenericBound::Trait(ref trait_ref, _) = *bound {
128                 let params = &trait_ref
129                     .trait_ref
130                     .path
131                     .segments
132                     .last()
133                     .expect("a path must have at least one segment")
134                     .args;
135                 if let Some(ref params) = *params {
136                     let lifetimes = params.args.iter().filter_map(|arg| match arg {
137                         GenericArg::Lifetime(lt) => Some(lt),
138                         GenericArg::Type(_) => None,
139                     });
140                     for bound in lifetimes {
141                         if bound.name != LifetimeName::Static && !bound.is_elided() {
142                             return;
143                         }
144                         bounds_lts.push(bound);
145                     }
146                 }
147             }
148         }
149     }
150     if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
151         span_lint(
152             cx,
153             NEEDLESS_LIFETIMES,
154             span,
155             "explicit lifetimes given in parameter types where they could be elided (or replaced with `'_` if needed by type declaration)",
156         );
157     }
158     report_extra_lifetimes(cx, decl, generics);
159 }
160
161 fn could_use_elision<'a, 'tcx: 'a>(
162     cx: &LateContext<'a, 'tcx>,
163     func: &'tcx FnDecl,
164     body: Option<BodyId>,
165     named_generics: &'tcx [GenericParam],
166     bounds_lts: Vec<&'tcx Lifetime>,
167 ) -> bool {
168     // There are two scenarios where elision works:
169     // * no output references, all input references have different LT
170     // * output references, exactly one input reference with same LT
171     // All lifetimes must be unnamed, 'static or defined without bounds on the
172     // level of the current item.
173
174     // check named LTs
175     let allowed_lts = allowed_lts_from(named_generics);
176
177     // these will collect all the lifetimes for references in arg/return types
178     let mut input_visitor = RefVisitor::new(cx);
179     let mut output_visitor = RefVisitor::new(cx);
180
181     // extract lifetimes in input argument types
182     for arg in &func.inputs {
183         input_visitor.visit_ty(arg);
184     }
185     // extract lifetimes in output type
186     if let Return(ref ty) = func.output {
187         output_visitor.visit_ty(ty);
188     }
189
190     let input_lts = match input_visitor.into_vec() {
191         Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
192         None => return false,
193     };
194     let output_lts = match output_visitor.into_vec() {
195         Some(val) => val,
196         None => return false,
197     };
198
199     if let Some(body_id) = body {
200         let mut checker = BodyLifetimeChecker {
201             lifetimes_used_in_body: false,
202         };
203         checker.visit_expr(&cx.tcx.hir.body(body_id).value);
204         if checker.lifetimes_used_in_body {
205             return false;
206         }
207     }
208
209     // check for lifetimes from higher scopes
210     for lt in input_lts.iter().chain(output_lts.iter()) {
211         if !allowed_lts.contains(lt) {
212             return false;
213         }
214     }
215
216     // no input lifetimes? easy case!
217     if input_lts.is_empty() {
218         false
219     } else if output_lts.is_empty() {
220         // no output lifetimes, check distinctness of input lifetimes
221
222         // only unnamed and static, ok
223         let unnamed_and_static = input_lts
224             .iter()
225             .all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
226         if unnamed_and_static {
227             return false;
228         }
229         // we have no output reference, so we only need all distinct lifetimes
230         input_lts.len() == unique_lifetimes(&input_lts)
231     } else {
232         // we have output references, so we need one input reference,
233         // and all output lifetimes must be the same
234         if unique_lifetimes(&output_lts) > 1 {
235             return false;
236         }
237         if input_lts.len() == 1 {
238             match (&input_lts[0], &output_lts[0]) {
239                 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
240                 (&RefLt::Named(_), &RefLt::Unnamed) => true,
241                 _ => false, /* already elided, different named lifetimes
242                              * or something static going on */
243             }
244         } else {
245             false
246         }
247     }
248 }
249
250 fn allowed_lts_from(named_generics: &[GenericParam]) -> FxHashSet<RefLt> {
251     let mut allowed_lts = FxHashSet::default();
252     for par in named_generics.iter() {
253         if let GenericParamKind::Lifetime { .. } = par.kind {
254             if par.bounds.is_empty() {
255                 allowed_lts.insert(RefLt::Named(par.name.ident().name));
256             }
257         }
258     }
259     allowed_lts.insert(RefLt::Unnamed);
260     allowed_lts.insert(RefLt::Static);
261     allowed_lts
262 }
263
264 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
265     for lt in bounds_lts {
266         if lt.name != LifetimeName::Static {
267             vec.push(RefLt::Named(lt.name.ident().name));
268         }
269     }
270
271     vec
272 }
273
274 /// Number of unique lifetimes in the given vector.
275 fn unique_lifetimes(lts: &[RefLt]) -> usize {
276     lts.iter().collect::<FxHashSet<_>>().len()
277 }
278
279 /// A visitor usable for `rustc_front::visit::walk_ty()`.
280 struct RefVisitor<'a, 'tcx: 'a> {
281     cx: &'a LateContext<'a, 'tcx>,
282     lts: Vec<RefLt>,
283     abort: bool,
284 }
285
286 impl<'v, 't> RefVisitor<'v, 't> {
287     fn new(cx: &'v LateContext<'v, 't>) -> Self {
288         Self {
289             cx,
290             lts: Vec::new(),
291             abort: false,
292         }
293     }
294
295     fn record(&mut self, lifetime: &Option<Lifetime>) {
296         if let Some(ref lt) = *lifetime {
297             if lt.name == LifetimeName::Static {
298                 self.lts.push(RefLt::Static);
299             } else if lt.is_elided() {
300                 self.lts.push(RefLt::Unnamed);
301             } else {
302                 self.lts.push(RefLt::Named(lt.name.ident().name));
303             }
304         } else {
305             self.lts.push(RefLt::Unnamed);
306         }
307     }
308
309     fn into_vec(self) -> Option<Vec<RefLt>> {
310         if self.abort {
311             None
312         } else {
313             Some(self.lts)
314         }
315     }
316
317     fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
318         if let Some(ref last_path_segment) = last_path_segment(qpath).args {
319             if !last_path_segment.parenthesized
320                 && !last_path_segment.args.iter().any(|arg| match arg {
321                     GenericArg::Lifetime(_) => true,
322                     GenericArg::Type(_) => false,
323                 }) {
324                 let hir_id = self.cx.tcx.hir.node_to_hir_id(ty.id);
325                 match self.cx.tables.qpath_def(qpath, hir_id) {
326                     Def::TyAlias(def_id) | Def::Struct(def_id) => {
327                         let generics = self.cx.tcx.generics_of(def_id);
328                         for _ in generics.params.as_slice() {
329                             self.record(&None);
330                         }
331                     },
332                     Def::Trait(def_id) => {
333                         let trait_def = self.cx.tcx.trait_def(def_id);
334                         for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
335                             self.record(&None);
336                         }
337                     },
338                     _ => (),
339                 }
340             }
341         }
342     }
343 }
344
345 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
346     // for lifetimes as parameters of generics
347     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
348         self.record(&Some(*lifetime));
349     }
350
351     fn visit_ty(&mut self, ty: &'tcx Ty) {
352         match ty.node {
353             TyKind::Rptr(ref lt, _) if lt.is_elided() => {
354                 self.record(&None);
355             },
356             TyKind::Path(ref path) => {
357
358                 self.collect_anonymous_lifetimes(path, ty);
359             }
360             TyKind::Def(item, _) => {
361                 if let ItemKind::Existential(ref exist_ty) = self.cx.tcx.hir.expect_item(item.id).node {
362                     for bound in &exist_ty.bounds {
363                         if let GenericBound::Outlives(_) = *bound {
364                             self.record(&None);
365                         }
366                     }
367                 } else {
368                     unreachable!()
369                 }
370                 walk_ty(self, ty);
371             }
372             TyKind::TraitObject(ref bounds, ref lt) => {
373                 if !lt.is_elided() {
374                     self.abort = true;
375                 }
376                 for bound in bounds {
377                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
378                 }
379                 return;
380             },
381             _ => (),
382         }
383         walk_ty(self, ty);
384     }
385     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
386         NestedVisitorMap::None
387     }
388 }
389
390 /// Are any lifetimes mentioned in the `where` clause? If yes, we don't try to
391 /// reason about elision.
392 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
393     for predicate in &where_clause.predicates {
394         match *predicate {
395             WherePredicate::RegionPredicate(..) => return true,
396             WherePredicate::BoundPredicate(ref pred) => {
397                 // a predicate like F: Trait or F: for<'a> Trait<'a>
398                 let mut visitor = RefVisitor::new(cx);
399                 // walk the type F, it may not contain LT refs
400                 walk_ty(&mut visitor, &pred.bounded_ty);
401                 if !visitor.lts.is_empty() {
402                     return true;
403                 }
404                 // if the bounds define new lifetimes, they are fine to occur
405                 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
406                 // now walk the bounds
407                 for bound in pred.bounds.iter() {
408                     walk_param_bound(&mut visitor, bound);
409                 }
410                 // and check that all lifetimes are allowed
411                 match visitor.into_vec() {
412                     None => return false,
413                     Some(lts) => for lt in lts {
414                         if !allowed_lts.contains(&lt) {
415                             return true;
416                         }
417                     },
418                 }
419             },
420             WherePredicate::EqPredicate(ref pred) => {
421                 let mut visitor = RefVisitor::new(cx);
422                 walk_ty(&mut visitor, &pred.lhs_ty);
423                 walk_ty(&mut visitor, &pred.rhs_ty);
424                 if !visitor.lts.is_empty() {
425                     return true;
426                 }
427             },
428         }
429     }
430     false
431 }
432
433 struct LifetimeChecker {
434     map: FxHashMap<Name, Span>,
435 }
436
437 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
438     // for lifetimes as parameters of generics
439     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
440         self.map.remove(&lifetime.name.ident().name);
441     }
442
443     fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
444         // don't actually visit `<'a>` or `<'a: 'b>`
445         // we've already visited the `'a` declarations and
446         // don't want to spuriously remove them
447         // `'b` in `'a: 'b` is useless unless used elsewhere in
448         // a non-lifetime bound
449         if let GenericParamKind::Type { .. } = param.kind {
450             walk_generic_param(self, param)
451         }
452     }
453     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
454         NestedVisitorMap::None
455     }
456 }
457
458 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
459     let hs = generics.params.iter()
460         .filter_map(|par| match par.kind {
461             GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
462             _ => None,
463         })
464         .collect();
465     let mut checker = LifetimeChecker { map: hs };
466
467     walk_generics(&mut checker, generics);
468     walk_fn_decl(&mut checker, func);
469
470     for &v in checker.map.values() {
471         span_lint(cx, EXTRA_UNUSED_LIFETIMES, v, "this lifetime isn't used in the function definition");
472     }
473 }
474
475 struct BodyLifetimeChecker {
476     lifetimes_used_in_body: bool,
477 }
478
479 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
480     // for lifetimes as parameters of generics
481     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
482         if lifetime.name.ident().name != keywords::Invalid.name() && lifetime.name.ident().name != "'static" {
483             self.lifetimes_used_in_body = true;
484         }
485     }
486
487     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
488         NestedVisitorMap::None
489     }
490 }