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