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