1 use crate::reexport::*;
2 use crate::utils::{last_path_segment, span_lint};
4 use rustc::hir::def::Def;
5 use rustc::hir::intravisit::*;
7 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
8 use rustc::{declare_tool_lint, lint_array};
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use syntax::source_map::Span;
11 use 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 {
29 declare_clippy_lint! {
30 pub NEEDLESS_LIFETIMES,
32 "using explicit lifetimes for references in function arguments when elision rules \
33 would allow omitting them"
36 /// **What it does:** Checks for lifetimes in generics that are never used
39 /// **Why is this bad?** The additional lifetimes make the code look more
40 /// complicated, while there is nothing out of the ordinary going on. Removing
41 /// them leads to more readable code.
43 /// **Known problems:** None.
47 /// fn unused_lifetime<'a>(x: u8) {
51 declare_clippy_lint! {
52 pub EXTRA_UNUSED_LIFETIMES,
54 "unused lifetimes in function definitions"
57 #[derive(Copy, Clone)]
58 pub struct LifetimePass;
60 impl LintPass for LifetimePass {
61 fn get_lints(&self) -> LintArray {
62 lint_array!(NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES)
65 fn name(&self) -> &'static str {
70 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LifetimePass {
71 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
72 if let ItemKind::Fn(ref decl, _, ref generics, id) = item.node {
73 check_fn_inner(cx, decl, Some(id), generics, item.span);
77 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
78 if let ImplItemKind::Method(ref sig, id) = item.node {
79 check_fn_inner(cx, &sig.decl, Some(id), &item.generics, item.span);
83 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
84 if let TraitItemKind::Method(ref sig, ref body) = item.node {
85 let body = match *body {
86 TraitMethod::Required(_) => None,
87 TraitMethod::Provided(id) => Some(id),
89 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span);
94 /// The lifetime of a &-reference.
95 #[derive(PartialEq, Eq, Hash, Debug)]
102 fn check_fn_inner<'a, 'tcx>(
103 cx: &LateContext<'a, 'tcx>,
105 body: Option<BodyId>,
106 generics: &'tcx Generics,
109 if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
113 let mut bounds_lts = Vec::new();
114 let types = generics.params.iter().filter(|param| match param.kind {
115 GenericParamKind::Type { .. } => true,
119 for bound in &typ.bounds {
120 let mut visitor = RefVisitor::new(cx);
121 walk_param_bound(&mut visitor, bound);
122 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
125 if let GenericBound::Trait(ref trait_ref, _) = *bound {
126 let params = &trait_ref
131 .expect("a path must have at least one segment")
133 if let Some(ref params) = *params {
134 let lifetimes = params.args.iter().filter_map(|arg| match arg {
135 GenericArg::Lifetime(lt) => Some(lt),
138 for bound in lifetimes {
139 if bound.name != LifetimeName::Static && !bound.is_elided() {
142 bounds_lts.push(bound);
148 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
153 "explicit lifetimes given in parameter types where they could be elided \
154 (or replaced with `'_` if needed by type declaration)",
157 report_extra_lifetimes(cx, decl, generics);
160 fn could_use_elision<'a, 'tcx: 'a>(
161 cx: &LateContext<'a, 'tcx>,
163 body: Option<BodyId>,
164 named_generics: &'tcx [GenericParam],
165 bounds_lts: Vec<&'tcx Lifetime>,
167 // There are two scenarios where elision works:
168 // * no output references, all input references have different LT
169 // * output references, exactly one input reference with same LT
170 // All lifetimes must be unnamed, 'static or defined without bounds on the
171 // level of the current item.
174 let allowed_lts = allowed_lts_from(named_generics);
176 // these will collect all the lifetimes for references in arg/return types
177 let mut input_visitor = RefVisitor::new(cx);
178 let mut output_visitor = RefVisitor::new(cx);
180 // extract lifetimes in input argument types
181 for arg in &func.inputs {
182 input_visitor.visit_ty(arg);
184 // extract lifetimes in output type
185 if let Return(ref ty) = func.output {
186 output_visitor.visit_ty(ty);
189 let input_lts = match input_visitor.into_vec() {
190 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
191 None => return false,
193 let output_lts = match output_visitor.into_vec() {
195 None => return false,
198 if let Some(body_id) = body {
199 let mut checker = BodyLifetimeChecker {
200 lifetimes_used_in_body: false,
202 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
203 if checker.lifetimes_used_in_body {
208 // check for lifetimes from higher scopes
209 for lt in input_lts.iter().chain(output_lts.iter()) {
210 if !allowed_lts.contains(lt) {
215 // no input lifetimes? easy case!
216 if input_lts.is_empty() {
218 } else if output_lts.is_empty() {
219 // no output lifetimes, check distinctness of input lifetimes
221 // only unnamed and static, ok
222 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
223 if unnamed_and_static {
226 // we have no output reference, so we only need all distinct lifetimes
227 input_lts.len() == unique_lifetimes(&input_lts)
229 // we have output references, so we need one input reference,
230 // and all output lifetimes must be the same
231 if unique_lifetimes(&output_lts) > 1 {
234 if input_lts.len() == 1 {
235 match (&input_lts[0], &output_lts[0]) {
236 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
237 (&RefLt::Named(_), &RefLt::Unnamed) => true,
238 _ => false, /* already elided, different named lifetimes
239 * or something static going on */
247 fn allowed_lts_from(named_generics: &[GenericParam]) -> FxHashSet<RefLt> {
248 let mut allowed_lts = FxHashSet::default();
249 for par in named_generics.iter() {
250 if let GenericParamKind::Lifetime { .. } = par.kind {
251 if par.bounds.is_empty() {
252 allowed_lts.insert(RefLt::Named(par.name.ident().name));
256 allowed_lts.insert(RefLt::Unnamed);
257 allowed_lts.insert(RefLt::Static);
261 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
262 for lt in bounds_lts {
263 if lt.name != LifetimeName::Static {
264 vec.push(RefLt::Named(lt.name.ident().name));
271 /// Number of unique lifetimes in the given vector.
272 fn unique_lifetimes(lts: &[RefLt]) -> usize {
273 lts.iter().collect::<FxHashSet<_>>().len()
276 /// A visitor usable for `rustc_front::visit::walk_ty()`.
277 struct RefVisitor<'a, 'tcx: 'a> {
278 cx: &'a LateContext<'a, 'tcx>,
283 impl<'v, 't> RefVisitor<'v, 't> {
284 fn new(cx: &'v LateContext<'v, 't>) -> Self {
292 fn record(&mut self, lifetime: &Option<Lifetime>) {
293 if let Some(ref lt) = *lifetime {
294 if lt.name == LifetimeName::Static {
295 self.lts.push(RefLt::Static);
296 } else if lt.is_elided() {
297 self.lts.push(RefLt::Unnamed);
299 self.lts.push(RefLt::Named(lt.name.ident().name));
302 self.lts.push(RefLt::Unnamed);
306 fn into_vec(self) -> Option<Vec<RefLt>> {
314 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
315 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
316 if !last_path_segment.parenthesized
317 && !last_path_segment.args.iter().any(|arg| match arg {
318 GenericArg::Lifetime(_) => true,
322 let hir_id = self.cx.tcx.hir().node_to_hir_id(ty.id);
323 match self.cx.tables.qpath_def(qpath, hir_id) {
324 Def::TyAlias(def_id) | Def::Struct(def_id) => {
325 let generics = self.cx.tcx.generics_of(def_id);
326 for _ in generics.params.as_slice() {
330 Def::Trait(def_id) => {
331 let trait_def = self.cx.tcx.trait_def(def_id);
332 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
343 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
344 // for lifetimes as parameters of generics
345 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
346 self.record(&Some(*lifetime));
349 fn visit_ty(&mut self, ty: &'tcx Ty) {
351 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
354 TyKind::Path(ref path) => {
355 self.collect_anonymous_lifetimes(path, ty);
357 TyKind::Def(item, _) => {
358 if let ItemKind::Existential(ref exist_ty) = self.cx.tcx.hir().expect_item(item.id).node {
359 for bound in &exist_ty.bounds {
360 if let GenericBound::Outlives(_) = *bound {
369 TyKind::TraitObject(ref bounds, ref lt) => {
373 for bound in bounds {
374 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
382 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
383 NestedVisitorMap::None
387 /// Are any lifetimes mentioned in the `where` clause? If yes, we don't try to
388 /// reason about elision.
389 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
390 for predicate in &where_clause.predicates {
392 WherePredicate::RegionPredicate(..) => return true,
393 WherePredicate::BoundPredicate(ref pred) => {
394 // a predicate like F: Trait or F: for<'a> Trait<'a>
395 let mut visitor = RefVisitor::new(cx);
396 // walk the type F, it may not contain LT refs
397 walk_ty(&mut visitor, &pred.bounded_ty);
398 if !visitor.lts.is_empty() {
401 // if the bounds define new lifetimes, they are fine to occur
402 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
403 // now walk the bounds
404 for bound in pred.bounds.iter() {
405 walk_param_bound(&mut visitor, bound);
407 // and check that all lifetimes are allowed
408 match visitor.into_vec() {
409 None => return false,
412 if !allowed_lts.contains(<) {
419 WherePredicate::EqPredicate(ref pred) => {
420 let mut visitor = RefVisitor::new(cx);
421 walk_ty(&mut visitor, &pred.lhs_ty);
422 walk_ty(&mut visitor, &pred.rhs_ty);
423 if !visitor.lts.is_empty() {
432 struct LifetimeChecker {
433 map: FxHashMap<Name, Span>,
436 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
437 // for lifetimes as parameters of generics
438 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
439 self.map.remove(&lifetime.name.ident().name);
442 fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
443 // don't actually visit `<'a>` or `<'a: 'b>`
444 // we've already visited the `'a` declarations and
445 // don't want to spuriously remove them
446 // `'b` in `'a: 'b` is useless unless used elsewhere in
447 // a non-lifetime bound
448 if let GenericParamKind::Type { .. } = param.kind {
449 walk_generic_param(self, param)
452 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
453 NestedVisitorMap::None
457 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
461 .filter_map(|par| match par.kind {
462 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
466 let mut checker = LifetimeChecker { map: hs };
468 walk_generics(&mut checker, generics);
469 walk_fn_decl(&mut checker, func);
471 for &v in checker.map.values() {
474 EXTRA_UNUSED_LIFETIMES,
476 "this lifetime isn't used in the function definition",
481 struct BodyLifetimeChecker {
482 lifetimes_used_in_body: bool,
485 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
486 // for lifetimes as parameters of generics
487 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
488 if lifetime.name.ident().name != keywords::Invalid.name() && lifetime.name.ident().name != "'static" {
489 self.lifetimes_used_in_body = true;
493 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
494 NestedVisitorMap::None