1 use crate::reexport::*;
3 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, LintContext};
4 use crate::rustc::{declare_tool_lint, lint_array};
5 use crate::rustc::hir::def::Def;
6 use crate::rustc::hir::*;
7 use crate::rustc::hir::intravisit::*;
8 use crate::rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use crate::syntax::source_map::Span;
10 use crate::utils::{last_path_segment, span_lint};
11 use crate::syntax::symbol::keywords;
13 /// **What it does:** Checks for lifetime annotations which can be removed by
14 /// relying on lifetime elision.
16 /// **Why is this bad?** The additional lifetimes make the code look more
17 /// complicated, while there is nothing out of the ordinary going on. Removing
18 /// them leads to more readable code.
20 /// **Known problems:** Potential false negatives: we bail out if the function
21 /// has a `where` clause where lifetimes are mentioned.
25 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 { x }
27 declare_clippy_lint! {
28 pub NEEDLESS_LIFETIMES,
30 "using explicit lifetimes for references in function arguments when elision rules \
31 would allow omitting them"
34 /// **What it does:** Checks for lifetimes in generics that are never used
37 /// **Why is this bad?** The additional lifetimes make the code look more
38 /// complicated, while there is nothing out of the ordinary going on. Removing
39 /// them leads to more readable code.
41 /// **Known problems:** None.
45 /// fn unused_lifetime<'a>(x: u8) { .. }
47 declare_clippy_lint! {
48 pub EXTRA_UNUSED_LIFETIMES,
50 "unused lifetimes in function definitions"
53 #[derive(Copy, Clone)]
54 pub struct LifetimePass;
56 impl LintPass for LifetimePass {
57 fn get_lints(&self) -> LintArray {
58 lint_array!(NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES)
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LifetimePass {
63 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
64 if let ItemKind::Fn(ref decl, _, ref generics, id) = item.node {
65 check_fn_inner(cx, decl, Some(id), generics, item.span);
69 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
70 if let ImplItemKind::Method(ref sig, id) = item.node {
71 check_fn_inner(cx, &sig.decl, Some(id), &item.generics, item.span);
75 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
76 if let TraitItemKind::Method(ref sig, ref body) = item.node {
77 let body = match *body {
78 TraitMethod::Required(_) => None,
79 TraitMethod::Provided(id) => Some(id),
81 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span);
86 /// The lifetime of a &-reference.
87 #[derive(PartialEq, Eq, Hash, Debug)]
94 fn check_fn_inner<'a, 'tcx>(
95 cx: &LateContext<'a, 'tcx>,
98 generics: &'tcx Generics,
101 if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
105 let mut bounds_lts = Vec::new();
106 let types = generics.params.iter().filter_map(|param| match param.kind {
107 GenericParamKind::Type { .. } => Some(param),
108 GenericParamKind::Lifetime { .. } => None,
111 for bound in &typ.bounds {
112 let mut visitor = RefVisitor::new(cx);
113 walk_param_bound(&mut visitor, bound);
114 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
117 if let GenericBound::Trait(ref trait_ref, _) = *bound {
118 let params = &trait_ref
123 .expect("a path must have at least one segment")
125 if let Some(ref params) = *params {
126 let lifetimes = params.args.iter().filter_map(|arg| match arg {
127 GenericArg::Lifetime(lt) => Some(lt),
128 GenericArg::Type(_) => None,
130 for bound in lifetimes {
131 if bound.name != LifetimeName::Static && !bound.is_elided() {
134 bounds_lts.push(bound);
140 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
145 "explicit lifetimes given in parameter types where they could be elided",
148 report_extra_lifetimes(cx, decl, generics);
151 fn could_use_elision<'a, 'tcx: 'a>(
152 cx: &LateContext<'a, 'tcx>,
154 body: Option<BodyId>,
155 named_generics: &'tcx [GenericParam],
156 bounds_lts: Vec<&'tcx Lifetime>,
158 // There are two scenarios where elision works:
159 // * no output references, all input references have different LT
160 // * output references, exactly one input reference with same LT
161 // All lifetimes must be unnamed, 'static or defined without bounds on the
162 // level of the current item.
165 let allowed_lts = allowed_lts_from(named_generics);
167 // these will collect all the lifetimes for references in arg/return types
168 let mut input_visitor = RefVisitor::new(cx);
169 let mut output_visitor = RefVisitor::new(cx);
171 // extract lifetimes in input argument types
172 for arg in &func.inputs {
173 input_visitor.visit_ty(arg);
175 // extract lifetimes in output type
176 if let Return(ref ty) = func.output {
177 output_visitor.visit_ty(ty);
180 let input_lts = match input_visitor.into_vec() {
181 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
182 None => return false,
184 let output_lts = match output_visitor.into_vec() {
186 None => return false,
189 if let Some(body_id) = body {
190 let mut checker = BodyLifetimeChecker {
191 lifetimes_used_in_body: false,
193 checker.visit_expr(&cx.tcx.hir.body(body_id).value);
194 if checker.lifetimes_used_in_body {
199 // check for lifetimes from higher scopes
200 for lt in input_lts.iter().chain(output_lts.iter()) {
201 if !allowed_lts.contains(lt) {
206 // no input lifetimes? easy case!
207 if input_lts.is_empty() {
209 } else if output_lts.is_empty() {
210 // no output lifetimes, check distinctness of input lifetimes
212 // only unnamed and static, ok
213 let unnamed_and_static = input_lts
215 .all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
216 if unnamed_and_static {
219 // we have no output reference, so we only need all distinct lifetimes
220 input_lts.len() == unique_lifetimes(&input_lts)
222 // we have output references, so we need one input reference,
223 // and all output lifetimes must be the same
224 if unique_lifetimes(&output_lts) > 1 {
227 if input_lts.len() == 1 {
228 match (&input_lts[0], &output_lts[0]) {
229 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
230 (&RefLt::Named(_), &RefLt::Unnamed) => true,
231 _ => false, /* already elided, different named lifetimes
232 * or something static going on */
240 fn allowed_lts_from(named_generics: &[GenericParam]) -> FxHashSet<RefLt> {
241 let mut allowed_lts = FxHashSet::default();
242 for par in named_generics.iter() {
243 if let GenericParamKind::Lifetime { .. } = par.kind {
244 if par.bounds.is_empty() {
245 allowed_lts.insert(RefLt::Named(par.name.ident().name));
249 allowed_lts.insert(RefLt::Unnamed);
250 allowed_lts.insert(RefLt::Static);
254 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
255 for lt in bounds_lts {
256 if lt.name != LifetimeName::Static {
257 vec.push(RefLt::Named(lt.name.ident().name));
264 /// Number of unique lifetimes in the given vector.
265 fn unique_lifetimes(lts: &[RefLt]) -> usize {
266 lts.iter().collect::<FxHashSet<_>>().len()
269 /// A visitor usable for `rustc_front::visit::walk_ty()`.
270 struct RefVisitor<'a, 'tcx: 'a> {
271 cx: &'a LateContext<'a, 'tcx>,
276 impl<'v, 't> RefVisitor<'v, 't> {
277 fn new(cx: &'v LateContext<'v, 't>) -> Self {
285 fn record(&mut self, lifetime: &Option<Lifetime>) {
286 if let Some(ref lt) = *lifetime {
287 if lt.name == LifetimeName::Static {
288 self.lts.push(RefLt::Static);
289 } else if lt.is_elided() {
290 self.lts.push(RefLt::Unnamed);
292 self.lts.push(RefLt::Named(lt.name.ident().name));
295 self.lts.push(RefLt::Unnamed);
299 fn into_vec(self) -> Option<Vec<RefLt>> {
307 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
308 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
309 if !last_path_segment.parenthesized
310 && !last_path_segment.args.iter().any(|arg| match arg {
311 GenericArg::Lifetime(_) => true,
312 GenericArg::Type(_) => false,
314 let hir_id = self.cx.tcx.hir.node_to_hir_id(ty.id);
315 match self.cx.tables.qpath_def(qpath, hir_id) {
316 Def::TyAlias(def_id) | Def::Struct(def_id) => {
317 let generics = self.cx.tcx.generics_of(def_id);
318 for _ in generics.params.as_slice() {
322 Def::Trait(def_id) => {
323 let trait_def = self.cx.tcx.trait_def(def_id);
324 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
335 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
336 // for lifetimes as parameters of generics
337 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
338 self.record(&Some(*lifetime));
341 fn visit_ty(&mut self, ty: &'tcx Ty) {
343 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
346 TyKind::Path(ref path) => {
347 if let QPath::Resolved(_, ref path) = *path {
348 if let Def::Existential(def_id) = path.def {
349 let node_id = self.cx.tcx.hir.as_local_node_id(def_id).unwrap();
350 if let ItemKind::Existential(ref exist_ty) = self.cx.tcx.hir.expect_item(node_id).node {
351 for bound in &exist_ty.bounds {
352 if let GenericBound::Outlives(_) = *bound {
363 self.collect_anonymous_lifetimes(path, ty);
365 TyKind::TraitObject(ref bounds, ref lt) => {
369 for bound in bounds {
370 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
378 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
379 NestedVisitorMap::None
383 /// Are any lifetimes mentioned in the `where` clause? If yes, we don't try to
384 /// reason about elision.
385 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
386 for predicate in &where_clause.predicates {
388 WherePredicate::RegionPredicate(..) => return true,
389 WherePredicate::BoundPredicate(ref pred) => {
390 // a predicate like F: Trait or F: for<'a> Trait<'a>
391 let mut visitor = RefVisitor::new(cx);
392 // walk the type F, it may not contain LT refs
393 walk_ty(&mut visitor, &pred.bounded_ty);
394 if !visitor.lts.is_empty() {
397 // if the bounds define new lifetimes, they are fine to occur
398 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
399 // now walk the bounds
400 for bound in pred.bounds.iter() {
401 walk_param_bound(&mut visitor, bound);
403 // and check that all lifetimes are allowed
404 match visitor.into_vec() {
405 None => return false,
406 Some(lts) => for lt in lts {
407 if !allowed_lts.contains(<) {
413 WherePredicate::EqPredicate(ref pred) => {
414 let mut visitor = RefVisitor::new(cx);
415 walk_ty(&mut visitor, &pred.lhs_ty);
416 walk_ty(&mut visitor, &pred.rhs_ty);
417 if !visitor.lts.is_empty() {
426 struct LifetimeChecker {
427 map: FxHashMap<Name, Span>,
430 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
431 // for lifetimes as parameters of generics
432 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
433 self.map.remove(&lifetime.name.ident().name);
436 fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
437 // don't actually visit `<'a>` or `<'a: 'b>`
438 // we've already visited the `'a` declarations and
439 // don't want to spuriously remove them
440 // `'b` in `'a: 'b` is useless unless used elsewhere in
441 // a non-lifetime bound
442 if let GenericParamKind::Type { .. } = param.kind {
443 walk_generic_param(self, param)
446 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
447 NestedVisitorMap::None
451 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
452 let hs = generics.params.iter()
453 .filter_map(|par| match par.kind {
454 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
458 let mut checker = LifetimeChecker { map: hs };
460 walk_generics(&mut checker, generics);
461 walk_fn_decl(&mut checker, func);
463 for &v in checker.map.values() {
464 span_lint(cx, EXTRA_UNUSED_LIFETIMES, v, "this lifetime isn't used in the function definition");
468 struct BodyLifetimeChecker {
469 lifetimes_used_in_body: bool,
472 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
473 // for lifetimes as parameters of generics
474 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
475 if lifetime.name.ident().name != keywords::Invalid.name() && lifetime.name.ident().name != "'static" {
476 self.lifetimes_used_in_body = true;
480 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
481 NestedVisitorMap::None