1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::{in_macro, 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! {
21 /// **What it does:** Checks for lifetime annotations which can be removed by
22 /// relying on lifetime elision.
24 /// **Why is this bad?** The additional lifetimes make the code look more
25 /// complicated, while there is nothing out of the ordinary going on. Removing
26 /// them leads to more readable code.
28 /// **Known problems:**
29 /// - We bail out if the function has a `where` clause where lifetimes
30 /// are mentioned due to potenial false positives.
31 /// - Lifetime bounds such as `impl Foo + 'a` and `T: 'a` must be elided with the
32 /// placeholder notation `'_` because the fully elided notation leaves the type bound to `'static`.
36 /// // Bad: unnecessary lifetime annotations
37 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
42 /// fn elided(x: &u8, y: u8) -> &u8 {
46 pub NEEDLESS_LIFETIMES,
48 "using explicit lifetimes for references in function arguments when elision rules \
49 would allow omitting them"
52 declare_clippy_lint! {
53 /// **What it does:** Checks for lifetimes in generics that are never used
56 /// **Why is this bad?** The additional lifetimes make the code look more
57 /// complicated, while there is nothing out of the ordinary going on. Removing
58 /// them leads to more readable code.
60 /// **Known problems:** None.
64 /// // Bad: unnecessary lifetimes
65 /// fn unused_lifetime<'a>(x: u8) {
70 /// fn no_lifetime(x: u8) {
74 pub EXTRA_UNUSED_LIFETIMES,
76 "unused lifetimes in function definitions"
79 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
81 impl<'tcx> LateLintPass<'tcx> for Lifetimes {
82 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
83 if let ItemKind::Fn(ref sig, ref generics, id) = item.kind {
84 check_fn_inner(cx, sig.decl, Some(id), generics, item.span, true);
88 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
89 if let ImplItemKind::Fn(ref sig, id) = item.kind {
90 let report_extra_lifetimes = trait_ref_of_method(cx, item.hir_id()).is_none();
97 report_extra_lifetimes,
102 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
103 if let TraitItemKind::Fn(ref sig, ref body) = item.kind {
104 let body = match *body {
105 TraitFn::Required(_) => None,
106 TraitFn::Provided(id) => Some(id),
108 check_fn_inner(cx, sig.decl, body, &item.generics, item.span, true);
113 /// The lifetime of a &-reference.
114 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
121 fn check_fn_inner<'tcx>(
122 cx: &LateContext<'tcx>,
123 decl: &'tcx FnDecl<'_>,
124 body: Option<BodyId>,
125 generics: &'tcx Generics<'_>,
127 report_extra_lifetimes: bool,
129 if in_macro(span) || has_where_lifetimes(cx, &generics.where_clause) {
136 .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
138 for bound in typ.bounds {
139 let mut visitor = RefVisitor::new(cx);
140 walk_param_bound(&mut visitor, bound);
141 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
144 if let GenericBound::Trait(ref trait_ref, _) = *bound {
145 let params = &trait_ref
150 .expect("a path must have at least one segment")
152 if let Some(params) = *params {
153 let lifetimes = params.args.iter().filter_map(|arg| match arg {
154 GenericArg::Lifetime(lt) => Some(lt),
157 for bound in lifetimes {
158 if bound.name != LifetimeName::Static && !bound.is_elided() {
166 if could_use_elision(cx, decl, body, generics.params) {
170 span.with_hi(decl.output.span().hi()),
171 "explicit lifetimes given in parameter types where they could be elided \
172 (or replaced with `'_` if needed by type declaration)",
175 if report_extra_lifetimes {
176 self::report_extra_lifetimes(cx, decl, generics);
180 fn could_use_elision<'tcx>(
181 cx: &LateContext<'tcx>,
182 func: &'tcx FnDecl<'_>,
183 body: Option<BodyId>,
184 named_generics: &'tcx [GenericParam<'_>],
186 // There are two scenarios where elision works:
187 // * no output references, all input references have different LT
188 // * output references, exactly one input reference with same LT
189 // All lifetimes must be unnamed, 'static or defined without bounds on the
190 // level of the current item.
193 let allowed_lts = allowed_lts_from(named_generics);
195 // these will collect all the lifetimes for references in arg/return types
196 let mut input_visitor = RefVisitor::new(cx);
197 let mut output_visitor = RefVisitor::new(cx);
199 // extract lifetimes in input argument types
200 for arg in func.inputs {
201 input_visitor.visit_ty(arg);
203 // extract lifetimes in output type
204 if let Return(ty) = func.output {
205 output_visitor.visit_ty(ty);
207 for lt in named_generics {
208 input_visitor.visit_generic_param(lt);
211 if input_visitor.abort() || output_visitor.abort() {
218 .nested_elision_site_lts
220 .chain(output_visitor.nested_elision_site_lts.iter())
222 .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: [LangItem; 3] = [LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
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.iter().any(|&item| {
367 .map_or(false, |id| Some(id) == trait_ref.trait_def_id())
369 let mut sub_visitor = RefVisitor::new(self.cx);
370 sub_visitor.visit_trait_ref(trait_ref);
371 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
373 walk_poly_trait_ref(self, poly_tref, tbm);
377 fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
379 TyKind::OpaqueDef(item, _) => {
380 let map = self.cx.tcx.hir();
381 let item = map.item(item);
382 walk_item(self, item);
385 TyKind::BareFn(&BareFnTy { decl, .. }) => {
386 let mut sub_visitor = RefVisitor::new(self.cx);
387 sub_visitor.visit_fn_decl(decl);
388 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
391 TyKind::TraitObject(bounds, ref lt, _) => {
393 self.unelided_trait_object_lifetime = true;
395 for bound in bounds {
396 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
404 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
405 NestedVisitorMap::None
409 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
410 /// reason about elision.
411 fn has_where_lifetimes<'tcx>(cx: &LateContext<'tcx>, where_clause: &'tcx WhereClause<'_>) -> bool {
412 for predicate in where_clause.predicates {
414 WherePredicate::RegionPredicate(..) => return true,
415 WherePredicate::BoundPredicate(ref pred) => {
416 // a predicate like F: Trait or F: for<'a> Trait<'a>
417 let mut visitor = RefVisitor::new(cx);
418 // walk the type F, it may not contain LT refs
419 walk_ty(&mut visitor, pred.bounded_ty);
420 if !visitor.all_lts().is_empty() {
423 // if the bounds define new lifetimes, they are fine to occur
424 let allowed_lts = allowed_lts_from(pred.bound_generic_params);
425 // now walk the bounds
426 for bound in pred.bounds.iter() {
427 walk_param_bound(&mut visitor, bound);
429 // and check that all lifetimes are allowed
430 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
434 WherePredicate::EqPredicate(ref pred) => {
435 let mut visitor = RefVisitor::new(cx);
436 walk_ty(&mut visitor, pred.lhs_ty);
437 walk_ty(&mut visitor, pred.rhs_ty);
438 if !visitor.lts.is_empty() {
447 struct LifetimeChecker {
448 map: FxHashMap<Symbol, Span>,
451 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
452 type Map = Map<'tcx>;
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(&mut self) -> NestedVisitorMap<Self::Map> {
470 NestedVisitorMap::None
474 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'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 type Map = Map<'tcx>;
505 // for lifetimes as parameters of generics
506 fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
507 if lifetime.name.ident().name != kw::Empty && lifetime.name.ident().name != kw::StaticLifetime {
508 self.lifetimes_used_in_body = true;
512 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
513 NestedVisitorMap::None