1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::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, LangItem, Lifetime, LifetimeName, ParamName, PolyTraitRef, TraitBoundModifier,
12 TraitFn, 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};
20 declare_clippy_lint! {
22 /// Checks for lifetime annotations which can be removed by
23 /// relying on lifetime elision.
25 /// ### Why is this bad?
26 /// The additional lifetimes make the code look more
27 /// complicated, while there is nothing out of the ordinary going on. Removing
28 /// them leads to more readable code.
30 /// ### Known problems
31 /// - We bail out if the function has a `where` clause where lifetimes
32 /// are mentioned due to potenial false positives.
33 /// - Lifetime bounds such as `impl Foo + 'a` and `T: 'a` must be elided with the
34 /// placeholder notation `'_` because the fully elided notation leaves the type bound to `'static`.
38 /// // Bad: unnecessary lifetime annotations
39 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
44 /// fn elided(x: &u8, y: u8) -> &u8 {
48 #[clippy::version = "pre 1.29.0"]
49 pub NEEDLESS_LIFETIMES,
51 "using explicit lifetimes for references in function arguments when elision rules \
52 would allow omitting them"
55 declare_clippy_lint! {
57 /// Checks for lifetimes in generics that are never used
60 /// ### Why is this bad?
61 /// The additional lifetimes make the code look more
62 /// complicated, while there is nothing out of the ordinary going on. Removing
63 /// them leads to more readable code.
67 /// // Bad: unnecessary lifetimes
68 /// fn unused_lifetime<'a>(x: u8) {
73 /// fn no_lifetime(x: u8) {
77 #[clippy::version = "pre 1.29.0"]
78 pub EXTRA_UNUSED_LIFETIMES,
80 "unused lifetimes in function definitions"
83 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
85 impl<'tcx> LateLintPass<'tcx> for Lifetimes {
86 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
87 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
88 check_fn_inner(cx, sig.decl, Some(id), generics, item.span, true);
92 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
93 if let ImplItemKind::Fn(ref sig, id) = item.kind {
94 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id()).is_none();
101 report_extra_lifetimes,
106 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
107 if let TraitItemKind::Fn(ref sig, ref body) = item.kind {
108 let body = match *body {
109 TraitFn::Required(_) => None,
110 TraitFn::Provided(id) => Some(id),
112 check_fn_inner(cx, sig.decl, body, &item.generics, item.span, true);
117 /// The lifetime of a &-reference.
118 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
125 fn check_fn_inner<'tcx>(
126 cx: &LateContext<'tcx>,
127 decl: &'tcx FnDecl<'_>,
128 body: Option<BodyId>,
129 generics: &'tcx Generics<'_>,
131 report_extra_lifetimes: bool,
133 if span.from_expansion() || has_where_lifetimes(cx, &generics.where_clause) {
140 .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
142 for bound in typ.bounds {
143 let mut visitor = RefVisitor::new(cx);
144 walk_param_bound(&mut visitor, bound);
145 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
148 if let GenericBound::Trait(ref trait_ref, _) = *bound {
149 let params = &trait_ref
154 .expect("a path must have at least one segment")
156 if let Some(params) = *params {
157 let lifetimes = params.args.iter().filter_map(|arg| match arg {
158 GenericArg::Lifetime(lt) => Some(lt),
161 for bound in lifetimes {
162 if bound.name != LifetimeName::Static && !bound.is_elided() {
170 if could_use_elision(cx, decl, body, generics.params) {
174 span.with_hi(decl.output.span().hi()),
175 "explicit lifetimes given in parameter types where they could be elided \
176 (or replaced with `'_` if needed by type declaration)",
179 if report_extra_lifetimes {
180 self::report_extra_lifetimes(cx, decl, generics);
184 fn could_use_elision<'tcx>(
185 cx: &LateContext<'tcx>,
186 func: &'tcx FnDecl<'_>,
187 body: Option<BodyId>,
188 named_generics: &'tcx [GenericParam<'_>],
190 // There are two scenarios where elision works:
191 // * no output references, all input references have different LT
192 // * output references, exactly one input reference with same LT
193 // All lifetimes must be unnamed, 'static or defined without bounds on the
194 // level of the current item.
197 let allowed_lts = allowed_lts_from(named_generics);
199 // these will collect all the lifetimes for references in arg/return types
200 let mut input_visitor = RefVisitor::new(cx);
201 let mut output_visitor = RefVisitor::new(cx);
203 // extract lifetimes in input argument types
204 for arg in func.inputs {
205 input_visitor.visit_ty(arg);
207 // extract lifetimes in output type
208 if let Return(ty) = func.output {
209 output_visitor.visit_ty(ty);
211 for lt in named_generics {
212 input_visitor.visit_generic_param(lt);
215 if input_visitor.abort() || output_visitor.abort() {
222 .nested_elision_site_lts
224 .chain(output_visitor.nested_elision_site_lts.iter())
226 .filter(|v| matches!(v, RefLt::Named(_)))
235 let input_lts = input_visitor.lts;
236 let output_lts = output_visitor.lts;
238 if let Some(body_id) = body {
239 let mut checker = BodyLifetimeChecker {
240 lifetimes_used_in_body: false,
242 checker.visit_expr(&cx.tcx.hir().body(body_id).value);
243 if checker.lifetimes_used_in_body {
248 // check for lifetimes from higher scopes
249 for lt in input_lts.iter().chain(output_lts.iter()) {
250 if !allowed_lts.contains(lt) {
255 // no input lifetimes? easy case!
256 if input_lts.is_empty() {
258 } else if output_lts.is_empty() {
259 // no output lifetimes, check distinctness of input lifetimes
261 // only unnamed and static, ok
262 let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
263 if unnamed_and_static {
266 // we have no output reference, so we only need all distinct lifetimes
267 input_lts.len() == unique_lifetimes(&input_lts)
269 // we have output references, so we need one input reference,
270 // and all output lifetimes must be the same
271 if unique_lifetimes(&output_lts) > 1 {
274 if input_lts.len() == 1 {
275 match (&input_lts[0], &output_lts[0]) {
276 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
277 (&RefLt::Named(_), &RefLt::Unnamed) => true,
278 _ => false, /* already elided, different named lifetimes
279 * or something static going on */
287 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
288 let mut allowed_lts = FxHashSet::default();
289 for par in named_generics.iter() {
290 if let GenericParamKind::Lifetime { .. } = par.kind {
291 if par.bounds.is_empty() {
292 allowed_lts.insert(RefLt::Named(par.name.ident().name));
296 allowed_lts.insert(RefLt::Unnamed);
297 allowed_lts.insert(RefLt::Static);
301 /// Number of unique lifetimes in the given vector.
303 fn unique_lifetimes(lts: &[RefLt]) -> usize {
304 lts.iter().collect::<FxHashSet<_>>().len()
307 const CLOSURE_TRAIT_BOUNDS: [LangItem; 3] = [LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
309 /// A visitor usable for `rustc_front::visit::walk_ty()`.
310 struct RefVisitor<'a, 'tcx> {
311 cx: &'a LateContext<'tcx>,
313 nested_elision_site_lts: Vec<RefLt>,
314 unelided_trait_object_lifetime: bool,
317 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
318 fn new(cx: &'a LateContext<'tcx>) -> Self {
322 nested_elision_site_lts: Vec::new(),
323 unelided_trait_object_lifetime: false,
327 fn record(&mut self, lifetime: &Option<Lifetime>) {
328 if let Some(ref lt) = *lifetime {
329 if lt.name == LifetimeName::Static {
330 self.lts.push(RefLt::Static);
331 } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
332 // Fresh lifetimes generated should be ignored.
333 } else if lt.is_elided() {
334 self.lts.push(RefLt::Unnamed);
336 self.lts.push(RefLt::Named(lt.name.ident().name));
339 self.lts.push(RefLt::Unnamed);
343 fn all_lts(&self) -> Vec<RefLt> {
346 .chain(self.nested_elision_site_lts.iter())
351 fn abort(&self) -> bool {
352 self.unelided_trait_object_lifetime
356 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
357 type Map = Map<'tcx>;
359 // for lifetimes as parameters of generics
360 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
361 self.record(&Some(*lifetime));
364 fn visit_poly_trait_ref(&mut self, poly_tref: &'tcx PolyTraitRef<'tcx>, tbm: TraitBoundModifier) {
365 let trait_ref = &poly_tref.trait_ref;
366 if CLOSURE_TRAIT_BOUNDS.iter().any(|&item| {
371 .map_or(false, |id| Some(id) == trait_ref.trait_def_id())
373 let mut sub_visitor = RefVisitor::new(self.cx);
374 sub_visitor.visit_trait_ref(trait_ref);
375 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
377 walk_poly_trait_ref(self, poly_tref, tbm);
381 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
383 TyKind::OpaqueDef(item, bounds) => {
384 let map = self.cx.tcx.hir();
385 let item = map.item(item);
386 walk_item(self, item);
388 self.lts.extend(bounds.iter().filter_map(|bound| match bound {
389 GenericArg::Lifetime(l) => Some(RefLt::Named(l.name.ident().name)),
393 TyKind::BareFn(&BareFnTy { decl, .. }) => {
394 let mut sub_visitor = RefVisitor::new(self.cx);
395 sub_visitor.visit_fn_decl(decl);
396 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
399 TyKind::TraitObject(bounds, ref lt, _) => {
401 self.unelided_trait_object_lifetime = true;
403 for bound in bounds {
404 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
412 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
413 NestedVisitorMap::None
417 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
418 /// reason about elision.
419 fn has_where_lifetimes<'tcx>(cx: &LateContext<'tcx>, where_clause: &'tcx WhereClause<'_>) -> bool {
420 for predicate in where_clause.predicates {
422 WherePredicate::RegionPredicate(..) => return true,
423 WherePredicate::BoundPredicate(ref pred) => {
424 // a predicate like F: Trait or F: for<'a> Trait<'a>
425 let mut visitor = RefVisitor::new(cx);
426 // walk the type F, it may not contain LT refs
427 walk_ty(&mut visitor, pred.bounded_ty);
428 if !visitor.all_lts().is_empty() {
431 // if the bounds define new lifetimes, they are fine to occur
432 let allowed_lts = allowed_lts_from(pred.bound_generic_params);
433 // now walk the bounds
434 for bound in pred.bounds.iter() {
435 walk_param_bound(&mut visitor, bound);
437 // and check that all lifetimes are allowed
438 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
442 WherePredicate::EqPredicate(ref pred) => {
443 let mut visitor = RefVisitor::new(cx);
444 walk_ty(&mut visitor, pred.lhs_ty);
445 walk_ty(&mut visitor, pred.rhs_ty);
446 if !visitor.lts.is_empty() {
455 struct LifetimeChecker {
456 map: FxHashMap<Symbol, Span>,
459 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
460 type Map = Map<'tcx>;
462 // for lifetimes as parameters of generics
463 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
464 self.map.remove(&lifetime.name.ident().name);
467 fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
468 // don't actually visit `<'a>` or `<'a: 'b>`
469 // we've already visited the `'a` declarations and
470 // don't want to spuriously remove them
471 // `'b` in `'a: 'b` is useless unless used elsewhere in
472 // a non-lifetime bound
473 if let GenericParamKind::Type { .. } = param.kind {
474 walk_generic_param(self, param);
477 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
478 NestedVisitorMap::None
482 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
486 .filter_map(|par| match par.kind {
487 GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
491 let mut checker = LifetimeChecker { map: hs };
493 walk_generics(&mut checker, generics);
494 walk_fn_decl(&mut checker, func);
496 for &v in checker.map.values() {
499 EXTRA_UNUSED_LIFETIMES,
501 "this lifetime isn't used in the function definition",
506 struct BodyLifetimeChecker {
507 lifetimes_used_in_body: bool,
510 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
511 type Map = Map<'tcx>;
513 // for lifetimes as parameters of generics
514 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
515 if lifetime.name.ident().name != kw::Empty && lifetime.name.ident().name != kw::StaticLifetime {
516 self.lifetimes_used_in_body = true;
520 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
521 NestedVisitorMap::None