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