2 use rustc::hir::map::Map;
3 use rustc::lint::in_external_macro;
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_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::source_map::Span;
12 use rustc_span::symbol::kw;
14 use crate::reexport::*;
15 use crate::utils::{last_path_segment, span_lint, trait_ref_of_method};
17 declare_clippy_lint! {
18 /// **What it does:** Checks for lifetime annotations which can be removed by
19 /// relying on lifetime elision.
21 /// **Why is this bad?** The additional lifetimes make the code look more
22 /// complicated, while there is nothing out of the ordinary going on. Removing
23 /// them leads to more readable code.
25 /// **Known problems:** Potential false negatives: we bail out if the function
26 /// has a `where` clause where lifetimes are mentioned.
30 /// // Bad: unnecessary lifetime annotations
31 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
36 /// fn elided(x: &u8, y: u8) -> &u8 {
40 pub NEEDLESS_LIFETIMES,
42 "using explicit lifetimes for references in function arguments when elision rules \
43 would allow omitting them"
46 declare_clippy_lint! {
47 /// **What it does:** Checks for lifetimes in generics that are never used
50 /// **Why is this bad?** The additional lifetimes make the code look more
51 /// complicated, while there is nothing out of the ordinary going on. Removing
52 /// them leads to more readable code.
54 /// **Known problems:** None.
58 /// // Bad: unnecessary lifetimes
59 /// fn unused_lifetime<'a>(x: u8) {
64 /// fn no_lifetime(x: u8) {
68 pub EXTRA_UNUSED_LIFETIMES,
70 "unused lifetimes in function definitions"
73 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
75 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes {
76 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
77 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
78 check_fn_inner(cx, &sig.decl, Some(id), generics, item.span, true);
82 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
83 if let ImplItemKind::Method(ref sig, id) = item.kind {
84 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id).is_none();
91 report_extra_lifetimes,
96 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
97 if let TraitItemKind::Method(ref sig, ref body) = item.kind {
98 let body = match *body {
99 TraitMethod::Required(_) => None,
100 TraitMethod::Provided(id) => Some(id),
102 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span, true);
107 /// The lifetime of a &-reference.
108 #[derive(PartialEq, Eq, Hash, Debug)]
115 fn check_fn_inner<'a, 'tcx>(
116 cx: &LateContext<'a, 'tcx>,
117 decl: &'tcx FnDecl<'_>,
118 body: Option<BodyId>,
119 generics: &'tcx Generics<'_>,
121 report_extra_lifetimes: bool,
123 if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
127 let mut bounds_lts = Vec::new();
128 let types = generics.params.iter().filter(|param| match param.kind {
129 GenericParamKind::Type { .. } => true,
133 for bound in typ.bounds {
134 let mut visitor = RefVisitor::new(cx);
135 walk_param_bound(&mut visitor, bound);
136 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
139 if let GenericBound::Trait(ref trait_ref, _) = *bound {
140 let params = &trait_ref
145 .expect("a path must have at least one segment")
147 if let Some(ref params) = *params {
148 let lifetimes = params.args.iter().filter_map(|arg| match arg {
149 GenericArg::Lifetime(lt) => Some(lt),
152 for bound in lifetimes {
153 if bound.name != LifetimeName::Static && !bound.is_elided() {
156 bounds_lts.push(bound);
162 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
167 "explicit lifetimes given in parameter types where they could be elided \
168 (or replaced with `'_` if needed by type declaration)",
171 if report_extra_lifetimes {
172 self::report_extra_lifetimes(cx, decl, generics);
176 fn could_use_elision<'a, 'tcx>(
177 cx: &LateContext<'a, 'tcx>,
178 func: &'tcx FnDecl<'_>,
179 body: Option<BodyId>,
180 named_generics: &'tcx [GenericParam<'_>],
181 bounds_lts: Vec<&'tcx Lifetime>,
183 // There are two scenarios where elision works:
184 // * no output references, all input references have different LT
185 // * output references, exactly one input reference with same LT
186 // All lifetimes must be unnamed, 'static or defined without bounds on the
187 // level of the current item.
190 let allowed_lts = allowed_lts_from(named_generics);
192 // these will collect all the lifetimes for references in arg/return types
193 let mut input_visitor = RefVisitor::new(cx);
194 let mut output_visitor = RefVisitor::new(cx);
196 // extract lifetimes in input argument types
197 for arg in func.inputs {
198 input_visitor.visit_ty(arg);
200 // extract lifetimes in output type
201 if let Return(ref ty) = func.output {
202 output_visitor.visit_ty(ty);
205 let input_lts = match input_visitor.into_vec() {
206 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
207 None => return false,
209 let output_lts = match output_visitor.into_vec() {
211 None => return false,
214 if let Some(body_id) = body {
215 let mut checker = BodyLifetimeChecker {
216 lifetimes_used_in_body: false,
218 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
219 if checker.lifetimes_used_in_body {
224 // check for lifetimes from higher scopes
225 for lt in input_lts.iter().chain(output_lts.iter()) {
226 if !allowed_lts.contains(lt) {
231 // no input lifetimes? easy case!
232 if input_lts.is_empty() {
234 } else if output_lts.is_empty() {
235 // no output lifetimes, check distinctness of input lifetimes
237 // only unnamed and static, ok
238 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
239 if unnamed_and_static {
242 // we have no output reference, so we only need all distinct lifetimes
243 input_lts.len() == unique_lifetimes(&input_lts)
245 // we have output references, so we need one input reference,
246 // and all output lifetimes must be the same
247 if unique_lifetimes(&output_lts) > 1 {
250 if input_lts.len() == 1 {
251 match (&input_lts[0], &output_lts[0]) {
252 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
253 (&RefLt::Named(_), &RefLt::Unnamed) => true,
254 _ => false, /* already elided, different named lifetimes
255 * or something static going on */
263 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
264 let mut allowed_lts = FxHashSet::default();
265 for par in named_generics.iter() {
266 if let GenericParamKind::Lifetime { .. } = par.kind {
267 if par.bounds.is_empty() {
268 allowed_lts.insert(RefLt::Named(par.name.ident().name));
272 allowed_lts.insert(RefLt::Unnamed);
273 allowed_lts.insert(RefLt::Static);
277 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
278 for lt in bounds_lts {
279 if lt.name != LifetimeName::Static {
280 vec.push(RefLt::Named(lt.name.ident().name));
287 /// Number of unique lifetimes in the given vector.
289 fn unique_lifetimes(lts: &[RefLt]) -> usize {
290 lts.iter().collect::<FxHashSet<_>>().len()
293 /// A visitor usable for `rustc_front::visit::walk_ty()`.
294 struct RefVisitor<'a, 'tcx> {
295 cx: &'a LateContext<'a, 'tcx>,
300 impl<'v, 't> RefVisitor<'v, 't> {
301 fn new(cx: &'v LateContext<'v, 't>) -> Self {
309 fn record(&mut self, lifetime: &Option<Lifetime>) {
310 if let Some(ref lt) = *lifetime {
311 if lt.name == LifetimeName::Static {
312 self.lts.push(RefLt::Static);
313 } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
314 // Fresh lifetimes generated should be ignored.
315 } else if lt.is_elided() {
316 self.lts.push(RefLt::Unnamed);
318 self.lts.push(RefLt::Named(lt.name.ident().name));
321 self.lts.push(RefLt::Unnamed);
325 fn into_vec(self) -> Option<Vec<RefLt>> {
333 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath<'_>, ty: &Ty<'_>) {
334 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
335 if !last_path_segment.parenthesized
336 && !last_path_segment.args.iter().any(|arg| match arg {
337 GenericArg::Lifetime(_) => true,
341 let hir_id = ty.hir_id;
342 match self.cx.tables.qpath_res(qpath, hir_id) {
343 Res::Def(DefKind::TyAlias, def_id) | Res::Def(DefKind::Struct, def_id) => {
344 let generics = self.cx.tcx.generics_of(def_id);
345 for _ in generics.params.as_slice() {
349 Res::Def(DefKind::Trait, def_id) => {
350 let trait_def = self.cx.tcx.trait_def(def_id);
351 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
362 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
363 type Map = Map<'tcx>;
365 // for lifetimes as parameters of generics
366 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
367 self.record(&Some(*lifetime));
370 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
372 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
375 TyKind::Path(ref path) => {
376 self.collect_anonymous_lifetimes(path, ty);
378 TyKind::Def(item, _) => {
379 let map = self.cx.tcx.hir();
380 if let ItemKind::OpaqueTy(ref exist_ty) = map.expect_item(item.id).kind {
381 for bound in exist_ty.bounds {
382 if let GenericBound::Outlives(_) = *bound {
391 TyKind::TraitObject(bounds, ref lt) => {
395 for bound in bounds {
396 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
404 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
405 NestedVisitorMap::None
409 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
410 /// reason about elision.
411 fn has_where_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause<'_>) -> bool {
412 for predicate in where_clause.predicates {
414 WherePredicate::RegionPredicate(..) => return true,
415 WherePredicate::BoundPredicate(ref pred) => {
416 // a predicate like F: Trait or F: for<'a> Trait<'a>
417 let mut visitor = RefVisitor::new(cx);
418 // walk the type F, it may not contain LT refs
419 walk_ty(&mut visitor, &pred.bounded_ty);
420 if !visitor.lts.is_empty() {
423 // if the bounds define new lifetimes, they are fine to occur
424 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
425 // now walk the bounds
426 for bound in pred.bounds.iter() {
427 walk_param_bound(&mut visitor, bound);
429 // and check that all lifetimes are allowed
430 match visitor.into_vec() {
431 None => return false,
434 if !allowed_lts.contains(<) {
441 WherePredicate::EqPredicate(ref pred) => {
442 let mut visitor = RefVisitor::new(cx);
443 walk_ty(&mut visitor, &pred.lhs_ty);
444 walk_ty(&mut visitor, &pred.rhs_ty);
445 if !visitor.lts.is_empty() {
454 struct LifetimeChecker {
455 map: FxHashMap<Name, Span>,
458 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
459 type Map = Map<'tcx>;
461 // for lifetimes as parameters of generics
462 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
463 self.map.remove(&lifetime.name.ident().name);
466 fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
467 // don't actually visit `<'a>` or `<'a: 'b>`
468 // we've already visited the `'a` declarations and
469 // don't want to spuriously remove them
470 // `'b` in `'a: 'b` is useless unless used elsewhere in
471 // a non-lifetime bound
472 if let GenericParamKind::Type { .. } = param.kind {
473 walk_generic_param(self, param)
476 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
477 NestedVisitorMap::None
481 fn report_extra_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
485 .filter_map(|par| match par.kind {
486 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
490 let mut checker = LifetimeChecker { map: hs };
492 walk_generics(&mut checker, generics);
493 walk_fn_decl(&mut checker, func);
495 for &v in checker.map.values() {
498 EXTRA_UNUSED_LIFETIMES,
500 "this lifetime isn't used in the function definition",
505 struct BodyLifetimeChecker {
506 lifetimes_used_in_body: bool,
509 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
510 type Map = Map<'tcx>;
512 // for lifetimes as parameters of generics
513 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
514 if lifetime.name.ident().name != kw::Invalid && lifetime.name.ident().name != kw::StaticLifetime {
515 self.lifetimes_used_in_body = true;
519 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
520 NestedVisitorMap::None