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