1 use crate::utils::paths;
2 use crate::utils::{get_trait_def_id, in_macro, span_lint, trait_ref_of_method};
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_hir::intravisit::{
5 walk_fn_decl, walk_generic_param, walk_generics, walk_item, walk_param_bound, walk_poly_trait_ref, walk_ty,
6 NestedVisitorMap, Visitor,
8 use rustc_hir::FnRetTy::Return;
10 BareFnTy, BodyId, FnDecl, GenericArg, GenericBound, GenericParam, GenericParamKind, Generics, ImplItem,
11 ImplItemKind, Item, ItemKind, Lifetime, LifetimeName, ParamName, PolyTraitRef, TraitBoundModifier, TraitFn,
12 TraitItem, TraitItemKind, Ty, TyKind, WhereClause, WherePredicate,
14 use rustc_lint::{LateContext, LateLintPass};
15 use rustc_middle::hir::map::Map;
16 use rustc_session::{declare_lint_pass, declare_tool_lint};
17 use rustc_span::source_map::Span;
18 use rustc_span::symbol::{kw, Symbol};
19 use std::iter::FromIterator;
21 declare_clippy_lint! {
22 /// **What it does:** Checks for lifetime annotations which can be removed by
23 /// relying on lifetime elision.
25 /// **Why is this bad?** The additional lifetimes make the code look more
26 /// complicated, while there is nothing out of the ordinary going on. Removing
27 /// them leads to more readable code.
29 /// **Known problems:**
30 /// - We bail out if the function has a `where` clause where lifetimes
31 /// are mentioned due to potenial false positives.
32 /// - Lifetime bounds such as `impl Foo + 'a` and `T: 'a` must be elided with the
33 /// placeholder notation `'_` because the fully elided notation leaves the type bound to `'static`.
37 /// // Bad: unnecessary lifetime annotations
38 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
43 /// fn elided(x: &u8, y: u8) -> &u8 {
47 pub NEEDLESS_LIFETIMES,
49 "using explicit lifetimes for references in function arguments when elision rules \
50 would allow omitting them"
53 declare_clippy_lint! {
54 /// **What it does:** Checks for lifetimes in generics that are never used
57 /// **Why is this bad?** The additional lifetimes make the code look more
58 /// complicated, while there is nothing out of the ordinary going on. Removing
59 /// them leads to more readable code.
61 /// **Known problems:** None.
65 /// // Bad: unnecessary lifetimes
66 /// fn unused_lifetime<'a>(x: u8) {
71 /// fn no_lifetime(x: u8) {
75 pub EXTRA_UNUSED_LIFETIMES,
77 "unused lifetimes in function definitions"
80 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
82 impl<'tcx> LateLintPass<'tcx> for Lifetimes {
83 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
84 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
85 check_fn_inner(cx, &sig.decl, Some(id), generics, item.span, true);
89 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
90 if let ImplItemKind::Fn(ref sig, id) = item.kind {
91 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id).is_none();
98 report_extra_lifetimes,
103 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
104 if let TraitItemKind::Fn(ref sig, ref body) = item.kind {
105 let body = match *body {
106 TraitFn::Required(_) => None,
107 TraitFn::Provided(id) => Some(id),
109 check_fn_inner(cx, &sig.decl, body, &item.generics, item.span, true);
114 /// The lifetime of a &-reference.
115 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
122 fn check_fn_inner<'tcx>(
123 cx: &LateContext<'tcx>,
124 decl: &'tcx FnDecl<'_>,
125 body: Option<BodyId>,
126 generics: &'tcx Generics<'_>,
128 report_extra_lifetimes: bool,
130 if in_macro(span) || has_where_lifetimes(cx, &generics.where_clause) {
137 .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
139 for bound in typ.bounds {
140 let mut visitor = RefVisitor::new(cx);
141 walk_param_bound(&mut visitor, bound);
142 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
145 if let GenericBound::Trait(ref trait_ref, _) = *bound {
146 let params = &trait_ref
151 .expect("a path must have at least one segment")
153 if let Some(ref params) = *params {
154 let lifetimes = params.args.iter().filter_map(|arg| match arg {
155 GenericArg::Lifetime(lt) => Some(lt),
158 for bound in lifetimes {
159 if bound.name != LifetimeName::Static && !bound.is_elided() {
167 if could_use_elision(cx, decl, body, &generics.params) {
171 span.with_hi(decl.output.span().hi()),
172 "explicit lifetimes given in parameter types where they could be elided \
173 (or replaced with `'_` if needed by type declaration)",
176 if report_extra_lifetimes {
177 self::report_extra_lifetimes(cx, decl, generics);
181 fn could_use_elision<'tcx>(
182 cx: &LateContext<'tcx>,
183 func: &'tcx FnDecl<'_>,
184 body: Option<BodyId>,
185 named_generics: &'tcx [GenericParam<'_>],
187 // There are two scenarios where elision works:
188 // * no output references, all input references have different LT
189 // * output references, exactly one input reference with same LT
190 // All lifetimes must be unnamed, 'static or defined without bounds on the
191 // level of the current item.
194 let allowed_lts = allowed_lts_from(named_generics);
196 // these will collect all the lifetimes for references in arg/return types
197 let mut input_visitor = RefVisitor::new(cx);
198 let mut output_visitor = RefVisitor::new(cx);
200 // extract lifetimes in input argument types
201 for arg in func.inputs {
202 input_visitor.visit_ty(arg);
204 // extract lifetimes in output type
205 if let Return(ref ty) = func.output {
206 output_visitor.visit_ty(ty);
208 for lt in named_generics {
209 input_visitor.visit_generic_param(lt)
212 if input_visitor.abort() || output_visitor.abort() {
217 .intersection(&FxHashSet::from_iter(
219 .nested_elision_site_lts
221 .chain(output_visitor.nested_elision_site_lts.iter())
223 .filter(|v| matches!(v, RefLt::Named(_))),
231 let input_lts = input_visitor.lts;
232 let output_lts = output_visitor.lts;
234 if let Some(body_id) = body {
235 let mut checker = BodyLifetimeChecker {
236 lifetimes_used_in_body: false,
238 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
239 if checker.lifetimes_used_in_body {
244 // check for lifetimes from higher scopes
245 for lt in input_lts.iter().chain(output_lts.iter()) {
246 if !allowed_lts.contains(lt) {
251 // no input lifetimes? easy case!
252 if input_lts.is_empty() {
254 } else if output_lts.is_empty() {
255 // no output lifetimes, check distinctness of input lifetimes
257 // only unnamed and static, ok
258 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
259 if unnamed_and_static {
262 // we have no output reference, so we only need all distinct lifetimes
263 input_lts.len() == unique_lifetimes(&input_lts)
265 // we have output references, so we need one input reference,
266 // and all output lifetimes must be the same
267 if unique_lifetimes(&output_lts) > 1 {
270 if input_lts.len() == 1 {
271 match (&input_lts[0], &output_lts[0]) {
272 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
273 (&RefLt::Named(_), &RefLt::Unnamed) => true,
274 _ => false, /* already elided, different named lifetimes
275 * or something static going on */
283 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
284 let mut allowed_lts = FxHashSet::default();
285 for par in named_generics.iter() {
286 if let GenericParamKind::Lifetime { .. } = par.kind {
287 if par.bounds.is_empty() {
288 allowed_lts.insert(RefLt::Named(par.name.ident().name));
292 allowed_lts.insert(RefLt::Unnamed);
293 allowed_lts.insert(RefLt::Static);
297 /// Number of unique lifetimes in the given vector.
299 fn unique_lifetimes(lts: &[RefLt]) -> usize {
300 lts.iter().collect::<FxHashSet<_>>().len()
303 const CLOSURE_TRAIT_BOUNDS: [&[&str]; 3] = [&paths::FN, &paths::FN_MUT, &paths::FN_ONCE];
305 /// A visitor usable for `rustc_front::visit::walk_ty()`.
306 struct RefVisitor<'a, 'tcx> {
307 cx: &'a LateContext<'tcx>,
309 nested_elision_site_lts: Vec<RefLt>,
310 unelided_trait_object_lifetime: bool,
313 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
314 fn new(cx: &'a LateContext<'tcx>) -> Self {
318 nested_elision_site_lts: Vec::new(),
319 unelided_trait_object_lifetime: false,
323 fn record(&mut self, lifetime: &Option<Lifetime>) {
324 if let Some(ref lt) = *lifetime {
325 if lt.name == LifetimeName::Static {
326 self.lts.push(RefLt::Static);
327 } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
328 // Fresh lifetimes generated should be ignored.
329 } else if lt.is_elided() {
330 self.lts.push(RefLt::Unnamed);
332 self.lts.push(RefLt::Named(lt.name.ident().name));
335 self.lts.push(RefLt::Unnamed);
339 fn all_lts(&self) -> Vec<RefLt> {
342 .chain(self.nested_elision_site_lts.iter())
347 fn abort(&self) -> bool {
348 self.unelided_trait_object_lifetime
352 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
353 type Map = Map<'tcx>;
355 // for lifetimes as parameters of generics
356 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
357 self.record(&Some(*lifetime));
360 fn visit_poly_trait_ref(&mut self, poly_tref: &'tcx PolyTraitRef<'tcx>, tbm: TraitBoundModifier) {
361 let trait_ref = &poly_tref.trait_ref;
362 if CLOSURE_TRAIT_BOUNDS
364 .any(|trait_path| trait_ref.trait_def_id() == get_trait_def_id(self.cx, trait_path))
366 let mut sub_visitor = RefVisitor::new(self.cx);
367 sub_visitor.visit_trait_ref(trait_ref);
368 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
370 walk_poly_trait_ref(self, poly_tref, tbm);
374 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
376 TyKind::OpaqueDef(item, _) => {
377 let map = self.cx.tcx.hir();
378 let item = map.expect_item(item.id);
379 walk_item(self, item);
382 TyKind::BareFn(&BareFnTy { decl, .. }) => {
383 let mut sub_visitor = RefVisitor::new(self.cx);
384 sub_visitor.visit_fn_decl(decl);
385 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
388 TyKind::TraitObject(bounds, ref lt) => {
390 self.unelided_trait_object_lifetime = true;
392 for bound in bounds {
393 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
401 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
402 NestedVisitorMap::None
406 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
407 /// reason about elision.
408 fn has_where_lifetimes<'tcx>(cx: &LateContext<'tcx>, where_clause: &'tcx WhereClause<'_>) -> bool {
409 for predicate in where_clause.predicates {
411 WherePredicate::RegionPredicate(..) => return true,
412 WherePredicate::BoundPredicate(ref pred) => {
413 // a predicate like F: Trait or F: for<'a> Trait<'a>
414 let mut visitor = RefVisitor::new(cx);
415 // walk the type F, it may not contain LT refs
416 walk_ty(&mut visitor, &pred.bounded_ty);
417 if !visitor.lts.is_empty() {
420 // if the bounds define new lifetimes, they are fine to occur
421 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
422 // now walk the bounds
423 for bound in pred.bounds.iter() {
424 walk_param_bound(&mut visitor, bound);
426 // and check that all lifetimes are allowed
427 return visitor.all_lts().iter().any(|it| !allowed_lts.contains(it));
429 WherePredicate::EqPredicate(ref pred) => {
430 let mut visitor = RefVisitor::new(cx);
431 walk_ty(&mut visitor, &pred.lhs_ty);
432 walk_ty(&mut visitor, &pred.rhs_ty);
433 if !visitor.lts.is_empty() {
442 struct LifetimeChecker {
443 map: FxHashMap<Symbol, Span>,
446 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
447 type Map = Map<'tcx>;
449 // for lifetimes as parameters of generics
450 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
451 self.map.remove(&lifetime.name.ident().name);
454 fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
455 // don't actually visit `<'a>` or `<'a: 'b>`
456 // we've already visited the `'a` declarations and
457 // don't want to spuriously remove them
458 // `'b` in `'a: 'b` is useless unless used elsewhere in
459 // a non-lifetime bound
460 if let GenericParamKind::Type { .. } = param.kind {
461 walk_generic_param(self, param)
464 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
465 NestedVisitorMap::None
469 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
473 .filter_map(|par| match par.kind {
474 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
478 let mut checker = LifetimeChecker { map: hs };
480 walk_generics(&mut checker, generics);
481 walk_fn_decl(&mut checker, func);
483 for &v in checker.map.values() {
486 EXTRA_UNUSED_LIFETIMES,
488 "this lifetime isn't used in the function definition",
493 struct BodyLifetimeChecker {
494 lifetimes_used_in_body: bool,
497 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
498 type Map = Map<'tcx>;
500 // for lifetimes as parameters of generics
501 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
502 if lifetime.name.ident().name != kw::Invalid && lifetime.name.ident().name != kw::StaticLifetime {
503 self.lifetimes_used_in_body = true;
507 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
508 NestedVisitorMap::None