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};
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 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
31 pub NEEDLESS_LIFETIMES,
33 "using explicit lifetimes for references in function arguments when elision rules \
34 would allow omitting them"
37 declare_clippy_lint! {
38 /// **What it does:** Checks for lifetimes in generics that are never used
41 /// **Why is this bad?** The additional lifetimes make the code look more
42 /// complicated, while there is nothing out of the ordinary going on. Removing
43 /// them leads to more readable code.
45 /// **Known problems:** None.
49 /// fn unused_lifetime<'a>(x: u8) {
53 pub EXTRA_UNUSED_LIFETIMES,
55 "unused lifetimes in function definitions"
58 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes {
61 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
62 if let ItemKind::Fn(ref decl, _, ref generics, id) = item.node {
63 check_fn_inner(cx, decl, Some(id), generics, item.span);
67 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
68 if let ImplItemKind::Method(ref sig, id) = item.node {
69 check_fn_inner(cx, &sig.decl, Some(id), &item.generics, item.span);
73 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
74 if let TraitItemKind::Method(ref sig, ref body) = item.node {
75 let body = match *body {
76 TraitMethod::Required(_) => None,
77 TraitMethod::Provided(id) => Some(id),
79 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span);
84 /// The lifetime of a &-reference.
85 #[derive(PartialEq, Eq, Hash, Debug)]
92 fn check_fn_inner<'a, 'tcx>(
93 cx: &LateContext<'a, 'tcx>,
96 generics: &'tcx Generics,
99 if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
103 let mut bounds_lts = Vec::new();
104 let types = generics.params.iter().filter(|param| match param.kind {
105 GenericParamKind::Type { .. } => true,
109 for bound in &typ.bounds {
110 let mut visitor = RefVisitor::new(cx);
111 walk_param_bound(&mut visitor, bound);
112 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
115 if let GenericBound::Trait(ref trait_ref, _) = *bound {
116 let params = &trait_ref
121 .expect("a path must have at least one segment")
123 if let Some(ref params) = *params {
124 let lifetimes = params.args.iter().filter_map(|arg| match arg {
125 GenericArg::Lifetime(lt) => Some(lt),
128 for bound in lifetimes {
129 if bound.name != LifetimeName::Static && !bound.is_elided() {
132 bounds_lts.push(bound);
138 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
143 "explicit lifetimes given in parameter types where they could be elided \
144 (or replaced with `'_` if needed by type declaration)",
147 report_extra_lifetimes(cx, decl, generics);
150 fn could_use_elision<'a, 'tcx: 'a>(
151 cx: &LateContext<'a, 'tcx>,
153 body: Option<BodyId>,
154 named_generics: &'tcx [GenericParam],
155 bounds_lts: Vec<&'tcx Lifetime>,
157 // There are two scenarios where elision works:
158 // * no output references, all input references have different LT
159 // * output references, exactly one input reference with same LT
160 // All lifetimes must be unnamed, 'static or defined without bounds on the
161 // level of the current item.
164 let allowed_lts = allowed_lts_from(named_generics);
166 // these will collect all the lifetimes for references in arg/return types
167 let mut input_visitor = RefVisitor::new(cx);
168 let mut output_visitor = RefVisitor::new(cx);
170 // extract lifetimes in input argument types
171 for arg in &func.inputs {
172 input_visitor.visit_ty(arg);
174 // extract lifetimes in output type
175 if let Return(ref ty) = func.output {
176 output_visitor.visit_ty(ty);
179 let input_lts = match input_visitor.into_vec() {
180 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
181 None => return false,
183 let output_lts = match output_visitor.into_vec() {
185 None => return false,
188 if let Some(body_id) = body {
189 let mut checker = BodyLifetimeChecker {
190 lifetimes_used_in_body: false,
192 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
193 if checker.lifetimes_used_in_body {
198 // check for lifetimes from higher scopes
199 for lt in input_lts.iter().chain(output_lts.iter()) {
200 if !allowed_lts.contains(lt) {
205 // no input lifetimes? easy case!
206 if input_lts.is_empty() {
208 } else if output_lts.is_empty() {
209 // no output lifetimes, check distinctness of input lifetimes
211 // only unnamed and static, ok
212 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
213 if unnamed_and_static {
216 // we have no output reference, so we only need all distinct lifetimes
217 input_lts.len() == unique_lifetimes(&input_lts)
219 // we have output references, so we need one input reference,
220 // and all output lifetimes must be the same
221 if unique_lifetimes(&output_lts) > 1 {
224 if input_lts.len() == 1 {
225 match (&input_lts[0], &output_lts[0]) {
226 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
227 (&RefLt::Named(_), &RefLt::Unnamed) => true,
228 _ => false, /* already elided, different named lifetimes
229 * or something static going on */
237 fn allowed_lts_from(named_generics: &[GenericParam]) -> FxHashSet<RefLt> {
238 let mut allowed_lts = FxHashSet::default();
239 for par in named_generics.iter() {
240 if let GenericParamKind::Lifetime { .. } = par.kind {
241 if par.bounds.is_empty() {
242 allowed_lts.insert(RefLt::Named(par.name.ident().name));
246 allowed_lts.insert(RefLt::Unnamed);
247 allowed_lts.insert(RefLt::Static);
251 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
252 for lt in bounds_lts {
253 if lt.name != LifetimeName::Static {
254 vec.push(RefLt::Named(lt.name.ident().name));
261 /// Number of unique lifetimes in the given vector.
262 fn unique_lifetimes(lts: &[RefLt]) -> usize {
263 lts.iter().collect::<FxHashSet<_>>().len()
266 /// A visitor usable for `rustc_front::visit::walk_ty()`.
267 struct RefVisitor<'a, 'tcx: 'a> {
268 cx: &'a LateContext<'a, 'tcx>,
273 impl<'v, 't> RefVisitor<'v, 't> {
274 fn new(cx: &'v LateContext<'v, 't>) -> Self {
282 fn record(&mut self, lifetime: &Option<Lifetime>) {
283 if let Some(ref lt) = *lifetime {
284 if lt.name == LifetimeName::Static {
285 self.lts.push(RefLt::Static);
286 } else if lt.is_elided() {
287 self.lts.push(RefLt::Unnamed);
289 self.lts.push(RefLt::Named(lt.name.ident().name));
292 self.lts.push(RefLt::Unnamed);
296 fn into_vec(self) -> Option<Vec<RefLt>> {
304 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
305 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
306 if !last_path_segment.parenthesized
307 && !last_path_segment.args.iter().any(|arg| match arg {
308 GenericArg::Lifetime(_) => true,
312 let hir_id = ty.hir_id;
313 match self.cx.tables.qpath_res(qpath, hir_id) {
314 Res::Def(DefKind::TyAlias, def_id) | Res::Def(DefKind::Struct, def_id) => {
315 let generics = self.cx.tcx.generics_of(def_id);
316 for _ in generics.params.as_slice() {
320 Res::Def(DefKind::Trait, def_id) => {
321 let trait_def = self.cx.tcx.trait_def(def_id);
322 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
333 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
334 // for lifetimes as parameters of generics
335 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
336 self.record(&Some(*lifetime));
339 fn visit_ty(&mut self, ty: &'tcx Ty) {
341 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
344 TyKind::Path(ref path) => {
345 self.collect_anonymous_lifetimes(path, ty);
347 TyKind::Def(item, _) => {
348 let map = self.cx.tcx.hir();
349 if let ItemKind::Existential(ref exist_ty) = map.expect_item(map.hir_to_node_id(item.id)).node {
350 for bound in &exist_ty.bounds {
351 if let GenericBound::Outlives(_) = *bound {
360 TyKind::TraitObject(ref bounds, ref lt) => {
364 for bound in bounds {
365 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
373 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
374 NestedVisitorMap::None
378 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
379 /// reason about elision.
380 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
381 for predicate in &where_clause.predicates {
383 WherePredicate::RegionPredicate(..) => return true,
384 WherePredicate::BoundPredicate(ref pred) => {
385 // a predicate like F: Trait or F: for<'a> Trait<'a>
386 let mut visitor = RefVisitor::new(cx);
387 // walk the type F, it may not contain LT refs
388 walk_ty(&mut visitor, &pred.bounded_ty);
389 if !visitor.lts.is_empty() {
392 // if the bounds define new lifetimes, they are fine to occur
393 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
394 // now walk the bounds
395 for bound in pred.bounds.iter() {
396 walk_param_bound(&mut visitor, bound);
398 // and check that all lifetimes are allowed
399 match visitor.into_vec() {
400 None => return false,
403 if !allowed_lts.contains(<) {
410 WherePredicate::EqPredicate(ref pred) => {
411 let mut visitor = RefVisitor::new(cx);
412 walk_ty(&mut visitor, &pred.lhs_ty);
413 walk_ty(&mut visitor, &pred.rhs_ty);
414 if !visitor.lts.is_empty() {
423 struct LifetimeChecker {
424 map: FxHashMap<Name, Span>,
427 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
428 // for lifetimes as parameters of generics
429 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
430 self.map.remove(&lifetime.name.ident().name);
433 fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
434 // don't actually visit `<'a>` or `<'a: 'b>`
435 // we've already visited the `'a` declarations and
436 // don't want to spuriously remove them
437 // `'b` in `'a: 'b` is useless unless used elsewhere in
438 // a non-lifetime bound
439 if let GenericParamKind::Type { .. } = param.kind {
440 walk_generic_param(self, param)
443 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
444 NestedVisitorMap::None
448 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
452 .filter_map(|par| match par.kind {
453 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
457 let mut checker = LifetimeChecker { map: hs };
459 walk_generics(&mut checker, generics);
460 walk_fn_decl(&mut checker, func);
462 for &v in checker.map.values() {
465 EXTRA_UNUSED_LIFETIMES,
467 "this lifetime isn't used in the function definition",
472 struct BodyLifetimeChecker {
473 lifetimes_used_in_body: bool,
476 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
477 // for lifetimes as parameters of generics
478 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
479 if lifetime.name.ident().name != kw::Invalid && lifetime.name.ident().name != kw::StaticLifetime {
480 self.lifetimes_used_in_body = true;
484 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
485 NestedVisitorMap::None