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, LifetimeParamKind, ParamName, PolyTraitRef,
13 PredicateOrigin, 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 if !item.span.from_expansion() {
96 report_extra_impl_lifetimes(cx, impl_);
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();
111 report_extra_lifetimes,
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),
122 check_fn_inner(cx, sig.decl, body, trait_sig, item.generics, item.span, true);
127 /// The lifetime of a &-reference.
128 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
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<'_>,
142 report_extra_lifetimes: bool,
144 if span.from_expansion() || has_where_lifetimes(cx, generics) {
151 .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
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.
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(_))) {
165 if let GenericBound::Trait(ref trait_ref, _) = *bound {
166 let params = &trait_ref
171 .expect("a path must have at least one segment")
173 if let Some(params) = *params {
174 let lifetimes = params.args.iter().filter_map(|arg| match arg {
175 GenericArg::Lifetime(lt) => Some(lt),
178 for bound in lifetimes {
179 if bound.name != LifetimeName::Static && !bound.is_elided() {
188 if could_use_elision(cx, decl, body, trait_sig, generics.params) {
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)",
197 if report_extra_lifetimes {
198 self::report_extra_lifetimes(cx, decl, generics);
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 {
205 if let Some(ident) = ident;
206 if ident.name == kw::SelfLower;
207 if !func.implicit_self.has_implicit_self();
209 if let Some(self_ty) = func.inputs.first();
211 let mut visitor = RefVisitor::new(cx);
212 visitor.visit_ty(self_ty);
214 !visitor.all_lts().is_empty()
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<'_>],
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.
235 let allowed_lts = allowed_lts_from(named_generics);
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);
241 // extract lifetimes in input argument types
242 for arg in func.inputs {
243 input_visitor.visit_ty(arg);
245 // extract lifetimes in output type
246 if let Return(ty) = func.output {
247 output_visitor.visit_ty(ty);
249 for lt in named_generics {
250 input_visitor.visit_generic_param(lt);
253 if input_visitor.abort() || output_visitor.abort() {
260 .nested_elision_site_lts
262 .chain(output_visitor.nested_elision_site_lts.iter())
264 .filter(|v| matches!(v, RefLt::Named(_)))
273 let input_lts = input_visitor.lts;
274 let output_lts = output_visitor.lts;
276 if let Some(trait_sig) = trait_sig {
277 if explicit_self_type(cx, func, trait_sig.first().copied()) {
282 if let Some(body_id) = body {
283 let body = cx.tcx.hir().body(body_id);
285 let first_ident = body.params.first().and_then(|param| param.pat.simple_ident());
286 if explicit_self_type(cx, func, first_ident) {
290 let mut checker = BodyLifetimeChecker {
291 lifetimes_used_in_body: false,
293 checker.visit_expr(&body.value);
294 if checker.lifetimes_used_in_body {
299 // check for lifetimes from higher scopes
300 for lt in input_lts.iter().chain(output_lts.iter()) {
301 if !allowed_lts.contains(lt) {
306 // no input lifetimes? easy case!
307 if input_lts.is_empty() {
309 } else if output_lts.is_empty() {
310 // no output lifetimes, check distinctness of input lifetimes
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 {
317 // we have no output reference, so we only need all distinct lifetimes
318 input_lts.len() == unique_lifetimes(&input_lts)
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 {
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 */
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,
345 allowed_lts.insert(RefLt::Named(par.name.ident().name));
348 allowed_lts.insert(RefLt::Unnamed);
349 allowed_lts.insert(RefLt::Static);
353 /// Number of unique lifetimes in the given vector.
355 fn unique_lifetimes(lts: &[RefLt]) -> usize {
356 lts.iter().collect::<FxHashSet<_>>().len()
359 const CLOSURE_TRAIT_BOUNDS: [LangItem; 3] = [LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
361 /// A visitor usable for `rustc_front::visit::walk_ty()`.
362 struct RefVisitor<'a, 'tcx> {
363 cx: &'a LateContext<'tcx>,
365 nested_elision_site_lts: Vec<RefLt>,
366 unelided_trait_object_lifetime: bool,
369 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
370 fn new(cx: &'a LateContext<'tcx>) -> Self {
374 nested_elision_site_lts: Vec::new(),
375 unelided_trait_object_lifetime: false,
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);
389 self.lts.push(RefLt::Named(lt.name.ident().name));
392 self.lts.push(RefLt::Unnamed);
396 fn all_lts(&self) -> Vec<RefLt> {
399 .chain(self.nested_elision_site_lts.iter())
404 fn abort(&self) -> bool {
405 self.unelided_trait_object_lifetime
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));
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| {
422 .map_or(false, |id| Some(id) == trait_ref.trait_def_id())
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());
428 walk_poly_trait_ref(self, poly_tref, tbm);
432 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
434 TyKind::OpaqueDef(item, bounds) => {
435 let map = self.cx.tcx.hir();
436 let item = map.item(item);
437 walk_item(self, item);
439 self.lts.extend(bounds.iter().filter_map(|bound| match bound {
440 GenericArg::Lifetime(l) => Some(RefLt::Named(l.name.ident().name)),
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());
450 TyKind::TraitObject(bounds, ref lt, _) => {
452 self.unelided_trait_object_lifetime = true;
454 for bound in bounds {
455 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
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 {
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() {
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);
485 // and check that all lifetimes are allowed
486 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
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() {
503 struct LifetimeChecker<'cx, 'tcx, F> {
504 cx: &'cx LateContext<'tcx>,
505 map: FxHashMap<Symbol, Span>,
506 phantom: std::marker::PhantomData<F>,
509 impl<'cx, 'tcx, F> LifetimeChecker<'cx, 'tcx, F> {
510 fn new(cx: &'cx LateContext<'tcx>, map: FxHashMap<Symbol, Span>) -> LifetimeChecker<'cx, 'tcx, F> {
514 phantom: std::marker::PhantomData,
519 impl<'cx, 'tcx, F> Visitor<'tcx> for LifetimeChecker<'cx, 'tcx, F>
521 F: NestedFilter<'tcx>,
523 type Map = rustc_middle::hir::map::Map<'tcx>;
524 type NestedFilter = F;
526 // for lifetimes as parameters of generics
527 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
528 self.map.remove(&lifetime.name.ident().name);
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);
542 fn nested_visit_map(&mut self) -> Self::Map {
547 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
551 .filter_map(|par| match par.kind {
552 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
556 let mut checker = LifetimeChecker::<hir_nested_filter::None>::new(cx, hs);
558 walk_generics(&mut checker, generics);
559 walk_fn_decl(&mut checker, func);
561 for &v in checker.map.values() {
564 EXTRA_UNUSED_LIFETIMES,
566 "this lifetime isn't used in the function definition",
571 fn report_extra_impl_lifetimes<'tcx>(cx: &LateContext<'tcx>, impl_: &'tcx Impl<'_>) {
576 .filter_map(|par| match par.kind {
577 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
581 let mut checker = LifetimeChecker::<middle_nested_filter::All>::new(cx, hs);
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);
587 walk_ty(&mut checker, impl_.self_ty);
588 for item in impl_.items {
589 walk_impl_item_ref(&mut checker, item);
592 for &v in checker.map.values() {
593 span_lint(cx, EXTRA_UNUSED_LIFETIMES, v, "this lifetime isn't used in the impl");
597 struct BodyLifetimeChecker {
598 lifetimes_used_in_body: bool,
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;