1 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
2 use rustc_hir::def::{DefKind, Res};
3 use rustc_hir::intravisit::{
4 walk_fn_decl, walk_generic_param, walk_generics, walk_param_bound, walk_ty, NestedVisitorMap, Visitor,
6 use rustc_hir::FnRetTy::Return;
8 BodyId, FnDecl, GenericArg, GenericBound, GenericParam, GenericParamKind, Generics, ImplItem, ImplItemKind, Item,
9 ItemKind, Lifetime, LifetimeName, ParamName, QPath, TraitBoundModifier, TraitFn, TraitItem, TraitItemKind, Ty,
10 TyKind, WhereClause, WherePredicate,
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::hir::map::Map;
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::source_map::Span;
16 use rustc_span::symbol::kw;
18 use crate::reexport::Name;
19 use crate::utils::{in_macro, last_path_segment, span_lint, trait_ref_of_method};
21 declare_clippy_lint! {
22 /// **What it does:** Checks for lifetime annotations which can be removed by
23 /// relying on lifetime elision.
25 /// **Why is this bad?** The additional lifetimes make the code look more
26 /// complicated, while there is nothing out of the ordinary going on. Removing
27 /// them leads to more readable code.
29 /// **Known problems:** Potential false negatives: we bail out if the function
30 /// has a `where` clause where lifetimes are mentioned.
34 /// // Bad: unnecessary lifetime annotations
35 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
40 /// fn elided(x: &u8, y: u8) -> &u8 {
44 pub NEEDLESS_LIFETIMES,
46 "using explicit lifetimes for references in function arguments when elision rules \
47 would allow omitting them"
50 declare_clippy_lint! {
51 /// **What it does:** Checks for lifetimes in generics that are never used
54 /// **Why is this bad?** The additional lifetimes make the code look more
55 /// complicated, while there is nothing out of the ordinary going on. Removing
56 /// them leads to more readable code.
58 /// **Known problems:** None.
62 /// // Bad: unnecessary lifetimes
63 /// fn unused_lifetime<'a>(x: u8) {
68 /// fn no_lifetime(x: u8) {
72 pub EXTRA_UNUSED_LIFETIMES,
74 "unused lifetimes in function definitions"
77 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
79 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes {
80 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
81 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
82 check_fn_inner(cx, &sig.decl, Some(id), generics, item.span, true);
86 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
87 if let ImplItemKind::Fn(ref sig, id) = item.kind {
88 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id).is_none();
95 report_extra_lifetimes,
100 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
101 if let TraitItemKind::Fn(ref sig, ref body) = item.kind {
102 let body = match *body {
103 TraitFn::Required(_) => None,
104 TraitFn::Provided(id) => Some(id),
106 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span, true);
111 /// The lifetime of a &-reference.
112 #[derive(PartialEq, Eq, Hash, Debug)]
119 fn check_fn_inner<'a, 'tcx>(
120 cx: &LateContext<'a, 'tcx>,
121 decl: &'tcx FnDecl<'_>,
122 body: Option<BodyId>,
123 generics: &'tcx Generics<'_>,
125 report_extra_lifetimes: bool,
127 if in_macro(span) || has_where_lifetimes(cx, &generics.where_clause) {
131 let mut bounds_lts = Vec::new();
132 let types = generics.params.iter().filter(|param| match param.kind {
133 GenericParamKind::Type { .. } => true,
137 for bound in typ.bounds {
138 let mut visitor = RefVisitor::new(cx);
139 walk_param_bound(&mut visitor, bound);
140 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
143 if let GenericBound::Trait(ref trait_ref, _) = *bound {
144 let params = &trait_ref
149 .expect("a path must have at least one segment")
151 if let Some(ref params) = *params {
152 let lifetimes = params.args.iter().filter_map(|arg| match arg {
153 GenericArg::Lifetime(lt) => Some(lt),
156 for bound in lifetimes {
157 if bound.name != LifetimeName::Static && !bound.is_elided() {
160 bounds_lts.push(bound);
166 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
170 span.with_hi(decl.output.span().hi()),
171 "explicit lifetimes given in parameter types where they could be elided \
172 (or replaced with `'_` if needed by type declaration)",
175 if report_extra_lifetimes {
176 self::report_extra_lifetimes(cx, decl, generics);
180 fn could_use_elision<'a, 'tcx>(
181 cx: &LateContext<'a, 'tcx>,
182 func: &'tcx FnDecl<'_>,
183 body: Option<BodyId>,
184 named_generics: &'tcx [GenericParam<'_>],
185 bounds_lts: Vec<&'tcx Lifetime>,
187 // There are two scenarios where elision works:
188 // * no output references, all input references have different LT
189 // * output references, exactly one input reference with same LT
190 // All lifetimes must be unnamed, 'static or defined without bounds on the
191 // level of the current item.
194 let allowed_lts = allowed_lts_from(named_generics);
196 // these will collect all the lifetimes for references in arg/return types
197 let mut input_visitor = RefVisitor::new(cx);
198 let mut output_visitor = RefVisitor::new(cx);
200 // extract lifetimes in input argument types
201 for arg in func.inputs {
202 input_visitor.visit_ty(arg);
204 // extract lifetimes in output type
205 if let Return(ref ty) = func.output {
206 output_visitor.visit_ty(ty);
209 let input_lts = match input_visitor.into_vec() {
210 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
211 None => return false,
213 let output_lts = match output_visitor.into_vec() {
215 None => return false,
218 if let Some(body_id) = body {
219 let mut checker = BodyLifetimeChecker {
220 lifetimes_used_in_body: false,
222 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
223 if checker.lifetimes_used_in_body {
228 // check for lifetimes from higher scopes
229 for lt in input_lts.iter().chain(output_lts.iter()) {
230 if !allowed_lts.contains(lt) {
235 // no input lifetimes? easy case!
236 if input_lts.is_empty() {
238 } else if output_lts.is_empty() {
239 // no output lifetimes, check distinctness of input lifetimes
241 // only unnamed and static, ok
242 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
243 if unnamed_and_static {
246 // we have no output reference, so we only need all distinct lifetimes
247 input_lts.len() == unique_lifetimes(&input_lts)
249 // we have output references, so we need one input reference,
250 // and all output lifetimes must be the same
251 if unique_lifetimes(&output_lts) > 1 {
254 if input_lts.len() == 1 {
255 match (&input_lts[0], &output_lts[0]) {
256 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
257 (&RefLt::Named(_), &RefLt::Unnamed) => true,
258 _ => false, /* already elided, different named lifetimes
259 * or something static going on */
267 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
268 let mut allowed_lts = FxHashSet::default();
269 for par in named_generics.iter() {
270 if let GenericParamKind::Lifetime { .. } = par.kind {
271 if par.bounds.is_empty() {
272 allowed_lts.insert(RefLt::Named(par.name.ident().name));
276 allowed_lts.insert(RefLt::Unnamed);
277 allowed_lts.insert(RefLt::Static);
281 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
282 for lt in bounds_lts {
283 if lt.name != LifetimeName::Static {
284 vec.push(RefLt::Named(lt.name.ident().name));
291 /// Number of unique lifetimes in the given vector.
293 fn unique_lifetimes(lts: &[RefLt]) -> usize {
294 lts.iter().collect::<FxHashSet<_>>().len()
297 /// A visitor usable for `rustc_front::visit::walk_ty()`.
298 struct RefVisitor<'a, 'tcx> {
299 cx: &'a LateContext<'a, 'tcx>,
304 impl<'v, 't> RefVisitor<'v, 't> {
305 fn new(cx: &'v LateContext<'v, 't>) -> Self {
313 fn record(&mut self, lifetime: &Option<Lifetime>) {
314 if let Some(ref lt) = *lifetime {
315 if lt.name == LifetimeName::Static {
316 self.lts.push(RefLt::Static);
317 } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
318 // Fresh lifetimes generated should be ignored.
319 } else if lt.is_elided() {
320 self.lts.push(RefLt::Unnamed);
322 self.lts.push(RefLt::Named(lt.name.ident().name));
325 self.lts.push(RefLt::Unnamed);
329 fn into_vec(self) -> Option<Vec<RefLt>> {
337 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath<'_>, ty: &Ty<'_>) {
338 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
339 if !last_path_segment.parenthesized
340 && !last_path_segment.args.iter().any(|arg| match arg {
341 GenericArg::Lifetime(_) => true,
345 let hir_id = ty.hir_id;
346 match self.cx.tables.qpath_res(qpath, hir_id) {
347 Res::Def(DefKind::TyAlias | DefKind::Struct, def_id) => {
348 let generics = self.cx.tcx.generics_of(def_id);
349 for _ in generics.params.as_slice() {
353 Res::Def(DefKind::Trait, def_id) => {
354 let trait_def = self.cx.tcx.trait_def(def_id);
355 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
366 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
367 type Map = Map<'tcx>;
369 // for lifetimes as parameters of generics
370 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
371 self.record(&Some(*lifetime));
374 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
376 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
379 TyKind::Path(ref path) => {
380 self.collect_anonymous_lifetimes(path, ty);
382 TyKind::Def(item, _) => {
383 let map = self.cx.tcx.hir();
384 if let ItemKind::OpaqueTy(ref exist_ty) = map.expect_item(item.id).kind {
385 for bound in exist_ty.bounds {
386 if let GenericBound::Outlives(_) = *bound {
395 TyKind::TraitObject(bounds, ref lt) => {
399 for bound in bounds {
400 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
408 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
409 NestedVisitorMap::None
413 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
414 /// reason about elision.
415 fn has_where_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause<'_>) -> bool {
416 for predicate in where_clause.predicates {
418 WherePredicate::RegionPredicate(..) => return true,
419 WherePredicate::BoundPredicate(ref pred) => {
420 // a predicate like F: Trait or F: for<'a> Trait<'a>
421 let mut visitor = RefVisitor::new(cx);
422 // walk the type F, it may not contain LT refs
423 walk_ty(&mut visitor, &pred.bounded_ty);
424 if !visitor.lts.is_empty() {
427 // if the bounds define new lifetimes, they are fine to occur
428 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
429 // now walk the bounds
430 for bound in pred.bounds.iter() {
431 walk_param_bound(&mut visitor, bound);
433 // and check that all lifetimes are allowed
434 match visitor.into_vec() {
435 None => return false,
438 if !allowed_lts.contains(<) {
445 WherePredicate::EqPredicate(ref pred) => {
446 let mut visitor = RefVisitor::new(cx);
447 walk_ty(&mut visitor, &pred.lhs_ty);
448 walk_ty(&mut visitor, &pred.rhs_ty);
449 if !visitor.lts.is_empty() {
458 struct LifetimeChecker {
459 map: FxHashMap<Name, Span>,
462 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
463 type Map = Map<'tcx>;
465 // for lifetimes as parameters of generics
466 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
467 self.map.remove(&lifetime.name.ident().name);
470 fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
471 // don't actually visit `<'a>` or `<'a: 'b>`
472 // we've already visited the `'a` declarations and
473 // don't want to spuriously remove them
474 // `'b` in `'a: 'b` is useless unless used elsewhere in
475 // a non-lifetime bound
476 if let GenericParamKind::Type { .. } = param.kind {
477 walk_generic_param(self, param)
480 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
481 NestedVisitorMap::None
485 fn report_extra_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
489 .filter_map(|par| match par.kind {
490 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
494 let mut checker = LifetimeChecker { map: hs };
496 walk_generics(&mut checker, generics);
497 walk_fn_decl(&mut checker, func);
499 for &v in checker.map.values() {
502 EXTRA_UNUSED_LIFETIMES,
504 "this lifetime isn't used in the function definition",
509 struct BodyLifetimeChecker {
510 lifetimes_used_in_body: bool,
513 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
514 type Map = Map<'tcx>;
516 // for lifetimes as parameters of generics
517 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
518 if lifetime.name.ident().name != kw::Invalid && lifetime.name.ident().name != kw::StaticLifetime {
519 self.lifetimes_used_in_body = true;
523 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
524 NestedVisitorMap::None