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 walk_fn_decl, walk_generic_param, walk_generics, walk_param_bound, walk_ty, NestedVisitorMap, Visitor,
9 use rustc_hir::FnRetTy::Return;
11 BodyId, FnDecl, GenericArg, GenericBound, GenericParam, GenericParamKind, Generics, ImplItem, ImplItemKind, Item,
12 ItemKind, Lifetime, LifetimeName, ParamName, QPath, TraitBoundModifier, TraitItem, TraitItemKind, TraitMethod, Ty,
13 TyKind, WhereClause, WherePredicate,
15 use rustc_lint::{LateContext, LateLintPass, LintContext};
16 use rustc_session::{declare_lint_pass, declare_tool_lint};
17 use rustc_span::source_map::Span;
18 use rustc_span::symbol::kw;
20 use crate::reexport::Name;
21 use crate::utils::{last_path_segment, span_lint, trait_ref_of_method};
23 declare_clippy_lint! {
24 /// **What it does:** Checks for lifetime annotations which can be removed by
25 /// relying on lifetime elision.
27 /// **Why is this bad?** 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:** Potential false negatives: we bail out if the function
32 /// has a `where` clause where lifetimes are mentioned.
36 /// // Bad: unnecessary lifetime annotations
37 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
42 /// fn elided(x: &u8, y: u8) -> &u8 {
46 pub NEEDLESS_LIFETIMES,
48 "using explicit lifetimes for references in function arguments when elision rules \
49 would allow omitting them"
52 declare_clippy_lint! {
53 /// **What it does:** Checks for lifetimes in generics that are never used
56 /// **Why is this bad?** The additional lifetimes make the code look more
57 /// complicated, while there is nothing out of the ordinary going on. Removing
58 /// them leads to more readable code.
60 /// **Known problems:** None.
64 /// // Bad: unnecessary lifetimes
65 /// fn unused_lifetime<'a>(x: u8) {
70 /// fn no_lifetime(x: u8) {
74 pub EXTRA_UNUSED_LIFETIMES,
76 "unused lifetimes in function definitions"
79 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
81 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes {
82 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
83 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
84 check_fn_inner(cx, &sig.decl, Some(id), generics, item.span, true);
88 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
89 if let ImplItemKind::Method(ref sig, id) = item.kind {
90 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id).is_none();
97 report_extra_lifetimes,
102 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
103 if let TraitItemKind::Fn(ref sig, ref body) = item.kind {
104 let body = match *body {
105 TraitMethod::Required(_) => None,
106 TraitMethod::Provided(id) => Some(id),
108 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span, true);
113 /// The lifetime of a &-reference.
114 #[derive(PartialEq, Eq, Hash, Debug)]
121 fn check_fn_inner<'a, 'tcx>(
122 cx: &LateContext<'a, 'tcx>,
123 decl: &'tcx FnDecl<'_>,
124 body: Option<BodyId>,
125 generics: &'tcx Generics<'_>,
127 report_extra_lifetimes: bool,
129 if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
133 let mut bounds_lts = Vec::new();
134 let types = generics.params.iter().filter(|param| match param.kind {
135 GenericParamKind::Type { .. } => true,
139 for bound in typ.bounds {
140 let mut visitor = RefVisitor::new(cx);
141 walk_param_bound(&mut visitor, bound);
142 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
145 if let GenericBound::Trait(ref trait_ref, _) = *bound {
146 let params = &trait_ref
151 .expect("a path must have at least one segment")
153 if let Some(ref params) = *params {
154 let lifetimes = params.args.iter().filter_map(|arg| match arg {
155 GenericArg::Lifetime(lt) => Some(lt),
158 for bound in lifetimes {
159 if bound.name != LifetimeName::Static && !bound.is_elided() {
162 bounds_lts.push(bound);
168 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
173 "explicit lifetimes given in parameter types where they could be elided \
174 (or replaced with `'_` if needed by type declaration)",
177 if report_extra_lifetimes {
178 self::report_extra_lifetimes(cx, decl, generics);
182 fn could_use_elision<'a, 'tcx>(
183 cx: &LateContext<'a, 'tcx>,
184 func: &'tcx FnDecl<'_>,
185 body: Option<BodyId>,
186 named_generics: &'tcx [GenericParam<'_>],
187 bounds_lts: Vec<&'tcx Lifetime>,
189 // There are two scenarios where elision works:
190 // * no output references, all input references have different LT
191 // * output references, exactly one input reference with same LT
192 // All lifetimes must be unnamed, 'static or defined without bounds on the
193 // level of the current item.
196 let allowed_lts = allowed_lts_from(named_generics);
198 // these will collect all the lifetimes for references in arg/return types
199 let mut input_visitor = RefVisitor::new(cx);
200 let mut output_visitor = RefVisitor::new(cx);
202 // extract lifetimes in input argument types
203 for arg in func.inputs {
204 input_visitor.visit_ty(arg);
206 // extract lifetimes in output type
207 if let Return(ref ty) = func.output {
208 output_visitor.visit_ty(ty);
211 let input_lts = match input_visitor.into_vec() {
212 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
213 None => return false,
215 let output_lts = match output_visitor.into_vec() {
217 None => return false,
220 if let Some(body_id) = body {
221 let mut checker = BodyLifetimeChecker {
222 lifetimes_used_in_body: false,
224 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
225 if checker.lifetimes_used_in_body {
230 // check for lifetimes from higher scopes
231 for lt in input_lts.iter().chain(output_lts.iter()) {
232 if !allowed_lts.contains(lt) {
237 // no input lifetimes? easy case!
238 if input_lts.is_empty() {
240 } else if output_lts.is_empty() {
241 // no output lifetimes, check distinctness of input lifetimes
243 // only unnamed and static, ok
244 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
245 if unnamed_and_static {
248 // we have no output reference, so we only need all distinct lifetimes
249 input_lts.len() == unique_lifetimes(&input_lts)
251 // we have output references, so we need one input reference,
252 // and all output lifetimes must be the same
253 if unique_lifetimes(&output_lts) > 1 {
256 if input_lts.len() == 1 {
257 match (&input_lts[0], &output_lts[0]) {
258 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
259 (&RefLt::Named(_), &RefLt::Unnamed) => true,
260 _ => false, /* already elided, different named lifetimes
261 * or something static going on */
269 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
270 let mut allowed_lts = FxHashSet::default();
271 for par in named_generics.iter() {
272 if let GenericParamKind::Lifetime { .. } = par.kind {
273 if par.bounds.is_empty() {
274 allowed_lts.insert(RefLt::Named(par.name.ident().name));
278 allowed_lts.insert(RefLt::Unnamed);
279 allowed_lts.insert(RefLt::Static);
283 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
284 for lt in bounds_lts {
285 if lt.name != LifetimeName::Static {
286 vec.push(RefLt::Named(lt.name.ident().name));
293 /// Number of unique lifetimes in the given vector.
295 fn unique_lifetimes(lts: &[RefLt]) -> usize {
296 lts.iter().collect::<FxHashSet<_>>().len()
299 /// A visitor usable for `rustc_front::visit::walk_ty()`.
300 struct RefVisitor<'a, 'tcx> {
301 cx: &'a LateContext<'a, 'tcx>,
306 impl<'v, 't> RefVisitor<'v, 't> {
307 fn new(cx: &'v LateContext<'v, 't>) -> Self {
315 fn record(&mut self, lifetime: &Option<Lifetime>) {
316 if let Some(ref lt) = *lifetime {
317 if lt.name == LifetimeName::Static {
318 self.lts.push(RefLt::Static);
319 } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
320 // Fresh lifetimes generated should be ignored.
321 } else if lt.is_elided() {
322 self.lts.push(RefLt::Unnamed);
324 self.lts.push(RefLt::Named(lt.name.ident().name));
327 self.lts.push(RefLt::Unnamed);
331 fn into_vec(self) -> Option<Vec<RefLt>> {
339 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath<'_>, ty: &Ty<'_>) {
340 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
341 if !last_path_segment.parenthesized
342 && !last_path_segment.args.iter().any(|arg| match arg {
343 GenericArg::Lifetime(_) => true,
347 let hir_id = ty.hir_id;
348 match self.cx.tables.qpath_res(qpath, hir_id) {
349 Res::Def(DefKind::TyAlias | DefKind::Struct, def_id) => {
350 let generics = self.cx.tcx.generics_of(def_id);
351 for _ in generics.params.as_slice() {
355 Res::Def(DefKind::Trait, def_id) => {
356 let trait_def = self.cx.tcx.trait_def(def_id);
357 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
368 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
369 type Map = Map<'tcx>;
371 // for lifetimes as parameters of generics
372 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
373 self.record(&Some(*lifetime));
376 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
378 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
381 TyKind::Path(ref path) => {
382 self.collect_anonymous_lifetimes(path, ty);
384 TyKind::Def(item, _) => {
385 let map = self.cx.tcx.hir();
386 if let ItemKind::OpaqueTy(ref exist_ty) = map.expect_item(item.id).kind {
387 for bound in exist_ty.bounds {
388 if let GenericBound::Outlives(_) = *bound {
397 TyKind::TraitObject(bounds, ref lt) => {
401 for bound in bounds {
402 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
410 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
411 NestedVisitorMap::None
415 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
416 /// reason about elision.
417 fn has_where_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause<'_>) -> bool {
418 for predicate in where_clause.predicates {
420 WherePredicate::RegionPredicate(..) => return true,
421 WherePredicate::BoundPredicate(ref pred) => {
422 // a predicate like F: Trait or F: for<'a> Trait<'a>
423 let mut visitor = RefVisitor::new(cx);
424 // walk the type F, it may not contain LT refs
425 walk_ty(&mut visitor, &pred.bounded_ty);
426 if !visitor.lts.is_empty() {
429 // if the bounds define new lifetimes, they are fine to occur
430 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
431 // now walk the bounds
432 for bound in pred.bounds.iter() {
433 walk_param_bound(&mut visitor, bound);
435 // and check that all lifetimes are allowed
436 match visitor.into_vec() {
437 None => return false,
440 if !allowed_lts.contains(<) {
447 WherePredicate::EqPredicate(ref pred) => {
448 let mut visitor = RefVisitor::new(cx);
449 walk_ty(&mut visitor, &pred.lhs_ty);
450 walk_ty(&mut visitor, &pred.rhs_ty);
451 if !visitor.lts.is_empty() {
460 struct LifetimeChecker {
461 map: FxHashMap<Name, Span>,
464 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
465 type Map = Map<'tcx>;
467 // for lifetimes as parameters of generics
468 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
469 self.map.remove(&lifetime.name.ident().name);
472 fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
473 // don't actually visit `<'a>` or `<'a: 'b>`
474 // we've already visited the `'a` declarations and
475 // don't want to spuriously remove them
476 // `'b` in `'a: 'b` is useless unless used elsewhere in
477 // a non-lifetime bound
478 if let GenericParamKind::Type { .. } = param.kind {
479 walk_generic_param(self, param)
482 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
483 NestedVisitorMap::None
487 fn report_extra_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
491 .filter_map(|par| match par.kind {
492 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
496 let mut checker = LifetimeChecker { map: hs };
498 walk_generics(&mut checker, generics);
499 walk_fn_decl(&mut checker, func);
501 for &v in checker.map.values() {
504 EXTRA_UNUSED_LIFETIMES,
506 "this lifetime isn't used in the function definition",
511 struct BodyLifetimeChecker {
512 lifetimes_used_in_body: bool,
515 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
516 type Map = Map<'tcx>;
518 // for lifetimes as parameters of generics
519 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
520 if lifetime.name.ident().name != kw::Invalid && lifetime.name.ident().name != kw::StaticLifetime {
521 self.lifetimes_used_in_body = true;
525 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
526 NestedVisitorMap::None