2 use rustc::declare_lint_pass;
3 use rustc::hir::def::{DefKind, Res};
4 use rustc::hir::intravisit::*;
6 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_session::declare_tool_lint;
9 use syntax::source_map::Span;
10 use syntax::symbol::kw;
12 use crate::reexport::*;
13 use crate::utils::{last_path_segment, span_lint, trait_ref_of_method};
15 declare_clippy_lint! {
16 /// **What it does:** Checks for lifetime annotations which can be removed by
17 /// relying on lifetime elision.
19 /// **Why is this bad?** The additional lifetimes make the code look more
20 /// complicated, while there is nothing out of the ordinary going on. Removing
21 /// them leads to more readable code.
23 /// **Known problems:** Potential false negatives: we bail out if the function
24 /// has a `where` clause where lifetimes are mentioned.
28 /// // Bad: unnecessary lifetime annotations
29 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
34 /// fn elided(x: &u8, y: u8) -> &u8 {
38 pub NEEDLESS_LIFETIMES,
40 "using explicit lifetimes for references in function arguments when elision rules \
41 would allow omitting them"
44 declare_clippy_lint! {
45 /// **What it does:** Checks for lifetimes in generics that are never used
48 /// **Why is this bad?** The additional lifetimes make the code look more
49 /// complicated, while there is nothing out of the ordinary going on. Removing
50 /// them leads to more readable code.
52 /// **Known problems:** None.
56 /// // Bad: unnecessary lifetimes
57 /// fn unused_lifetime<'a>(x: u8) {
62 /// fn no_lifetime(x: u8) {
66 pub EXTRA_UNUSED_LIFETIMES,
68 "unused lifetimes in function definitions"
71 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes {
74 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
75 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
76 check_fn_inner(cx, &sig.decl, Some(id), generics, item.span, true);
80 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
81 if let ImplItemKind::Method(ref sig, id) = item.kind {
82 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id).is_none();
89 report_extra_lifetimes,
94 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
95 if let TraitItemKind::Method(ref sig, ref body) = item.kind {
96 let body = match *body {
97 TraitMethod::Required(_) => None,
98 TraitMethod::Provided(id) => Some(id),
100 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span, true);
105 /// The lifetime of a &-reference.
106 #[derive(PartialEq, Eq, Hash, Debug)]
113 fn check_fn_inner<'a, 'tcx>(
114 cx: &LateContext<'a, 'tcx>,
116 body: Option<BodyId>,
117 generics: &'tcx Generics,
119 report_extra_lifetimes: bool,
121 if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
125 let mut bounds_lts = Vec::new();
126 let types = generics.params.iter().filter(|param| match param.kind {
127 GenericParamKind::Type { .. } => true,
131 for bound in &typ.bounds {
132 let mut visitor = RefVisitor::new(cx);
133 walk_param_bound(&mut visitor, bound);
134 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
137 if let GenericBound::Trait(ref trait_ref, _) = *bound {
138 let params = &trait_ref
143 .expect("a path must have at least one segment")
145 if let Some(ref params) = *params {
146 let lifetimes = params.args.iter().filter_map(|arg| match arg {
147 GenericArg::Lifetime(lt) => Some(lt),
150 for bound in lifetimes {
151 if bound.name != LifetimeName::Static && !bound.is_elided() {
154 bounds_lts.push(bound);
160 if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
165 "explicit lifetimes given in parameter types where they could be elided \
166 (or replaced with `'_` if needed by type declaration)",
169 if report_extra_lifetimes {
170 self::report_extra_lifetimes(cx, decl, generics);
174 fn could_use_elision<'a, 'tcx>(
175 cx: &LateContext<'a, 'tcx>,
177 body: Option<BodyId>,
178 named_generics: &'tcx [GenericParam],
179 bounds_lts: Vec<&'tcx Lifetime>,
181 // There are two scenarios where elision works:
182 // * no output references, all input references have different LT
183 // * output references, exactly one input reference with same LT
184 // All lifetimes must be unnamed, 'static or defined without bounds on the
185 // level of the current item.
188 let allowed_lts = allowed_lts_from(named_generics);
190 // these will collect all the lifetimes for references in arg/return types
191 let mut input_visitor = RefVisitor::new(cx);
192 let mut output_visitor = RefVisitor::new(cx);
194 // extract lifetimes in input argument types
195 for arg in &func.inputs {
196 input_visitor.visit_ty(arg);
198 // extract lifetimes in output type
199 if let Return(ref ty) = func.output {
200 output_visitor.visit_ty(ty);
203 let input_lts = match input_visitor.into_vec() {
204 Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
205 None => return false,
207 let output_lts = match output_visitor.into_vec() {
209 None => return false,
212 if let Some(body_id) = body {
213 let mut checker = BodyLifetimeChecker {
214 lifetimes_used_in_body: false,
216 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
217 if checker.lifetimes_used_in_body {
222 // check for lifetimes from higher scopes
223 for lt in input_lts.iter().chain(output_lts.iter()) {
224 if !allowed_lts.contains(lt) {
229 // no input lifetimes? easy case!
230 if input_lts.is_empty() {
232 } else if output_lts.is_empty() {
233 // no output lifetimes, check distinctness of input lifetimes
235 // only unnamed and static, ok
236 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
237 if unnamed_and_static {
240 // we have no output reference, so we only need all distinct lifetimes
241 input_lts.len() == unique_lifetimes(&input_lts)
243 // we have output references, so we need one input reference,
244 // and all output lifetimes must be the same
245 if unique_lifetimes(&output_lts) > 1 {
248 if input_lts.len() == 1 {
249 match (&input_lts[0], &output_lts[0]) {
250 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
251 (&RefLt::Named(_), &RefLt::Unnamed) => true,
252 _ => false, /* already elided, different named lifetimes
253 * or something static going on */
261 fn allowed_lts_from(named_generics: &[GenericParam]) -> FxHashSet<RefLt> {
262 let mut allowed_lts = FxHashSet::default();
263 for par in named_generics.iter() {
264 if let GenericParamKind::Lifetime { .. } = par.kind {
265 if par.bounds.is_empty() {
266 allowed_lts.insert(RefLt::Named(par.name.ident().name));
270 allowed_lts.insert(RefLt::Unnamed);
271 allowed_lts.insert(RefLt::Static);
275 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
276 for lt in bounds_lts {
277 if lt.name != LifetimeName::Static {
278 vec.push(RefLt::Named(lt.name.ident().name));
285 /// Number of unique lifetimes in the given vector.
287 fn unique_lifetimes(lts: &[RefLt]) -> usize {
288 lts.iter().collect::<FxHashSet<_>>().len()
291 /// A visitor usable for `rustc_front::visit::walk_ty()`.
292 struct RefVisitor<'a, 'tcx> {
293 cx: &'a LateContext<'a, 'tcx>,
298 impl<'v, 't> RefVisitor<'v, 't> {
299 fn new(cx: &'v LateContext<'v, 't>) -> Self {
307 fn record(&mut self, lifetime: &Option<Lifetime>) {
308 if let Some(ref lt) = *lifetime {
309 if lt.name == LifetimeName::Static {
310 self.lts.push(RefLt::Static);
311 } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
312 // Fresh lifetimes generated should be ignored.
313 } else if lt.is_elided() {
314 self.lts.push(RefLt::Unnamed);
316 self.lts.push(RefLt::Named(lt.name.ident().name));
319 self.lts.push(RefLt::Unnamed);
323 fn into_vec(self) -> Option<Vec<RefLt>> {
331 fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
332 if let Some(ref last_path_segment) = last_path_segment(qpath).args {
333 if !last_path_segment.parenthesized
334 && !last_path_segment.args.iter().any(|arg| match arg {
335 GenericArg::Lifetime(_) => true,
339 let hir_id = ty.hir_id;
340 match self.cx.tables.qpath_res(qpath, hir_id) {
341 Res::Def(DefKind::TyAlias, def_id) | Res::Def(DefKind::Struct, def_id) => {
342 let generics = self.cx.tcx.generics_of(def_id);
343 for _ in generics.params.as_slice() {
347 Res::Def(DefKind::Trait, def_id) => {
348 let trait_def = self.cx.tcx.trait_def(def_id);
349 for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
360 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
361 // for lifetimes as parameters of generics
362 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
363 self.record(&Some(*lifetime));
366 fn visit_ty(&mut self, ty: &'tcx Ty) {
368 TyKind::Rptr(ref lt, _) if lt.is_elided() => {
371 TyKind::Path(ref path) => {
372 self.collect_anonymous_lifetimes(path, ty);
374 TyKind::Def(item, _) => {
375 let map = self.cx.tcx.hir();
376 if let ItemKind::OpaqueTy(ref exist_ty) = map.expect_item(item.id).kind {
377 for bound in &exist_ty.bounds {
378 if let GenericBound::Outlives(_) = *bound {
387 TyKind::TraitObject(ref bounds, ref lt) => {
391 for bound in bounds {
392 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
400 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
401 NestedVisitorMap::None
405 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
406 /// reason about elision.
407 fn has_where_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
408 for predicate in &where_clause.predicates {
410 WherePredicate::RegionPredicate(..) => return true,
411 WherePredicate::BoundPredicate(ref pred) => {
412 // a predicate like F: Trait or F: for<'a> Trait<'a>
413 let mut visitor = RefVisitor::new(cx);
414 // walk the type F, it may not contain LT refs
415 walk_ty(&mut visitor, &pred.bounded_ty);
416 if !visitor.lts.is_empty() {
419 // if the bounds define new lifetimes, they are fine to occur
420 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
421 // now walk the bounds
422 for bound in pred.bounds.iter() {
423 walk_param_bound(&mut visitor, bound);
425 // and check that all lifetimes are allowed
426 match visitor.into_vec() {
427 None => return false,
430 if !allowed_lts.contains(<) {
437 WherePredicate::EqPredicate(ref pred) => {
438 let mut visitor = RefVisitor::new(cx);
439 walk_ty(&mut visitor, &pred.lhs_ty);
440 walk_ty(&mut visitor, &pred.rhs_ty);
441 if !visitor.lts.is_empty() {
450 struct LifetimeChecker {
451 map: FxHashMap<Name, Span>,
454 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
455 // for lifetimes as parameters of generics
456 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
457 self.map.remove(&lifetime.name.ident().name);
460 fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
461 // don't actually visit `<'a>` or `<'a: 'b>`
462 // we've already visited the `'a` declarations and
463 // don't want to spuriously remove them
464 // `'b` in `'a: 'b` is useless unless used elsewhere in
465 // a non-lifetime bound
466 if let GenericParamKind::Type { .. } = param.kind {
467 walk_generic_param(self, param)
470 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
471 NestedVisitorMap::None
475 fn report_extra_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
479 .filter_map(|par| match par.kind {
480 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
484 let mut checker = LifetimeChecker { map: hs };
486 walk_generics(&mut checker, generics);
487 walk_fn_decl(&mut checker, func);
489 for &v in checker.map.values() {
492 EXTRA_UNUSED_LIFETIMES,
494 "this lifetime isn't used in the function definition",
499 struct BodyLifetimeChecker {
500 lifetimes_used_in_body: bool,
503 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
504 // for lifetimes as parameters of generics
505 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
506 if lifetime.name.ident().name != kw::Invalid && lifetime.name.ident().name != kw::StaticLifetime {
507 self.lifetimes_used_in_body = true;
511 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
512 NestedVisitorMap::None