2 use rustc::hir::def::{DefKind, Res};
3 use rustc::hir::intravisit::*;
5 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use syntax::source_map::Span;
9 use syntax::symbol::kw;
11 use crate::reexport::*;
12 use crate::utils::{last_path_segment, span_lint, trait_ref_of_method};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for lifetime annotations which can be removed by
16 /// relying on lifetime elision.
18 /// **Why is this bad?** The additional lifetimes make the code look more
19 /// complicated, while there is nothing out of the ordinary going on. Removing
20 /// them leads to more readable code.
22 /// **Known problems:** Potential false negatives: we bail out if the function
23 /// has a `where` clause where lifetimes are mentioned.
27 /// // Bad: unnecessary lifetime annotations
28 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
33 /// fn elided(x: &u8, y: u8) -> &u8 {
37 pub NEEDLESS_LIFETIMES,
39 "using explicit lifetimes for references in function arguments when elision rules \
40 would allow omitting them"
43 declare_clippy_lint! {
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 /// // Bad: unnecessary lifetimes
56 /// fn unused_lifetime<'a>(x: u8) {
61 /// fn no_lifetime(x: u8) {
65 pub EXTRA_UNUSED_LIFETIMES,
67 "unused lifetimes in function definitions"
70 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes {
73 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
74 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
75 check_fn_inner(cx, &sig.decl, Some(id), generics, item.span, true);
79 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
80 if let ImplItemKind::Method(ref sig, id) = item.kind {
81 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id).is_none();
88 report_extra_lifetimes,
93 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
94 if let TraitItemKind::Method(ref sig, ref body) = item.kind {
95 let body = match *body {
96 TraitMethod::Required(_) => None,
97 TraitMethod::Provided(id) => Some(id),
99 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span, true);
104 /// The lifetime of a &-reference.
105 #[derive(PartialEq, Eq, Hash, Debug)]
112 fn check_fn_inner<'a, 'tcx>(
113 cx: &LateContext<'a, 'tcx>,
115 body: Option<BodyId>,
116 generics: &'tcx Generics,
118 report_extra_lifetimes: bool,
120 if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
124 let mut bounds_lts = Vec::new();
125 let types = generics.params.iter().filter(|param| match param.kind {
126 GenericParamKind::Type { .. } => true,
130 for bound in &typ.bounds {
131 let mut visitor = RefVisitor::new(cx);
132 walk_param_bound(&mut visitor, bound);
133 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
136 if let GenericBound::Trait(ref trait_ref, _) = *bound {
137 let params = &trait_ref
142 .expect("a path must have at least one segment")
144 if let Some(ref params) = *params {
145 let lifetimes = params.args.iter().filter_map(|arg| match arg {
146 GenericArg::Lifetime(lt) => Some(lt),
149 for bound in lifetimes {
150 if bound.name != LifetimeName::Static && !bound.is_elided() {
153 bounds_lts.push(bound);
159 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
164 "explicit lifetimes given in parameter types where they could be elided \
165 (or replaced with `'_` if needed by type declaration)",
168 if report_extra_lifetimes {
169 self::report_extra_lifetimes(cx, decl, generics);
173 fn could_use_elision<'a, 'tcx>(
174 cx: &LateContext<'a, 'tcx>,
176 body: Option<BodyId>,
177 named_generics: &'tcx [GenericParam],
178 bounds_lts: Vec<&'tcx Lifetime>,
180 // There are two scenarios where elision works:
181 // * no output references, all input references have different LT
182 // * output references, exactly one input reference with same LT
183 // All lifetimes must be unnamed, 'static or defined without bounds on the
184 // level of the current item.
187 let allowed_lts = allowed_lts_from(named_generics);
189 // these will collect all the lifetimes for references in arg/return types
190 let mut input_visitor = RefVisitor::new(cx);
191 let mut output_visitor = RefVisitor::new(cx);
193 // extract lifetimes in input argument types
194 for arg in &func.inputs {
195 input_visitor.visit_ty(arg);
197 // extract lifetimes in output type
198 if let Return(ref ty) = func.output {
199 output_visitor.visit_ty(ty);
202 let input_lts = match input_visitor.into_vec() {
203 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
204 None => return false,
206 let output_lts = match output_visitor.into_vec() {
208 None => return false,
211 if let Some(body_id) = body {
212 let mut checker = BodyLifetimeChecker {
213 lifetimes_used_in_body: false,
215 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
216 if checker.lifetimes_used_in_body {
221 // check for lifetimes from higher scopes
222 for lt in input_lts.iter().chain(output_lts.iter()) {
223 if !allowed_lts.contains(lt) {
228 // no input lifetimes? easy case!
229 if input_lts.is_empty() {
231 } else if output_lts.is_empty() {
232 // no output lifetimes, check distinctness of input lifetimes
234 // only unnamed and static, ok
235 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
236 if unnamed_and_static {
239 // we have no output reference, so we only need all distinct lifetimes
240 input_lts.len() == unique_lifetimes(&input_lts)
242 // we have output references, so we need one input reference,
243 // and all output lifetimes must be the same
244 if unique_lifetimes(&output_lts) > 1 {
247 if input_lts.len() == 1 {
248 match (&input_lts[0], &output_lts[0]) {
249 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
250 (&RefLt::Named(_), &RefLt::Unnamed) => true,
251 _ => false, /* already elided, different named lifetimes
252 * or something static going on */
260 fn allowed_lts_from(named_generics: &[GenericParam]) -> FxHashSet<RefLt> {
261 let mut allowed_lts = FxHashSet::default();
262 for par in named_generics.iter() {
263 if let GenericParamKind::Lifetime { .. } = par.kind {
264 if par.bounds.is_empty() {
265 allowed_lts.insert(RefLt::Named(par.name.ident().name));
269 allowed_lts.insert(RefLt::Unnamed);
270 allowed_lts.insert(RefLt::Static);
274 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
275 for lt in bounds_lts {
276 if lt.name != LifetimeName::Static {
277 vec.push(RefLt::Named(lt.name.ident().name));
284 /// Number of unique lifetimes in the given vector.
286 fn unique_lifetimes(lts: &[RefLt]) -> usize {
287 lts.iter().collect::<FxHashSet<_>>().len()
290 /// A visitor usable for `rustc_front::visit::walk_ty()`.
291 struct RefVisitor<'a, 'tcx> {
292 cx: &'a LateContext<'a, 'tcx>,
297 impl<'v, 't> RefVisitor<'v, 't> {
298 fn new(cx: &'v LateContext<'v, 't>) -> Self {
306 fn record(&mut self, lifetime: &Option<Lifetime>) {
307 if let Some(ref lt) = *lifetime {
308 if lt.name == LifetimeName::Static {
309 self.lts.push(RefLt::Static);
310 } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
311 // Fresh lifetimes generated should be ignored.
312 } else if lt.is_elided() {
313 self.lts.push(RefLt::Unnamed);
315 self.lts.push(RefLt::Named(lt.name.ident().name));
318 self.lts.push(RefLt::Unnamed);
322 fn into_vec(self) -> Option<Vec<RefLt>> {
330 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
331 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
332 if !last_path_segment.parenthesized
333 && !last_path_segment.args.iter().any(|arg| match arg {
334 GenericArg::Lifetime(_) => true,
338 let hir_id = ty.hir_id;
339 match self.cx.tables.qpath_res(qpath, hir_id) {
340 Res::Def(DefKind::TyAlias, def_id) | Res::Def(DefKind::Struct, def_id) => {
341 let generics = self.cx.tcx.generics_of(def_id);
342 for _ in generics.params.as_slice() {
346 Res::Def(DefKind::Trait, def_id) => {
347 let trait_def = self.cx.tcx.trait_def(def_id);
348 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
359 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
360 // for lifetimes as parameters of generics
361 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
362 self.record(&Some(*lifetime));
365 fn visit_ty(&mut self, ty: &'tcx Ty) {
367 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
370 TyKind::Path(ref path) => {
371 self.collect_anonymous_lifetimes(path, ty);
373 TyKind::Def(item, _) => {
374 let map = self.cx.tcx.hir();
375 if let ItemKind::OpaqueTy(ref exist_ty) = map.expect_item(item.id).kind {
376 for bound in &exist_ty.bounds {
377 if let GenericBound::Outlives(_) = *bound {
386 TyKind::TraitObject(ref bounds, ref lt) => {
390 for bound in bounds {
391 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
399 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
400 NestedVisitorMap::None
404 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
405 /// reason about elision.
406 fn has_where_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
407 for predicate in &where_clause.predicates {
409 WherePredicate::RegionPredicate(..) => return true,
410 WherePredicate::BoundPredicate(ref pred) => {
411 // a predicate like F: Trait or F: for<'a> Trait<'a>
412 let mut visitor = RefVisitor::new(cx);
413 // walk the type F, it may not contain LT refs
414 walk_ty(&mut visitor, &pred.bounded_ty);
415 if !visitor.lts.is_empty() {
418 // if the bounds define new lifetimes, they are fine to occur
419 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
420 // now walk the bounds
421 for bound in pred.bounds.iter() {
422 walk_param_bound(&mut visitor, bound);
424 // and check that all lifetimes are allowed
425 match visitor.into_vec() {
426 None => return false,
429 if !allowed_lts.contains(<) {
436 WherePredicate::EqPredicate(ref pred) => {
437 let mut visitor = RefVisitor::new(cx);
438 walk_ty(&mut visitor, &pred.lhs_ty);
439 walk_ty(&mut visitor, &pred.rhs_ty);
440 if !visitor.lts.is_empty() {
449 struct LifetimeChecker {
450 map: FxHashMap<Name, Span>,
453 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
454 // for lifetimes as parameters of generics
455 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
456 self.map.remove(&lifetime.name.ident().name);
459 fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
460 // don't actually visit `<'a>` or `<'a: 'b>`
461 // we've already visited the `'a` declarations and
462 // don't want to spuriously remove them
463 // `'b` in `'a: 'b` is useless unless used elsewhere in
464 // a non-lifetime bound
465 if let GenericParamKind::Type { .. } = param.kind {
466 walk_generic_param(self, param)
469 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
470 NestedVisitorMap::None
474 fn report_extra_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
478 .filter_map(|par| match par.kind {
479 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
483 let mut checker = LifetimeChecker { map: hs };
485 walk_generics(&mut checker, generics);
486 walk_fn_decl(&mut checker, func);
488 for &v in checker.map.values() {
491 EXTRA_UNUSED_LIFETIMES,
493 "this lifetime isn't used in the function definition",
498 struct BodyLifetimeChecker {
499 lifetimes_used_in_body: bool,
502 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
503 // for lifetimes as parameters of generics
504 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
505 if lifetime.name.ident().name != kw::Invalid && lifetime.name.ident().name != kw::StaticLifetime {
506 self.lifetimes_used_in_body = true;
510 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
511 NestedVisitorMap::None