2 use rustc::hir::map::Map;
3 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintContext};
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 use rustc_hir::def::{DefKind, Res};
6 use rustc_hir::intravisit::*;
7 use rustc_hir::FunctionRetTy::Return;
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::source_map::Span;
11 use rustc_span::symbol::kw;
13 use crate::reexport::*;
14 use crate::utils::{last_path_segment, span_lint, trait_ref_of_method};
16 declare_clippy_lint! {
17 /// **What it does:** Checks for lifetime annotations which can be removed by
18 /// relying on lifetime elision.
20 /// **Why is this bad?** The additional lifetimes make the code look more
21 /// complicated, while there is nothing out of the ordinary going on. Removing
22 /// them leads to more readable code.
24 /// **Known problems:** Potential false negatives: we bail out if the function
25 /// has a `where` clause where lifetimes are mentioned.
29 /// // Bad: unnecessary lifetime annotations
30 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
35 /// fn elided(x: &u8, y: u8) -> &u8 {
39 pub NEEDLESS_LIFETIMES,
41 "using explicit lifetimes for references in function arguments when elision rules \
42 would allow omitting them"
45 declare_clippy_lint! {
46 /// **What it does:** Checks for lifetimes in generics that are never used
49 /// **Why is this bad?** The additional lifetimes make the code look more
50 /// complicated, while there is nothing out of the ordinary going on. Removing
51 /// them leads to more readable code.
53 /// **Known problems:** None.
57 /// // Bad: unnecessary lifetimes
58 /// fn unused_lifetime<'a>(x: u8) {
63 /// fn no_lifetime(x: u8) {
67 pub EXTRA_UNUSED_LIFETIMES,
69 "unused lifetimes in function definitions"
72 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
74 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes {
75 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
76 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
77 check_fn_inner(cx, &sig.decl, Some(id), generics, item.span, true);
81 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
82 if let ImplItemKind::Method(ref sig, id) = item.kind {
83 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id).is_none();
90 report_extra_lifetimes,
95 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
96 if let TraitItemKind::Method(ref sig, ref body) = item.kind {
97 let body = match *body {
98 TraitMethod::Required(_) => None,
99 TraitMethod::Provided(id) => Some(id),
101 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span, true);
106 /// The lifetime of a &-reference.
107 #[derive(PartialEq, Eq, Hash, Debug)]
114 fn check_fn_inner<'a, 'tcx>(
115 cx: &LateContext<'a, 'tcx>,
116 decl: &'tcx FnDecl<'_>,
117 body: Option<BodyId>,
118 generics: &'tcx Generics<'_>,
120 report_extra_lifetimes: bool,
122 if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
126 let mut bounds_lts = Vec::new();
127 let types = generics.params.iter().filter(|param| match param.kind {
128 GenericParamKind::Type { .. } => true,
132 for bound in typ.bounds {
133 let mut visitor = RefVisitor::new(cx);
134 walk_param_bound(&mut visitor, bound);
135 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
138 if let GenericBound::Trait(ref trait_ref, _) = *bound {
139 let params = &trait_ref
144 .expect("a path must have at least one segment")
146 if let Some(ref params) = *params {
147 let lifetimes = params.args.iter().filter_map(|arg| match arg {
148 GenericArg::Lifetime(lt) => Some(lt),
151 for bound in lifetimes {
152 if bound.name != LifetimeName::Static && !bound.is_elided() {
155 bounds_lts.push(bound);
161 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
166 "explicit lifetimes given in parameter types where they could be elided \
167 (or replaced with `'_` if needed by type declaration)",
170 if report_extra_lifetimes {
171 self::report_extra_lifetimes(cx, decl, generics);
175 fn could_use_elision<'a, 'tcx>(
176 cx: &LateContext<'a, 'tcx>,
177 func: &'tcx FnDecl<'_>,
178 body: Option<BodyId>,
179 named_generics: &'tcx [GenericParam<'_>],
180 bounds_lts: Vec<&'tcx Lifetime>,
182 // There are two scenarios where elision works:
183 // * no output references, all input references have different LT
184 // * output references, exactly one input reference with same LT
185 // All lifetimes must be unnamed, 'static or defined without bounds on the
186 // level of the current item.
189 let allowed_lts = allowed_lts_from(named_generics);
191 // these will collect all the lifetimes for references in arg/return types
192 let mut input_visitor = RefVisitor::new(cx);
193 let mut output_visitor = RefVisitor::new(cx);
195 // extract lifetimes in input argument types
196 for arg in func.inputs {
197 input_visitor.visit_ty(arg);
199 // extract lifetimes in output type
200 if let Return(ref ty) = func.output {
201 output_visitor.visit_ty(ty);
204 let input_lts = match input_visitor.into_vec() {
205 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
206 None => return false,
208 let output_lts = match output_visitor.into_vec() {
210 None => return false,
213 if let Some(body_id) = body {
214 let mut checker = BodyLifetimeChecker {
215 lifetimes_used_in_body: false,
217 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
218 if checker.lifetimes_used_in_body {
223 // check for lifetimes from higher scopes
224 for lt in input_lts.iter().chain(output_lts.iter()) {
225 if !allowed_lts.contains(lt) {
230 // no input lifetimes? easy case!
231 if input_lts.is_empty() {
233 } else if output_lts.is_empty() {
234 // no output lifetimes, check distinctness of input lifetimes
236 // only unnamed and static, ok
237 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
238 if unnamed_and_static {
241 // we have no output reference, so we only need all distinct lifetimes
242 input_lts.len() == unique_lifetimes(&input_lts)
244 // we have output references, so we need one input reference,
245 // and all output lifetimes must be the same
246 if unique_lifetimes(&output_lts) > 1 {
249 if input_lts.len() == 1 {
250 match (&input_lts[0], &output_lts[0]) {
251 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
252 (&RefLt::Named(_), &RefLt::Unnamed) => true,
253 _ => false, /* already elided, different named lifetimes
254 * or something static going on */
262 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
263 let mut allowed_lts = FxHashSet::default();
264 for par in named_generics.iter() {
265 if let GenericParamKind::Lifetime { .. } = par.kind {
266 if par.bounds.is_empty() {
267 allowed_lts.insert(RefLt::Named(par.name.ident().name));
271 allowed_lts.insert(RefLt::Unnamed);
272 allowed_lts.insert(RefLt::Static);
276 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
277 for lt in bounds_lts {
278 if lt.name != LifetimeName::Static {
279 vec.push(RefLt::Named(lt.name.ident().name));
286 /// Number of unique lifetimes in the given vector.
288 fn unique_lifetimes(lts: &[RefLt]) -> usize {
289 lts.iter().collect::<FxHashSet<_>>().len()
292 /// A visitor usable for `rustc_front::visit::walk_ty()`.
293 struct RefVisitor<'a, 'tcx> {
294 cx: &'a LateContext<'a, 'tcx>,
299 impl<'v, 't> RefVisitor<'v, 't> {
300 fn new(cx: &'v LateContext<'v, 't>) -> Self {
308 fn record(&mut self, lifetime: &Option<Lifetime>) {
309 if let Some(ref lt) = *lifetime {
310 if lt.name == LifetimeName::Static {
311 self.lts.push(RefLt::Static);
312 } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
313 // Fresh lifetimes generated should be ignored.
314 } else if lt.is_elided() {
315 self.lts.push(RefLt::Unnamed);
317 self.lts.push(RefLt::Named(lt.name.ident().name));
320 self.lts.push(RefLt::Unnamed);
324 fn into_vec(self) -> Option<Vec<RefLt>> {
332 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath<'_>, ty: &Ty<'_>) {
333 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
334 if !last_path_segment.parenthesized
335 && !last_path_segment.args.iter().any(|arg| match arg {
336 GenericArg::Lifetime(_) => true,
340 let hir_id = ty.hir_id;
341 match self.cx.tables.qpath_res(qpath, hir_id) {
342 Res::Def(DefKind::TyAlias, def_id) | Res::Def(DefKind::Struct, def_id) => {
343 let generics = self.cx.tcx.generics_of(def_id);
344 for _ in generics.params.as_slice() {
348 Res::Def(DefKind::Trait, def_id) => {
349 let trait_def = self.cx.tcx.trait_def(def_id);
350 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
361 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
362 type Map = Map<'tcx>;
364 // for lifetimes as parameters of generics
365 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
366 self.record(&Some(*lifetime));
369 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
371 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
374 TyKind::Path(ref path) => {
375 self.collect_anonymous_lifetimes(path, ty);
377 TyKind::Def(item, _) => {
378 let map = self.cx.tcx.hir();
379 if let ItemKind::OpaqueTy(ref exist_ty) = map.expect_item(item.id).kind {
380 for bound in exist_ty.bounds {
381 if let GenericBound::Outlives(_) = *bound {
390 TyKind::TraitObject(bounds, ref lt) => {
394 for bound in bounds {
395 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
403 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
404 NestedVisitorMap::None
408 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
409 /// reason about elision.
410 fn has_where_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause<'_>) -> bool {
411 for predicate in where_clause.predicates {
413 WherePredicate::RegionPredicate(..) => return true,
414 WherePredicate::BoundPredicate(ref pred) => {
415 // a predicate like F: Trait or F: for<'a> Trait<'a>
416 let mut visitor = RefVisitor::new(cx);
417 // walk the type F, it may not contain LT refs
418 walk_ty(&mut visitor, &pred.bounded_ty);
419 if !visitor.lts.is_empty() {
422 // if the bounds define new lifetimes, they are fine to occur
423 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
424 // now walk the bounds
425 for bound in pred.bounds.iter() {
426 walk_param_bound(&mut visitor, bound);
428 // and check that all lifetimes are allowed
429 match visitor.into_vec() {
430 None => return false,
433 if !allowed_lts.contains(<) {
440 WherePredicate::EqPredicate(ref pred) => {
441 let mut visitor = RefVisitor::new(cx);
442 walk_ty(&mut visitor, &pred.lhs_ty);
443 walk_ty(&mut visitor, &pred.rhs_ty);
444 if !visitor.lts.is_empty() {
453 struct LifetimeChecker {
454 map: FxHashMap<Name, Span>,
457 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
458 type Map = Map<'tcx>;
460 // for lifetimes as parameters of generics
461 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
462 self.map.remove(&lifetime.name.ident().name);
465 fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
466 // don't actually visit `<'a>` or `<'a: 'b>`
467 // we've already visited the `'a` declarations and
468 // don't want to spuriously remove them
469 // `'b` in `'a: 'b` is useless unless used elsewhere in
470 // a non-lifetime bound
471 if let GenericParamKind::Type { .. } = param.kind {
472 walk_generic_param(self, param)
475 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
476 NestedVisitorMap::None
480 fn report_extra_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
484 .filter_map(|par| match par.kind {
485 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
489 let mut checker = LifetimeChecker { map: hs };
491 walk_generics(&mut checker, generics);
492 walk_fn_decl(&mut checker, func);
494 for &v in checker.map.values() {
497 EXTRA_UNUSED_LIFETIMES,
499 "this lifetime isn't used in the function definition",
504 struct BodyLifetimeChecker {
505 lifetimes_used_in_body: bool,
508 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
509 type Map = Map<'tcx>;
511 // for lifetimes as parameters of generics
512 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
513 if lifetime.name.ident().name != kw::Invalid && lifetime.name.ident().name != kw::StaticLifetime {
514 self.lifetimes_used_in_body = true;
518 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
519 NestedVisitorMap::None