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