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