1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use crate::reexport::*;
13 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, LintContext};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc::hir::def::Def;
16 use crate::rustc::hir::*;
17 use crate::rustc::hir::intravisit::*;
18 use crate::rustc_data_structures::fx::{FxHashMap, FxHashSet};
19 use crate::syntax::source_map::Span;
20 use crate::utils::{last_path_segment, span_lint};
21 use crate::syntax::symbol::keywords;
23 /// **What it does:** Checks for lifetime annotations which can be removed by
24 /// relying on lifetime elision.
26 /// **Why is this bad?** The additional lifetimes make the code look more
27 /// complicated, while there is nothing out of the ordinary going on. Removing
28 /// them leads to more readable code.
30 /// **Known problems:** Potential false negatives: we bail out if the function
31 /// has a `where` clause where lifetimes are mentioned.
35 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 { x }
37 declare_clippy_lint! {
38 pub NEEDLESS_LIFETIMES,
40 "using explicit lifetimes for references in function arguments when elision rules \
41 would allow omitting them"
44 /// **What it does:** Checks for lifetimes in generics that are never used
47 /// **Why is this bad?** The additional lifetimes make the code look more
48 /// complicated, while there is nothing out of the ordinary going on. Removing
49 /// them leads to more readable code.
51 /// **Known problems:** None.
55 /// fn unused_lifetime<'a>(x: u8) { .. }
57 declare_clippy_lint! {
58 pub EXTRA_UNUSED_LIFETIMES,
60 "unused lifetimes in function definitions"
63 #[derive(Copy, Clone)]
64 pub struct LifetimePass;
66 impl LintPass for LifetimePass {
67 fn get_lints(&self) -> LintArray {
68 lint_array!(NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES)
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LifetimePass {
73 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
74 if let ItemKind::Fn(ref decl, _, ref generics, id) = item.node {
75 check_fn_inner(cx, decl, Some(id), generics, item.span);
79 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
80 if let ImplItemKind::Method(ref sig, id) = item.node {
81 check_fn_inner(cx, &sig.decl, Some(id), &item.generics, item.span);
85 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
86 if let TraitItemKind::Method(ref sig, ref body) = item.node {
87 let body = match *body {
88 TraitMethod::Required(_) => None,
89 TraitMethod::Provided(id) => Some(id),
91 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span);
96 /// The lifetime of a &-reference.
97 #[derive(PartialEq, Eq, Hash, Debug)]
104 fn check_fn_inner<'a, 'tcx>(
105 cx: &LateContext<'a, 'tcx>,
107 body: Option<BodyId>,
108 generics: &'tcx Generics,
111 if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
115 let mut bounds_lts = Vec::new();
116 let types = generics.params.iter().filter(|param| match param.kind {
117 GenericParamKind::Type { .. } => true,
118 GenericParamKind::Lifetime { .. } => false,
121 for bound in &typ.bounds {
122 let mut visitor = RefVisitor::new(cx);
123 walk_param_bound(&mut visitor, bound);
124 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
127 if let GenericBound::Trait(ref trait_ref, _) = *bound {
128 let params = &trait_ref
133 .expect("a path must have at least one segment")
135 if let Some(ref params) = *params {
136 let lifetimes = params.args.iter().filter_map(|arg| match arg {
137 GenericArg::Lifetime(lt) => Some(lt),
138 GenericArg::Type(_) => None,
140 for bound in lifetimes {
141 if bound.name != LifetimeName::Static && !bound.is_elided() {
144 bounds_lts.push(bound);
150 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
155 "explicit lifetimes given in parameter types where they could be elided (or replaced with `'_` if needed by type declaration)",
158 report_extra_lifetimes(cx, decl, generics);
161 fn could_use_elision<'a, 'tcx: 'a>(
162 cx: &LateContext<'a, 'tcx>,
164 body: Option<BodyId>,
165 named_generics: &'tcx [GenericParam],
166 bounds_lts: Vec<&'tcx Lifetime>,
168 // There are two scenarios where elision works:
169 // * no output references, all input references have different LT
170 // * output references, exactly one input reference with same LT
171 // All lifetimes must be unnamed, 'static or defined without bounds on the
172 // level of the current item.
175 let allowed_lts = allowed_lts_from(named_generics);
177 // these will collect all the lifetimes for references in arg/return types
178 let mut input_visitor = RefVisitor::new(cx);
179 let mut output_visitor = RefVisitor::new(cx);
181 // extract lifetimes in input argument types
182 for arg in &func.inputs {
183 input_visitor.visit_ty(arg);
185 // extract lifetimes in output type
186 if let Return(ref ty) = func.output {
187 output_visitor.visit_ty(ty);
190 let input_lts = match input_visitor.into_vec() {
191 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
192 None => return false,
194 let output_lts = match output_visitor.into_vec() {
196 None => return false,
199 if let Some(body_id) = body {
200 let mut checker = BodyLifetimeChecker {
201 lifetimes_used_in_body: false,
203 checker.visit_expr(&cx.tcx.hir.body(body_id).value);
204 if checker.lifetimes_used_in_body {
209 // check for lifetimes from higher scopes
210 for lt in input_lts.iter().chain(output_lts.iter()) {
211 if !allowed_lts.contains(lt) {
216 // no input lifetimes? easy case!
217 if input_lts.is_empty() {
219 } else if output_lts.is_empty() {
220 // no output lifetimes, check distinctness of input lifetimes
222 // only unnamed and static, ok
223 let unnamed_and_static = input_lts
225 .all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
226 if unnamed_and_static {
229 // we have no output reference, so we only need all distinct lifetimes
230 input_lts.len() == unique_lifetimes(&input_lts)
232 // we have output references, so we need one input reference,
233 // and all output lifetimes must be the same
234 if unique_lifetimes(&output_lts) > 1 {
237 if input_lts.len() == 1 {
238 match (&input_lts[0], &output_lts[0]) {
239 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
240 (&RefLt::Named(_), &RefLt::Unnamed) => true,
241 _ => false, /* already elided, different named lifetimes
242 * or something static going on */
250 fn allowed_lts_from(named_generics: &[GenericParam]) -> FxHashSet<RefLt> {
251 let mut allowed_lts = FxHashSet::default();
252 for par in named_generics.iter() {
253 if let GenericParamKind::Lifetime { .. } = par.kind {
254 if par.bounds.is_empty() {
255 allowed_lts.insert(RefLt::Named(par.name.ident().name));
259 allowed_lts.insert(RefLt::Unnamed);
260 allowed_lts.insert(RefLt::Static);
264 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
265 for lt in bounds_lts {
266 if lt.name != LifetimeName::Static {
267 vec.push(RefLt::Named(lt.name.ident().name));
274 /// Number of unique lifetimes in the given vector.
275 fn unique_lifetimes(lts: &[RefLt]) -> usize {
276 lts.iter().collect::<FxHashSet<_>>().len()
279 /// A visitor usable for `rustc_front::visit::walk_ty()`.
280 struct RefVisitor<'a, 'tcx: 'a> {
281 cx: &'a LateContext<'a, 'tcx>,
286 impl<'v, 't> RefVisitor<'v, 't> {
287 fn new(cx: &'v LateContext<'v, 't>) -> Self {
295 fn record(&mut self, lifetime: &Option<Lifetime>) {
296 if let Some(ref lt) = *lifetime {
297 if lt.name == LifetimeName::Static {
298 self.lts.push(RefLt::Static);
299 } else if lt.is_elided() {
300 self.lts.push(RefLt::Unnamed);
302 self.lts.push(RefLt::Named(lt.name.ident().name));
305 self.lts.push(RefLt::Unnamed);
309 fn into_vec(self) -> Option<Vec<RefLt>> {
317 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
318 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
319 if !last_path_segment.parenthesized
320 && !last_path_segment.args.iter().any(|arg| match arg {
321 GenericArg::Lifetime(_) => true,
322 GenericArg::Type(_) => false,
324 let hir_id = self.cx.tcx.hir.node_to_hir_id(ty.id);
325 match self.cx.tables.qpath_def(qpath, hir_id) {
326 Def::TyAlias(def_id) | Def::Struct(def_id) => {
327 let generics = self.cx.tcx.generics_of(def_id);
328 for _ in generics.params.as_slice() {
332 Def::Trait(def_id) => {
333 let trait_def = self.cx.tcx.trait_def(def_id);
334 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
345 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
346 // for lifetimes as parameters of generics
347 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
348 self.record(&Some(*lifetime));
351 fn visit_ty(&mut self, ty: &'tcx Ty) {
353 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
356 TyKind::Path(ref path) => {
358 self.collect_anonymous_lifetimes(path, ty);
360 TyKind::Def(item, _) => {
361 if let ItemKind::Existential(ref exist_ty) = self.cx.tcx.hir.expect_item(item.id).node {
362 for bound in &exist_ty.bounds {
363 if let GenericBound::Outlives(_) = *bound {
372 TyKind::TraitObject(ref bounds, ref lt) => {
376 for bound in bounds {
377 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
385 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
386 NestedVisitorMap::None
390 /// Are any lifetimes mentioned in the `where` clause? If yes, we don't try to
391 /// reason about elision.
392 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
393 for predicate in &where_clause.predicates {
395 WherePredicate::RegionPredicate(..) => return true,
396 WherePredicate::BoundPredicate(ref pred) => {
397 // a predicate like F: Trait or F: for<'a> Trait<'a>
398 let mut visitor = RefVisitor::new(cx);
399 // walk the type F, it may not contain LT refs
400 walk_ty(&mut visitor, &pred.bounded_ty);
401 if !visitor.lts.is_empty() {
404 // if the bounds define new lifetimes, they are fine to occur
405 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
406 // now walk the bounds
407 for bound in pred.bounds.iter() {
408 walk_param_bound(&mut visitor, bound);
410 // and check that all lifetimes are allowed
411 match visitor.into_vec() {
412 None => return false,
413 Some(lts) => for lt in lts {
414 if !allowed_lts.contains(<) {
420 WherePredicate::EqPredicate(ref pred) => {
421 let mut visitor = RefVisitor::new(cx);
422 walk_ty(&mut visitor, &pred.lhs_ty);
423 walk_ty(&mut visitor, &pred.rhs_ty);
424 if !visitor.lts.is_empty() {
433 struct LifetimeChecker {
434 map: FxHashMap<Name, Span>,
437 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
438 // for lifetimes as parameters of generics
439 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
440 self.map.remove(&lifetime.name.ident().name);
443 fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
444 // don't actually visit `<'a>` or `<'a: 'b>`
445 // we've already visited the `'a` declarations and
446 // don't want to spuriously remove them
447 // `'b` in `'a: 'b` is useless unless used elsewhere in
448 // a non-lifetime bound
449 if let GenericParamKind::Type { .. } = param.kind {
450 walk_generic_param(self, param)
453 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
454 NestedVisitorMap::None
458 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
459 let hs = generics.params.iter()
460 .filter_map(|par| match par.kind {
461 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
465 let mut checker = LifetimeChecker { map: hs };
467 walk_generics(&mut checker, generics);
468 walk_fn_decl(&mut checker, func);
470 for &v in checker.map.values() {
471 span_lint(cx, EXTRA_UNUSED_LIFETIMES, v, "this lifetime isn't used in the function definition");
475 struct BodyLifetimeChecker {
476 lifetimes_used_in_body: bool,
479 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
480 // for lifetimes as parameters of generics
481 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
482 if lifetime.name.ident().name != keywords::Invalid.name() && lifetime.name.ident().name != "'static" {
483 self.lifetimes_used_in_body = true;
487 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
488 NestedVisitorMap::None