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