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,
6 NestedVisitorMap, Visitor,
8 use rustc_hir::FnRetTy::Return;
10 BareFnTy, BodyId, FnDecl, GenericArg, GenericBound, GenericParam, GenericParamKind, Generics, ImplItem,
11 ImplItemKind, Item, ItemKind, LangItem, Lifetime, LifetimeName, ParamName, PolyTraitRef, TraitBoundModifier,
12 TraitFn, TraitItem, TraitItemKind, Ty, TyKind, WhereClause, WherePredicate,
14 use rustc_lint::{LateContext, LateLintPass};
15 use rustc_middle::hir::map::Map;
16 use rustc_session::{declare_lint_pass, declare_tool_lint};
17 use rustc_span::source_map::Span;
18 use rustc_span::symbol::{kw, Ident, Symbol};
20 declare_clippy_lint! {
22 /// Checks for lifetime annotations which can be removed by
23 /// relying on lifetime elision.
25 /// ### Why is this bad?
26 /// The additional lifetimes make the code look more
27 /// complicated, while there is nothing out of the ordinary going on. Removing
28 /// them leads to more readable code.
30 /// ### Known problems
31 /// - We bail out if the function has a `where` clause where lifetimes
32 /// are mentioned due to potential false positives.
33 /// - Lifetime bounds such as `impl Foo + 'a` and `T: 'a` must be elided with the
34 /// placeholder notation `'_` because the fully elided notation leaves the type bound to `'static`.
38 /// // Bad: unnecessary lifetime annotations
39 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
44 /// fn elided(x: &u8, y: u8) -> &u8 {
48 #[clippy::version = "pre 1.29.0"]
49 pub NEEDLESS_LIFETIMES,
51 "using explicit lifetimes for references in function arguments when elision rules \
52 would allow omitting them"
55 declare_clippy_lint! {
57 /// Checks for lifetimes in generics that are never used
60 /// ### Why is this bad?
61 /// The additional lifetimes make the code look more
62 /// complicated, while there is nothing out of the ordinary going on. Removing
63 /// them leads to more readable code.
67 /// // Bad: unnecessary lifetimes
68 /// fn unused_lifetime<'a>(x: u8) {
73 /// fn no_lifetime(x: u8) {
77 #[clippy::version = "pre 1.29.0"]
78 pub EXTRA_UNUSED_LIFETIMES,
80 "unused lifetimes in function definitions"
83 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
85 impl<'tcx> LateLintPass<'tcx> for Lifetimes {
86 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
87 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
88 check_fn_inner(cx, sig.decl, Some(id), None, generics, item.span, true);
92 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
93 if let ImplItemKind::Fn(ref sig, id) = item.kind {
94 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id()).is_none();
102 report_extra_lifetimes,
107 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
108 if let TraitItemKind::Fn(ref sig, ref body) = item.kind {
109 let (body, trait_sig) = match *body {
110 TraitFn::Required(sig) => (None, Some(sig)),
111 TraitFn::Provided(id) => (Some(id), None),
113 check_fn_inner(cx, sig.decl, body, trait_sig, &item.generics, item.span, true);
118 /// The lifetime of a &-reference.
119 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
126 fn check_fn_inner<'tcx>(
127 cx: &LateContext<'tcx>,
128 decl: &'tcx FnDecl<'_>,
129 body: Option<BodyId>,
130 trait_sig: Option<&[Ident]>,
131 generics: &'tcx Generics<'_>,
133 report_extra_lifetimes: bool,
135 if span.from_expansion() || has_where_lifetimes(cx, &generics.where_clause) {
142 .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
144 for bound in typ.bounds {
145 let mut visitor = RefVisitor::new(cx);
146 walk_param_bound(&mut visitor, bound);
147 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
150 if let GenericBound::Trait(ref trait_ref, _) = *bound {
151 let params = &trait_ref
156 .expect("a path must have at least one segment")
158 if let Some(params) = *params {
159 let lifetimes = params.args.iter().filter_map(|arg| match arg {
160 GenericArg::Lifetime(lt) => Some(lt),
163 for bound in lifetimes {
164 if bound.name != LifetimeName::Static && !bound.is_elided() {
172 if could_use_elision(cx, decl, body, trait_sig, generics.params) {
176 span.with_hi(decl.output.span().hi()),
177 "explicit lifetimes given in parameter types where they could be elided \
178 (or replaced with `'_` if needed by type declaration)",
181 if report_extra_lifetimes {
182 self::report_extra_lifetimes(cx, decl, generics);
186 // elision doesn't work for explicit self types, see rust-lang/rust#69064
187 fn explicit_self_type<'tcx>(cx: &LateContext<'tcx>, func: &FnDecl<'tcx>, ident: Option<Ident>) -> bool {
189 if let Some(ident) = ident;
190 if ident.name == kw::SelfLower;
191 if !func.implicit_self.has_implicit_self();
193 if let Some(self_ty) = func.inputs.first();
195 let mut visitor = RefVisitor::new(cx);
196 visitor.visit_ty(self_ty);
198 !visitor.all_lts().is_empty()
206 fn could_use_elision<'tcx>(
207 cx: &LateContext<'tcx>,
208 func: &'tcx FnDecl<'_>,
209 body: Option<BodyId>,
210 trait_sig: Option<&[Ident]>,
211 named_generics: &'tcx [GenericParam<'_>],
213 // There are two scenarios where elision works:
214 // * no output references, all input references have different LT
215 // * output references, exactly one input reference with same LT
216 // All lifetimes must be unnamed, 'static or defined without bounds on the
217 // level of the current item.
220 let allowed_lts = allowed_lts_from(named_generics);
222 // these will collect all the lifetimes for references in arg/return types
223 let mut input_visitor = RefVisitor::new(cx);
224 let mut output_visitor = RefVisitor::new(cx);
226 // extract lifetimes in input argument types
227 for arg in func.inputs {
228 input_visitor.visit_ty(arg);
230 // extract lifetimes in output type
231 if let Return(ty) = func.output {
232 output_visitor.visit_ty(ty);
234 for lt in named_generics {
235 input_visitor.visit_generic_param(lt);
238 if input_visitor.abort() || output_visitor.abort() {
245 .nested_elision_site_lts
247 .chain(output_visitor.nested_elision_site_lts.iter())
249 .filter(|v| matches!(v, RefLt::Named(_)))
258 let input_lts = input_visitor.lts;
259 let output_lts = output_visitor.lts;
261 if let Some(trait_sig) = trait_sig {
262 if explicit_self_type(cx, func, trait_sig.first().copied()) {
267 if let Some(body_id) = body {
268 let body = cx.tcx.hir().body(body_id);
270 let first_ident = body.params.first().and_then(|param| param.pat.simple_ident());
271 if explicit_self_type(cx, func, first_ident) {
275 let mut checker = BodyLifetimeChecker {
276 lifetimes_used_in_body: false,
278 checker.visit_expr(&body.value);
279 if checker.lifetimes_used_in_body {
284 // check for lifetimes from higher scopes
285 for lt in input_lts.iter().chain(output_lts.iter()) {
286 if !allowed_lts.contains(lt) {
291 // no input lifetimes? easy case!
292 if input_lts.is_empty() {
294 } else if output_lts.is_empty() {
295 // no output lifetimes, check distinctness of input lifetimes
297 // only unnamed and static, ok
298 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
299 if unnamed_and_static {
302 // we have no output reference, so we only need all distinct lifetimes
303 input_lts.len() == unique_lifetimes(&input_lts)
305 // we have output references, so we need one input reference,
306 // and all output lifetimes must be the same
307 if unique_lifetimes(&output_lts) > 1 {
310 if input_lts.len() == 1 {
311 match (&input_lts[0], &output_lts[0]) {
312 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
313 (&RefLt::Named(_), &RefLt::Unnamed) => true,
314 _ => false, /* already elided, different named lifetimes
315 * or something static going on */
323 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
324 let mut allowed_lts = FxHashSet::default();
325 for par in named_generics.iter() {
326 if let GenericParamKind::Lifetime { .. } = par.kind {
327 if par.bounds.is_empty() {
328 allowed_lts.insert(RefLt::Named(par.name.ident().name));
332 allowed_lts.insert(RefLt::Unnamed);
333 allowed_lts.insert(RefLt::Static);
337 /// Number of unique lifetimes in the given vector.
339 fn unique_lifetimes(lts: &[RefLt]) -> usize {
340 lts.iter().collect::<FxHashSet<_>>().len()
343 const CLOSURE_TRAIT_BOUNDS: [LangItem; 3] = [LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
345 /// A visitor usable for `rustc_front::visit::walk_ty()`.
346 struct RefVisitor<'a, 'tcx> {
347 cx: &'a LateContext<'tcx>,
349 nested_elision_site_lts: Vec<RefLt>,
350 unelided_trait_object_lifetime: bool,
353 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
354 fn new(cx: &'a LateContext<'tcx>) -> Self {
358 nested_elision_site_lts: Vec::new(),
359 unelided_trait_object_lifetime: false,
363 fn record(&mut self, lifetime: &Option<Lifetime>) {
364 if let Some(ref lt) = *lifetime {
365 if lt.name == LifetimeName::Static {
366 self.lts.push(RefLt::Static);
367 } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
368 // Fresh lifetimes generated should be ignored.
369 } else if lt.is_elided() {
370 self.lts.push(RefLt::Unnamed);
372 self.lts.push(RefLt::Named(lt.name.ident().name));
375 self.lts.push(RefLt::Unnamed);
379 fn all_lts(&self) -> Vec<RefLt> {
382 .chain(self.nested_elision_site_lts.iter())
387 fn abort(&self) -> bool {
388 self.unelided_trait_object_lifetime
392 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
393 type Map = Map<'tcx>;
395 // for lifetimes as parameters of generics
396 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
397 self.record(&Some(*lifetime));
400 fn visit_poly_trait_ref(&mut self, poly_tref: &'tcx PolyTraitRef<'tcx>, tbm: TraitBoundModifier) {
401 let trait_ref = &poly_tref.trait_ref;
402 if CLOSURE_TRAIT_BOUNDS.iter().any(|&item| {
407 .map_or(false, |id| Some(id) == trait_ref.trait_def_id())
409 let mut sub_visitor = RefVisitor::new(self.cx);
410 sub_visitor.visit_trait_ref(trait_ref);
411 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
413 walk_poly_trait_ref(self, poly_tref, tbm);
417 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
419 TyKind::OpaqueDef(item, bounds) => {
420 let map = self.cx.tcx.hir();
421 let item = map.item(item);
422 walk_item(self, item);
424 self.lts.extend(bounds.iter().filter_map(|bound| match bound {
425 GenericArg::Lifetime(l) => Some(RefLt::Named(l.name.ident().name)),
429 TyKind::BareFn(&BareFnTy { decl, .. }) => {
430 let mut sub_visitor = RefVisitor::new(self.cx);
431 sub_visitor.visit_fn_decl(decl);
432 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
435 TyKind::TraitObject(bounds, ref lt, _) => {
437 self.unelided_trait_object_lifetime = true;
439 for bound in bounds {
440 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
448 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
449 NestedVisitorMap::None
453 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
454 /// reason about elision.
455 fn has_where_lifetimes<'tcx>(cx: &LateContext<'tcx>, where_clause: &'tcx WhereClause<'_>) -> bool {
456 for predicate in where_clause.predicates {
458 WherePredicate::RegionPredicate(..) => return true,
459 WherePredicate::BoundPredicate(ref pred) => {
460 // a predicate like F: Trait or F: for<'a> Trait<'a>
461 let mut visitor = RefVisitor::new(cx);
462 // walk the type F, it may not contain LT refs
463 walk_ty(&mut visitor, pred.bounded_ty);
464 if !visitor.all_lts().is_empty() {
467 // if the bounds define new lifetimes, they are fine to occur
468 let allowed_lts = allowed_lts_from(pred.bound_generic_params);
469 // now walk the bounds
470 for bound in pred.bounds.iter() {
471 walk_param_bound(&mut visitor, bound);
473 // and check that all lifetimes are allowed
474 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
478 WherePredicate::EqPredicate(ref pred) => {
479 let mut visitor = RefVisitor::new(cx);
480 walk_ty(&mut visitor, pred.lhs_ty);
481 walk_ty(&mut visitor, pred.rhs_ty);
482 if !visitor.lts.is_empty() {
491 struct LifetimeChecker {
492 map: FxHashMap<Symbol, Span>,
495 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
496 type Map = Map<'tcx>;
498 // for lifetimes as parameters of generics
499 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
500 self.map.remove(&lifetime.name.ident().name);
503 fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
504 // don't actually visit `<'a>` or `<'a: 'b>`
505 // we've already visited the `'a` declarations and
506 // don't want to spuriously remove them
507 // `'b` in `'a: 'b` is useless unless used elsewhere in
508 // a non-lifetime bound
509 if let GenericParamKind::Type { .. } = param.kind {
510 walk_generic_param(self, param);
513 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
514 NestedVisitorMap::None
518 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
522 .filter_map(|par| match par.kind {
523 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
527 let mut checker = LifetimeChecker { map: hs };
529 walk_generics(&mut checker, generics);
530 walk_fn_decl(&mut checker, func);
532 for &v in checker.map.values() {
535 EXTRA_UNUSED_LIFETIMES,
537 "this lifetime isn't used in the function definition",
542 struct BodyLifetimeChecker {
543 lifetimes_used_in_body: bool,
546 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
547 type Map = Map<'tcx>;
549 // for lifetimes as parameters of generics
550 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
551 if lifetime.name.ident().name != kw::Empty && lifetime.name.ident().name != kw::StaticLifetime {
552 self.lifetimes_used_in_body = true;
556 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
557 NestedVisitorMap::None