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