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