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