]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
Auto merge of #8030 - WaffleLapkin:ignore_trait_assoc_types_type_complexity, r=llogiq
[rust.git] / clippy_lints / src / lifetimes.rs
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,
7 };
8 use rustc_hir::FnRetTy::Return;
9 use rustc_hir::{
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,
13 };
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
20 declare_clippy_lint! {
21     /// ### What it does
22     /// Checks for lifetime annotations which can be removed by
23     /// relying on lifetime elision.
24     ///
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.
29     ///
30     /// ### Known problems
31     /// - We bail out if the function has a `where` clause where lifetimes
32     /// are mentioned due to potential 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`.
35     ///
36     /// ### Example
37     /// ```rust
38     /// // Bad: unnecessary lifetime annotations
39     /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
40     ///     x
41     /// }
42     ///
43     /// // Good
44     /// fn elided(x: &u8, y: u8) -> &u8 {
45     ///     x
46     /// }
47     /// ```
48     #[clippy::version = "pre 1.29.0"]
49     pub NEEDLESS_LIFETIMES,
50     complexity,
51     "using explicit lifetimes for references in function arguments when elision rules \
52      would allow omitting them"
53 }
54
55 declare_clippy_lint! {
56     /// ### What it does
57     /// Checks for lifetimes in generics that are never used
58     /// anywhere else.
59     ///
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.
64     ///
65     /// ### Example
66     /// ```rust
67     /// // Bad: unnecessary lifetimes
68     /// fn unused_lifetime<'a>(x: u8) {
69     ///     // ..
70     /// }
71     ///
72     /// // Good
73     /// fn no_lifetime(x: u8) {
74     ///     // ...
75     /// }
76     /// ```
77     #[clippy::version = "pre 1.29.0"]
78     pub EXTRA_UNUSED_LIFETIMES,
79     complexity,
80     "unused lifetimes in function definitions"
81 }
82
83 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
84
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);
89         }
90     }
91
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();
95             check_fn_inner(
96                 cx,
97                 sig.decl,
98                 Some(id),
99                 &item.generics,
100                 item.span,
101                 report_extra_lifetimes,
102             );
103         }
104     }
105
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),
111             };
112             check_fn_inner(cx, sig.decl, body, &item.generics, item.span, true);
113         }
114     }
115 }
116
117 /// The lifetime of a &-reference.
118 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
119 enum RefLt {
120     Unnamed,
121     Static,
122     Named(Symbol),
123 }
124
125 fn check_fn_inner<'tcx>(
126     cx: &LateContext<'tcx>,
127     decl: &'tcx FnDecl<'_>,
128     body: Option<BodyId>,
129     generics: &'tcx Generics<'_>,
130     span: Span,
131     report_extra_lifetimes: bool,
132 ) {
133     if span.from_expansion() || has_where_lifetimes(cx, &generics.where_clause) {
134         return;
135     }
136
137     let types = generics
138         .params
139         .iter()
140         .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
141     for typ in types {
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(_))) {
146                 return;
147             }
148             if let GenericBound::Trait(ref trait_ref, _) = *bound {
149                 let params = &trait_ref
150                     .trait_ref
151                     .path
152                     .segments
153                     .last()
154                     .expect("a path must have at least one segment")
155                     .args;
156                 if let Some(params) = *params {
157                     let lifetimes = params.args.iter().filter_map(|arg| match arg {
158                         GenericArg::Lifetime(lt) => Some(lt),
159                         _ => None,
160                     });
161                     for bound in lifetimes {
162                         if bound.name != LifetimeName::Static && !bound.is_elided() {
163                             return;
164                         }
165                     }
166                 }
167             }
168         }
169     }
170     if could_use_elision(cx, decl, body, generics.params) {
171         span_lint(
172             cx,
173             NEEDLESS_LIFETIMES,
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)",
177         );
178     }
179     if report_extra_lifetimes {
180         self::report_extra_lifetimes(cx, decl, generics);
181     }
182 }
183
184 fn could_use_elision<'tcx>(
185     cx: &LateContext<'tcx>,
186     func: &'tcx FnDecl<'_>,
187     body: Option<BodyId>,
188     named_generics: &'tcx [GenericParam<'_>],
189 ) -> bool {
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.
195
196     // check named LTs
197     let allowed_lts = allowed_lts_from(named_generics);
198
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);
202
203     // extract lifetimes in input argument types
204     for arg in func.inputs {
205         input_visitor.visit_ty(arg);
206     }
207     // extract lifetimes in output type
208     if let Return(ty) = func.output {
209         output_visitor.visit_ty(ty);
210     }
211     for lt in named_generics {
212         input_visitor.visit_generic_param(lt);
213     }
214
215     if input_visitor.abort() || output_visitor.abort() {
216         return false;
217     }
218
219     if allowed_lts
220         .intersection(
221             &input_visitor
222                 .nested_elision_site_lts
223                 .iter()
224                 .chain(output_visitor.nested_elision_site_lts.iter())
225                 .cloned()
226                 .filter(|v| matches!(v, RefLt::Named(_)))
227                 .collect(),
228         )
229         .next()
230         .is_some()
231     {
232         return false;
233     }
234
235     let input_lts = input_visitor.lts;
236     let output_lts = output_visitor.lts;
237
238     if let Some(body_id) = body {
239         let mut checker = BodyLifetimeChecker {
240             lifetimes_used_in_body: false,
241         };
242         checker.visit_expr(&cx.tcx.hir().body(body_id).value);
243         if checker.lifetimes_used_in_body {
244             return false;
245         }
246     }
247
248     // check for lifetimes from higher scopes
249     for lt in input_lts.iter().chain(output_lts.iter()) {
250         if !allowed_lts.contains(lt) {
251             return false;
252         }
253     }
254
255     // no input lifetimes? easy case!
256     if input_lts.is_empty() {
257         false
258     } else if output_lts.is_empty() {
259         // no output lifetimes, check distinctness of input lifetimes
260
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 {
264             return false;
265         }
266         // we have no output reference, so we only need all distinct lifetimes
267         input_lts.len() == unique_lifetimes(&input_lts)
268     } else {
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 {
272             return false;
273         }
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 */
280             }
281         } else {
282             false
283         }
284     }
285 }
286
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));
293             }
294         }
295     }
296     allowed_lts.insert(RefLt::Unnamed);
297     allowed_lts.insert(RefLt::Static);
298     allowed_lts
299 }
300
301 /// Number of unique lifetimes in the given vector.
302 #[must_use]
303 fn unique_lifetimes(lts: &[RefLt]) -> usize {
304     lts.iter().collect::<FxHashSet<_>>().len()
305 }
306
307 const CLOSURE_TRAIT_BOUNDS: [LangItem; 3] = [LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
308
309 /// A visitor usable for `rustc_front::visit::walk_ty()`.
310 struct RefVisitor<'a, 'tcx> {
311     cx: &'a LateContext<'tcx>,
312     lts: Vec<RefLt>,
313     nested_elision_site_lts: Vec<RefLt>,
314     unelided_trait_object_lifetime: bool,
315 }
316
317 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
318     fn new(cx: &'a LateContext<'tcx>) -> Self {
319         Self {
320             cx,
321             lts: Vec::new(),
322             nested_elision_site_lts: Vec::new(),
323             unelided_trait_object_lifetime: false,
324         }
325     }
326
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);
335             } else {
336                 self.lts.push(RefLt::Named(lt.name.ident().name));
337             }
338         } else {
339             self.lts.push(RefLt::Unnamed);
340         }
341     }
342
343     fn all_lts(&self) -> Vec<RefLt> {
344         self.lts
345             .iter()
346             .chain(self.nested_elision_site_lts.iter())
347             .cloned()
348             .collect::<Vec<_>>()
349     }
350
351     fn abort(&self) -> bool {
352         self.unelided_trait_object_lifetime
353     }
354 }
355
356 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
357     type Map = Map<'tcx>;
358
359     // for lifetimes as parameters of generics
360     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
361         self.record(&Some(*lifetime));
362     }
363
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| {
367             self.cx
368                 .tcx
369                 .lang_items()
370                 .require(item)
371                 .map_or(false, |id| Some(id) == trait_ref.trait_def_id())
372         }) {
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());
376         } else {
377             walk_poly_trait_ref(self, poly_tref, tbm);
378         }
379     }
380
381     fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
382         match ty.kind {
383             TyKind::OpaqueDef(item, bounds) => {
384                 let map = self.cx.tcx.hir();
385                 let item = map.item(item);
386                 walk_item(self, item);
387                 walk_ty(self, ty);
388                 self.lts.extend(bounds.iter().filter_map(|bound| match bound {
389                     GenericArg::Lifetime(l) => Some(RefLt::Named(l.name.ident().name)),
390                     _ => None,
391                 }));
392             },
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());
397                 return;
398             },
399             TyKind::TraitObject(bounds, ref lt, _) => {
400                 if !lt.is_elided() {
401                     self.unelided_trait_object_lifetime = true;
402                 }
403                 for bound in bounds {
404                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
405                 }
406                 return;
407             },
408             _ => (),
409         }
410         walk_ty(self, ty);
411     }
412     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
413         NestedVisitorMap::None
414     }
415 }
416
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 {
421         match *predicate {
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() {
429                     return true;
430                 }
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);
436                 }
437                 // and check that all lifetimes are allowed
438                 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
439                     return true;
440                 }
441             },
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() {
447                     return true;
448                 }
449             },
450         }
451     }
452     false
453 }
454
455 struct LifetimeChecker {
456     map: FxHashMap<Symbol, Span>,
457 }
458
459 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
460     type Map = Map<'tcx>;
461
462     // for lifetimes as parameters of generics
463     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
464         self.map.remove(&lifetime.name.ident().name);
465     }
466
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);
475         }
476     }
477     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
478         NestedVisitorMap::None
479     }
480 }
481
482 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
483     let hs = generics
484         .params
485         .iter()
486         .filter_map(|par| match par.kind {
487             GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
488             _ => None,
489         })
490         .collect();
491     let mut checker = LifetimeChecker { map: hs };
492
493     walk_generics(&mut checker, generics);
494     walk_fn_decl(&mut checker, func);
495
496     for &v in checker.map.values() {
497         span_lint(
498             cx,
499             EXTRA_UNUSED_LIFETIMES,
500             v,
501             "this lifetime isn't used in the function definition",
502         );
503     }
504 }
505
506 struct BodyLifetimeChecker {
507     lifetimes_used_in_body: bool,
508 }
509
510 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
511     type Map = Map<'tcx>;
512
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;
517         }
518     }
519
520     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
521         NestedVisitorMap::None
522     }
523 }