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,
9 use rustc_hir::FnRetTy::Return;
11 BareFnTy, BodyId, FnDecl, GenericArg, GenericBound, GenericParam, GenericParamKind, Generics, Impl, ImplItem,
12 ImplItemKind, Item, ItemKind, LangItem, Lifetime, LifetimeName, ParamName, PolyTraitRef, PredicateOrigin,
13 TraitBoundModifier, TraitFn, TraitItem, TraitItemKind, Ty, TyKind, WherePredicate,
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};
21 declare_clippy_lint! {
23 /// Checks for lifetime annotations which can be removed by
24 /// relying on lifetime elision.
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.
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`.
39 /// // Unnecessary lifetime annotations
40 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
47 /// fn elided(x: &u8, y: u8) -> &u8 {
51 #[clippy::version = "pre 1.29.0"]
52 pub NEEDLESS_LIFETIMES,
54 "using explicit lifetimes for references in function arguments when elision rules \
55 would allow omitting them"
58 declare_clippy_lint! {
60 /// Checks for lifetimes in generics that are never used
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.
70 /// // unnecessary lifetimes
71 /// fn unused_lifetime<'a>(x: u8) {
78 /// fn no_lifetime(x: u8) {
82 #[clippy::version = "pre 1.29.0"]
83 pub EXTRA_UNUSED_LIFETIMES,
85 "unused lifetimes in function definitions"
88 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
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 report_extra_impl_lifetimes(cx, impl_);
99 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
100 if let ImplItemKind::Fn(ref sig, id) = item.kind {
101 let report_extra_lifetimes = trait_ref_of_method(cx, item.def_id).is_none();
109 report_extra_lifetimes,
114 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
115 if let TraitItemKind::Fn(ref sig, ref body) = item.kind {
116 let (body, trait_sig) = match *body {
117 TraitFn::Required(sig) => (None, Some(sig)),
118 TraitFn::Provided(id) => (Some(id), None),
120 check_fn_inner(cx, sig.decl, body, trait_sig, item.generics, item.span, true);
125 /// The lifetime of a &-reference.
126 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
133 fn check_fn_inner<'tcx>(
134 cx: &LateContext<'tcx>,
135 decl: &'tcx FnDecl<'_>,
136 body: Option<BodyId>,
137 trait_sig: Option<&[Ident]>,
138 generics: &'tcx Generics<'_>,
140 report_extra_lifetimes: bool,
142 if span.from_expansion() || has_where_lifetimes(cx, generics) {
149 .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
151 for pred in generics.bounds_for_param(cx.tcx.hir().local_def_id(typ.hir_id)) {
152 if pred.origin == PredicateOrigin::WhereClause {
153 // has_where_lifetimes checked that this predicate contains no lifetime.
157 for bound in pred.bounds {
158 let mut visitor = RefVisitor::new(cx);
159 walk_param_bound(&mut visitor, bound);
160 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
163 if let GenericBound::Trait(ref trait_ref, _) = *bound {
164 let params = &trait_ref
169 .expect("a path must have at least one segment")
171 if let Some(params) = *params {
172 let lifetimes = params.args.iter().filter_map(|arg| match arg {
173 GenericArg::Lifetime(lt) => Some(lt),
176 for bound in lifetimes {
177 if bound.name != LifetimeName::Static && !bound.is_elided() {
186 if could_use_elision(cx, decl, body, trait_sig, generics.params) {
190 span.with_hi(decl.output.span().hi()),
191 "explicit lifetimes given in parameter types where they could be elided \
192 (or replaced with `'_` if needed by type declaration)",
195 if report_extra_lifetimes {
196 self::report_extra_lifetimes(cx, decl, generics);
200 // elision doesn't work for explicit self types, see rust-lang/rust#69064
201 fn explicit_self_type<'tcx>(cx: &LateContext<'tcx>, func: &FnDecl<'tcx>, ident: Option<Ident>) -> bool {
203 if let Some(ident) = ident;
204 if ident.name == kw::SelfLower;
205 if !func.implicit_self.has_implicit_self();
207 if let Some(self_ty) = func.inputs.first();
209 let mut visitor = RefVisitor::new(cx);
210 visitor.visit_ty(self_ty);
212 !visitor.all_lts().is_empty()
219 fn could_use_elision<'tcx>(
220 cx: &LateContext<'tcx>,
221 func: &'tcx FnDecl<'_>,
222 body: Option<BodyId>,
223 trait_sig: Option<&[Ident]>,
224 named_generics: &'tcx [GenericParam<'_>],
226 // There are two scenarios where elision works:
227 // * no output references, all input references have different LT
228 // * output references, exactly one input reference with same LT
229 // All lifetimes must be unnamed, 'static or defined without bounds on the
230 // level of the current item.
233 let allowed_lts = allowed_lts_from(named_generics);
235 // these will collect all the lifetimes for references in arg/return types
236 let mut input_visitor = RefVisitor::new(cx);
237 let mut output_visitor = RefVisitor::new(cx);
239 // extract lifetimes in input argument types
240 for arg in func.inputs {
241 input_visitor.visit_ty(arg);
243 // extract lifetimes in output type
244 if let Return(ty) = func.output {
245 output_visitor.visit_ty(ty);
247 for lt in named_generics {
248 input_visitor.visit_generic_param(lt);
251 if input_visitor.abort() || output_visitor.abort() {
258 .nested_elision_site_lts
260 .chain(output_visitor.nested_elision_site_lts.iter())
262 .filter(|v| matches!(v, RefLt::Named(_)))
271 let input_lts = input_visitor.lts;
272 let output_lts = output_visitor.lts;
274 if let Some(trait_sig) = trait_sig {
275 if explicit_self_type(cx, func, trait_sig.first().copied()) {
280 if let Some(body_id) = body {
281 let body = cx.tcx.hir().body(body_id);
283 let first_ident = body.params.first().and_then(|param| param.pat.simple_ident());
284 if explicit_self_type(cx, func, first_ident) {
288 let mut checker = BodyLifetimeChecker {
289 lifetimes_used_in_body: false,
291 checker.visit_expr(&body.value);
292 if checker.lifetimes_used_in_body {
297 // check for lifetimes from higher scopes
298 for lt in input_lts.iter().chain(output_lts.iter()) {
299 if !allowed_lts.contains(lt) {
304 // no input lifetimes? easy case!
305 if input_lts.is_empty() {
307 } else if output_lts.is_empty() {
308 // no output lifetimes, check distinctness of input lifetimes
310 // only unnamed and static, ok
311 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
312 if unnamed_and_static {
315 // we have no output reference, so we only need all distinct lifetimes
316 input_lts.len() == unique_lifetimes(&input_lts)
318 // we have output references, so we need one input reference,
319 // and all output lifetimes must be the same
320 if unique_lifetimes(&output_lts) > 1 {
323 if input_lts.len() == 1 {
324 match (&input_lts[0], &output_lts[0]) {
325 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
326 (&RefLt::Named(_), &RefLt::Unnamed) => true,
327 _ => false, /* already elided, different named lifetimes
328 * or something static going on */
336 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
337 let mut allowed_lts = FxHashSet::default();
338 for par in named_generics.iter() {
339 if let GenericParamKind::Lifetime { .. } = par.kind {
340 allowed_lts.insert(RefLt::Named(par.name.ident().name));
343 allowed_lts.insert(RefLt::Unnamed);
344 allowed_lts.insert(RefLt::Static);
348 /// Number of unique lifetimes in the given vector.
350 fn unique_lifetimes(lts: &[RefLt]) -> usize {
351 lts.iter().collect::<FxHashSet<_>>().len()
354 const CLOSURE_TRAIT_BOUNDS: [LangItem; 3] = [LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
356 /// A visitor usable for `rustc_front::visit::walk_ty()`.
357 struct RefVisitor<'a, 'tcx> {
358 cx: &'a LateContext<'tcx>,
360 nested_elision_site_lts: Vec<RefLt>,
361 unelided_trait_object_lifetime: bool,
364 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
365 fn new(cx: &'a LateContext<'tcx>) -> Self {
369 nested_elision_site_lts: Vec::new(),
370 unelided_trait_object_lifetime: false,
374 fn record(&mut self, lifetime: &Option<Lifetime>) {
375 if let Some(ref lt) = *lifetime {
376 if lt.name == LifetimeName::Static {
377 self.lts.push(RefLt::Static);
378 } else if let LifetimeName::Param(_, ParamName::Fresh) = lt.name {
379 // Fresh lifetimes generated should be ignored.
380 } else if lt.is_elided() {
381 self.lts.push(RefLt::Unnamed);
383 self.lts.push(RefLt::Named(lt.name.ident().name));
386 self.lts.push(RefLt::Unnamed);
390 fn all_lts(&self) -> Vec<RefLt> {
393 .chain(self.nested_elision_site_lts.iter())
398 fn abort(&self) -> bool {
399 self.unelided_trait_object_lifetime
403 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
404 // for lifetimes as parameters of generics
405 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
406 self.record(&Some(*lifetime));
409 fn visit_poly_trait_ref(&mut self, poly_tref: &'tcx PolyTraitRef<'tcx>, tbm: TraitBoundModifier) {
410 let trait_ref = &poly_tref.trait_ref;
411 if CLOSURE_TRAIT_BOUNDS.iter().any(|&item| {
416 .map_or(false, |id| Some(id) == trait_ref.trait_def_id())
418 let mut sub_visitor = RefVisitor::new(self.cx);
419 sub_visitor.visit_trait_ref(trait_ref);
420 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
422 walk_poly_trait_ref(self, poly_tref, tbm);
426 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
428 TyKind::OpaqueDef(item, bounds) => {
429 let map = self.cx.tcx.hir();
430 let item = map.item(item);
431 walk_item(self, item);
433 self.lts.extend(bounds.iter().filter_map(|bound| match bound {
434 GenericArg::Lifetime(l) => Some(RefLt::Named(l.name.ident().name)),
438 TyKind::BareFn(&BareFnTy { decl, .. }) => {
439 let mut sub_visitor = RefVisitor::new(self.cx);
440 sub_visitor.visit_fn_decl(decl);
441 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
444 TyKind::TraitObject(bounds, ref lt, _) => {
446 self.unelided_trait_object_lifetime = true;
448 for bound in bounds {
449 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
459 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
460 /// reason about elision.
461 fn has_where_lifetimes<'tcx>(cx: &LateContext<'tcx>, generics: &'tcx Generics<'_>) -> bool {
462 for predicate in generics.predicates {
464 WherePredicate::RegionPredicate(..) => return true,
465 WherePredicate::BoundPredicate(ref pred) => {
466 // a predicate like F: Trait or F: for<'a> Trait<'a>
467 let mut visitor = RefVisitor::new(cx);
468 // walk the type F, it may not contain LT refs
469 walk_ty(&mut visitor, pred.bounded_ty);
470 if !visitor.all_lts().is_empty() {
473 // if the bounds define new lifetimes, they are fine to occur
474 let allowed_lts = allowed_lts_from(pred.bound_generic_params);
475 // now walk the bounds
476 for bound in pred.bounds.iter() {
477 walk_param_bound(&mut visitor, bound);
479 // and check that all lifetimes are allowed
480 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
484 WherePredicate::EqPredicate(ref pred) => {
485 let mut visitor = RefVisitor::new(cx);
486 walk_ty(&mut visitor, pred.lhs_ty);
487 walk_ty(&mut visitor, pred.rhs_ty);
488 if !visitor.lts.is_empty() {
497 struct LifetimeChecker<'cx, 'tcx, F> {
498 cx: &'cx LateContext<'tcx>,
499 map: FxHashMap<Symbol, Span>,
500 phantom: std::marker::PhantomData<F>,
503 impl<'cx, 'tcx, F> LifetimeChecker<'cx, 'tcx, F> {
504 fn new(cx: &'cx LateContext<'tcx>, map: FxHashMap<Symbol, Span>) -> LifetimeChecker<'cx, 'tcx, F> {
508 phantom: std::marker::PhantomData,
513 impl<'cx, 'tcx, F> Visitor<'tcx> for LifetimeChecker<'cx, 'tcx, F>
515 F: NestedFilter<'tcx>,
517 type Map = rustc_middle::hir::map::Map<'tcx>;
518 type NestedFilter = F;
520 // for lifetimes as parameters of generics
521 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
522 self.map.remove(&lifetime.name.ident().name);
525 fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
526 // don't actually visit `<'a>` or `<'a: 'b>`
527 // we've already visited the `'a` declarations and
528 // don't want to spuriously remove them
529 // `'b` in `'a: 'b` is useless unless used elsewhere in
530 // a non-lifetime bound
531 if let GenericParamKind::Type { .. } = param.kind {
532 walk_generic_param(self, param);
536 fn nested_visit_map(&mut self) -> Self::Map {
541 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
545 .filter_map(|par| match par.kind {
546 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
550 let mut checker = LifetimeChecker::<hir_nested_filter::None>::new(cx, hs);
552 walk_generics(&mut checker, generics);
553 walk_fn_decl(&mut checker, func);
555 for &v in checker.map.values() {
558 EXTRA_UNUSED_LIFETIMES,
560 "this lifetime isn't used in the function definition",
565 fn report_extra_impl_lifetimes<'tcx>(cx: &LateContext<'tcx>, impl_: &'tcx Impl<'_>) {
570 .filter_map(|par| match par.kind {
571 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
575 let mut checker = LifetimeChecker::<middle_nested_filter::All>::new(cx, hs);
577 walk_generics(&mut checker, impl_.generics);
578 if let Some(ref trait_ref) = impl_.of_trait {
579 walk_trait_ref(&mut checker, trait_ref);
581 walk_ty(&mut checker, impl_.self_ty);
582 for item in impl_.items {
583 walk_impl_item_ref(&mut checker, item);
586 for &v in checker.map.values() {
587 span_lint(cx, EXTRA_UNUSED_LIFETIMES, v, "this lifetime isn't used in the impl");
591 struct BodyLifetimeChecker {
592 lifetimes_used_in_body: bool,
595 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
596 // for lifetimes as parameters of generics
597 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
598 if lifetime.name.ident().name != kw::Empty && lifetime.name.ident().name != kw::StaticLifetime {
599 self.lifetimes_used_in_body = true;