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