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