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_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};
23 declare_clippy_lint! {
25 /// Checks for lifetime annotations which can be removed by
26 /// relying on lifetime elision.
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.
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`.
41 /// // Unnecessary lifetime annotations
42 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
49 /// fn elided(x: &u8, y: u8) -> &u8 {
53 #[clippy::version = "pre 1.29.0"]
54 pub NEEDLESS_LIFETIMES,
56 "using explicit lifetimes for references in function arguments when elision rules \
57 would allow omitting them"
60 declare_clippy_lint! {
62 /// Checks for lifetimes in generics that are never used
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.
72 /// // unnecessary lifetimes
73 /// fn unused_lifetime<'a>(x: u8) {
80 /// fn no_lifetime(x: u8) {
84 #[clippy::version = "pre 1.29.0"]
85 pub EXTRA_UNUSED_LIFETIMES,
87 "unused lifetimes in function definitions"
90 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
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_);
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();
113 report_extra_lifetimes,
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),
124 check_fn_inner(cx, sig.decl, body, trait_sig, item.generics, item.span, true);
129 /// The lifetime of a &-reference.
130 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
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<'_>,
144 report_extra_lifetimes: bool,
146 if span.from_expansion() || has_where_lifetimes(cx, generics) {
153 .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
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.
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(_))) {
167 if let GenericBound::Trait(ref trait_ref, _) = *bound {
168 let params = &trait_ref
173 .expect("a path must have at least one segment")
175 if let Some(params) = *params {
176 let lifetimes = params.args.iter().filter_map(|arg| match arg {
177 GenericArg::Lifetime(lt) => Some(lt),
180 for bound in lifetimes {
181 if bound.name != LifetimeName::Static && !bound.is_elided() {
190 if could_use_elision(cx, decl, body, trait_sig, generics.params) {
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)",
199 if report_extra_lifetimes {
200 self::report_extra_lifetimes(cx, decl, generics);
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 {
207 if let Some(ident) = ident;
208 if ident.name == kw::SelfLower;
209 if !func.implicit_self.has_implicit_self();
211 if let Some(self_ty) = func.inputs.first();
213 let mut visitor = RefVisitor::new(cx);
214 visitor.visit_ty(self_ty);
216 !visitor.all_lts().is_empty()
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<'_>],
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.
237 let allowed_lts = allowed_lts_from(cx.tcx, named_generics);
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);
243 // extract lifetimes in input argument types
244 for arg in func.inputs {
245 input_visitor.visit_ty(arg);
247 // extract lifetimes in output type
248 if let Return(ty) = func.output {
249 output_visitor.visit_ty(ty);
251 for lt in named_generics {
252 input_visitor.visit_generic_param(lt);
255 if input_visitor.abort() || output_visitor.abort() {
259 let input_lts = input_visitor.lts;
260 let output_lts = output_visitor.lts;
262 if let Some(trait_sig) = trait_sig {
263 if explicit_self_type(cx, func, trait_sig.first().copied()) {
268 if let Some(body_id) = body {
269 let body = cx.tcx.hir().body(body_id);
271 let first_ident = body.params.first().and_then(|param| param.pat.simple_ident());
272 if explicit_self_type(cx, func, first_ident) {
276 let mut checker = BodyLifetimeChecker {
277 lifetimes_used_in_body: false,
279 checker.visit_expr(body.value);
280 if checker.lifetimes_used_in_body {
285 // check for lifetimes from higher scopes
286 for lt in input_lts.iter().chain(output_lts.iter()) {
287 if !allowed_lts.contains(lt) {
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
296 .filter_map(|lt| match lt {
297 RefLt::Named(def_id) => Some(cx.tcx.item_name(def_id.to_def_id())),
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())) {
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())) {
317 // no input lifetimes? easy case!
318 if input_lts.is_empty() {
320 } else if output_lts.is_empty() {
321 // no output lifetimes, check distinctness of input lifetimes
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 {
328 // we have no output reference, so we only need all distinct lifetimes
329 input_lts.len() == unique_lifetimes(&input_lts)
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 {
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 */
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)));
356 allowed_lts.insert(RefLt::Unnamed);
357 allowed_lts.insert(RefLt::Static);
361 /// Number of unique lifetimes in the given vector.
363 fn unique_lifetimes(lts: &[RefLt]) -> usize {
364 lts.iter().collect::<FxHashSet<_>>().len()
367 const CLOSURE_TRAIT_BOUNDS: [LangItem; 3] = [LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
369 /// A visitor usable for `rustc_front::visit::walk_ty()`.
370 struct RefVisitor<'a, 'tcx> {
371 cx: &'a LateContext<'tcx>,
373 nested_elision_site_lts: Vec<RefLt>,
374 unelided_trait_object_lifetime: bool,
377 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
378 fn new(cx: &'a LateContext<'tcx>) -> Self {
382 nested_elision_site_lts: Vec::new(),
383 unelided_trait_object_lifetime: false,
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));
399 self.lts.push(RefLt::Unnamed);
402 self.lts.push(RefLt::Unnamed);
406 fn all_lts(&self) -> Vec<RefLt> {
409 .chain(self.nested_elision_site_lts.iter())
414 fn abort(&self) -> bool {
415 self.unelided_trait_object_lifetime
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));
425 fn visit_poly_trait_ref(&mut self, poly_tref: &'tcx PolyTraitRef<'tcx>, tbm: TraitBoundModifier) {
426 let trait_ref = &poly_tref.trait_ref;
427 if CLOSURE_TRAIT_BOUNDS.iter().any(|&item| {
432 .map_or(false, |id| Some(id) == trait_ref.trait_def_id())
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());
438 walk_poly_trait_ref(self, poly_tref, tbm);
442 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
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 {
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());
464 TyKind::TraitObject(bounds, ref lt, _) => {
466 self.unelided_trait_object_lifetime = true;
468 for bound in bounds {
469 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
472 _ => walk_ty(self, ty),
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 {
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() {
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);
497 // and check that all lifetimes are allowed
498 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
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() {
515 struct LifetimeChecker<'cx, 'tcx, F> {
516 cx: &'cx LateContext<'tcx>,
517 map: FxHashMap<Symbol, Span>,
518 phantom: std::marker::PhantomData<F>,
521 impl<'cx, 'tcx, F> LifetimeChecker<'cx, 'tcx, F> {
522 fn new(cx: &'cx LateContext<'tcx>, map: FxHashMap<Symbol, Span>) -> LifetimeChecker<'cx, 'tcx, F> {
526 phantom: std::marker::PhantomData,
531 impl<'cx, 'tcx, F> Visitor<'tcx> for LifetimeChecker<'cx, 'tcx, F>
533 F: NestedFilter<'tcx>,
535 type Map = rustc_middle::hir::map::Map<'tcx>;
536 type NestedFilter = F;
538 // for lifetimes as parameters of generics
539 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
540 self.map.remove(&lifetime.name.ident().name);
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);
554 fn nested_visit_map(&mut self) -> Self::Map {
559 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
563 .filter_map(|par| match par.kind {
564 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
568 let mut checker = LifetimeChecker::<hir_nested_filter::None>::new(cx, hs);
570 walk_generics(&mut checker, generics);
571 walk_fn_decl(&mut checker, func);
573 for &v in checker.map.values() {
576 EXTRA_UNUSED_LIFETIMES,
578 "this lifetime isn't used in the function definition",
583 fn report_extra_impl_lifetimes<'tcx>(cx: &LateContext<'tcx>, impl_: &'tcx Impl<'_>) {
588 .filter_map(|par| match par.kind {
589 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
593 let mut checker = LifetimeChecker::<middle_nested_filter::All>::new(cx, hs);
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);
599 walk_ty(&mut checker, impl_.self_ty);
600 for item in impl_.items {
601 walk_impl_item_ref(&mut checker, item);
604 for &v in checker.map.values() {
605 span_lint(cx, EXTRA_UNUSED_LIFETIMES, v, "this lifetime isn't used in the impl");
609 struct BodyLifetimeChecker {
610 lifetimes_used_in_body: bool,
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;