]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / lifetimes.rs
1 use matches::matches;
2 use rustc::hir::def::Def;
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_tool_lint, lint_array};
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use syntax::source_map::Span;
9 use syntax::symbol::keywords;
10
11 use crate::reexport::*;
12 use crate::utils::{last_path_segment, span_lint};
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 #[derive(Copy, Clone)]
59 pub struct LifetimePass;
60
61 impl LintPass for LifetimePass {
62     fn get_lints(&self) -> LintArray {
63         lint_array!(NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES)
64     }
65
66     fn name(&self) -> &'static str {
67         "LifeTimes"
68     }
69 }
70
71 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LifetimePass {
72     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
73         if let ItemKind::Fn(ref decl, _, ref generics, id) = item.node {
74             check_fn_inner(cx, decl, Some(id), generics, item.span);
75         }
76     }
77
78     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
79         if let ImplItemKind::Method(ref sig, id) = item.node {
80             check_fn_inner(cx, &sig.decl, Some(id), &item.generics, item.span);
81         }
82     }
83
84     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
85         if let TraitItemKind::Method(ref sig, ref body) = item.node {
86             let body = match *body {
87                 TraitMethod::Required(_) => None,
88                 TraitMethod::Provided(id) => Some(id),
89             };
90             check_fn_inner(cx, &sig.decl, body, &item.generics, item.span);
91         }
92     }
93 }
94
95 /// The lifetime of a &-reference.
96 #[derive(PartialEq, Eq, Hash, Debug)]
97 enum RefLt {
98     Unnamed,
99     Static,
100     Named(Name),
101 }
102
103 fn check_fn_inner<'a, 'tcx>(
104     cx: &LateContext<'a, 'tcx>,
105     decl: &'tcx FnDecl,
106     body: Option<BodyId>,
107     generics: &'tcx Generics,
108     span: Span,
109 ) {
110     if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
111         return;
112     }
113
114     let mut bounds_lts = Vec::new();
115     let types = generics.params.iter().filter(|param| match param.kind {
116         GenericParamKind::Type { .. } => true,
117         _ => false,
118     });
119     for typ in types {
120         for bound in &typ.bounds {
121             let mut visitor = RefVisitor::new(cx);
122             walk_param_bound(&mut visitor, bound);
123             if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
124                 return;
125             }
126             if let GenericBound::Trait(ref trait_ref, _) = *bound {
127                 let params = &trait_ref
128                     .trait_ref
129                     .path
130                     .segments
131                     .last()
132                     .expect("a path must have at least one segment")
133                     .args;
134                 if let Some(ref params) = *params {
135                     let lifetimes = params.args.iter().filter_map(|arg| match arg {
136                         GenericArg::Lifetime(lt) => Some(lt),
137                         _ => None,
138                     });
139                     for bound in lifetimes {
140                         if bound.name != LifetimeName::Static && !bound.is_elided() {
141                             return;
142                         }
143                         bounds_lts.push(bound);
144                     }
145                 }
146             }
147         }
148     }
149     if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
150         span_lint(
151             cx,
152             NEEDLESS_LIFETIMES,
153             span,
154             "explicit lifetimes given in parameter types where they could be elided \
155              (or replaced with `'_` if needed by type declaration)",
156         );
157     }
158     report_extra_lifetimes(cx, decl, generics);
159 }
160
161 fn could_use_elision<'a, 'tcx: 'a>(
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 fn unique_lifetimes(lts: &[RefLt]) -> usize {
274     lts.iter().collect::<FxHashSet<_>>().len()
275 }
276
277 /// A visitor usable for `rustc_front::visit::walk_ty()`.
278 struct RefVisitor<'a, 'tcx: 'a> {
279     cx: &'a LateContext<'a, 'tcx>,
280     lts: Vec<RefLt>,
281     abort: bool,
282 }
283
284 impl<'v, 't> RefVisitor<'v, 't> {
285     fn new(cx: &'v LateContext<'v, 't>) -> Self {
286         Self {
287             cx,
288             lts: Vec::new(),
289             abort: false,
290         }
291     }
292
293     fn record(&mut self, lifetime: &Option<Lifetime>) {
294         if let Some(ref lt) = *lifetime {
295             if lt.name == LifetimeName::Static {
296                 self.lts.push(RefLt::Static);
297             } else if lt.is_elided() {
298                 self.lts.push(RefLt::Unnamed);
299             } else {
300                 self.lts.push(RefLt::Named(lt.name.ident().name));
301             }
302         } else {
303             self.lts.push(RefLt::Unnamed);
304         }
305     }
306
307     fn into_vec(self) -> Option<Vec<RefLt>> {
308         if self.abort {
309             None
310         } else {
311             Some(self.lts)
312         }
313     }
314
315     fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
316         if let Some(ref last_path_segment) = last_path_segment(qpath).args {
317             if !last_path_segment.parenthesized
318                 && !last_path_segment.args.iter().any(|arg| match arg {
319                     GenericArg::Lifetime(_) => true,
320                     _ => false,
321                 })
322             {
323                 let hir_id = ty.hir_id;
324                 match self.cx.tables.qpath_def(qpath, hir_id) {
325                     Def::TyAlias(def_id) | Def::Struct(def_id) => {
326                         let generics = self.cx.tcx.generics_of(def_id);
327                         for _ in generics.params.as_slice() {
328                             self.record(&None);
329                         }
330                     },
331                     Def::Trait(def_id) => {
332                         let trait_def = self.cx.tcx.trait_def(def_id);
333                         for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
334                             self.record(&None);
335                         }
336                     },
337                     _ => (),
338                 }
339             }
340         }
341     }
342 }
343
344 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
345     // for lifetimes as parameters of generics
346     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
347         self.record(&Some(*lifetime));
348     }
349
350     fn visit_ty(&mut self, ty: &'tcx Ty) {
351         match ty.node {
352             TyKind::Rptr(ref lt, _) if lt.is_elided() => {
353                 self.record(&None);
354             },
355             TyKind::Path(ref path) => {
356                 self.collect_anonymous_lifetimes(path, ty);
357             },
358             TyKind::Def(item, _) => {
359                 let map = self.cx.tcx.hir();
360                 if let ItemKind::Existential(ref exist_ty) = map.expect_item(map.hir_to_node_id(item.id)).node {
361                     for bound in &exist_ty.bounds {
362                         if let GenericBound::Outlives(_) = *bound {
363                             self.record(&None);
364                         }
365                     }
366                 } else {
367                     unreachable!()
368                 }
369                 walk_ty(self, ty);
370             },
371             TyKind::TraitObject(ref bounds, ref lt) => {
372                 if !lt.is_elided() {
373                     self.abort = true;
374                 }
375                 for bound in bounds {
376                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
377                 }
378                 return;
379             },
380             _ => (),
381         }
382         walk_ty(self, ty);
383     }
384     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
385         NestedVisitorMap::None
386     }
387 }
388
389 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
390 /// reason about elision.
391 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
392     for predicate in &where_clause.predicates {
393         match *predicate {
394             WherePredicate::RegionPredicate(..) => return true,
395             WherePredicate::BoundPredicate(ref pred) => {
396                 // a predicate like F: Trait or F: for<'a> Trait<'a>
397                 let mut visitor = RefVisitor::new(cx);
398                 // walk the type F, it may not contain LT refs
399                 walk_ty(&mut visitor, &pred.bounded_ty);
400                 if !visitor.lts.is_empty() {
401                     return true;
402                 }
403                 // if the bounds define new lifetimes, they are fine to occur
404                 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
405                 // now walk the bounds
406                 for bound in pred.bounds.iter() {
407                     walk_param_bound(&mut visitor, bound);
408                 }
409                 // and check that all lifetimes are allowed
410                 match visitor.into_vec() {
411                     None => return false,
412                     Some(lts) => {
413                         for lt in lts {
414                             if !allowed_lts.contains(&lt) {
415                                 return true;
416                             }
417                         }
418                     },
419                 }
420             },
421             WherePredicate::EqPredicate(ref pred) => {
422                 let mut visitor = RefVisitor::new(cx);
423                 walk_ty(&mut visitor, &pred.lhs_ty);
424                 walk_ty(&mut visitor, &pred.rhs_ty);
425                 if !visitor.lts.is_empty() {
426                     return true;
427                 }
428             },
429         }
430     }
431     false
432 }
433
434 struct LifetimeChecker {
435     map: FxHashMap<Name, Span>,
436 }
437
438 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
439     // for lifetimes as parameters of generics
440     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
441         self.map.remove(&lifetime.name.ident().name);
442     }
443
444     fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
445         // don't actually visit `<'a>` or `<'a: 'b>`
446         // we've already visited the `'a` declarations and
447         // don't want to spuriously remove them
448         // `'b` in `'a: 'b` is useless unless used elsewhere in
449         // a non-lifetime bound
450         if let GenericParamKind::Type { .. } = param.kind {
451             walk_generic_param(self, param)
452         }
453     }
454     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
455         NestedVisitorMap::None
456     }
457 }
458
459 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
460     let hs = generics
461         .params
462         .iter()
463         .filter_map(|par| match par.kind {
464             GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
465             _ => None,
466         })
467         .collect();
468     let mut checker = LifetimeChecker { map: hs };
469
470     walk_generics(&mut checker, generics);
471     walk_fn_decl(&mut checker, func);
472
473     for &v in checker.map.values() {
474         span_lint(
475             cx,
476             EXTRA_UNUSED_LIFETIMES,
477             v,
478             "this lifetime isn't used in the function definition",
479         );
480     }
481 }
482
483 struct BodyLifetimeChecker {
484     lifetimes_used_in_body: bool,
485 }
486
487 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
488     // for lifetimes as parameters of generics
489     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
490         if lifetime.name.ident().name != keywords::Invalid.name() && lifetime.name.ident().name != "'static" {
491             self.lifetimes_used_in_body = true;
492         }
493     }
494
495     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
496         NestedVisitorMap::None
497     }
498 }