]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/lifetimes.rs
Rollup merge of #81154 - dylni:improve-design-of-assert-len, r=KodrAus
[rust.git] / src / tools / clippy / clippy_lints / src / lifetimes.rs
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,
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, Lifetime, LifetimeName, ParamName, PolyTraitRef, TraitBoundModifier, TraitFn,
12     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:** Checks for lifetime annotations which can be removed by
22     /// relying on lifetime elision.
23     ///
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.
27     ///
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`.
33     ///
34     /// **Example:**
35     /// ```rust
36     /// // Bad: unnecessary lifetime annotations
37     /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
38     ///     x
39     /// }
40     ///
41     /// // Good
42     /// fn elided(x: &u8, y: u8) -> &u8 {
43     ///     x
44     /// }
45     /// ```
46     pub NEEDLESS_LIFETIMES,
47     complexity,
48     "using explicit lifetimes for references in function arguments when elision rules \
49      would allow omitting them"
50 }
51
52 declare_clippy_lint! {
53     /// **What it does:** Checks for lifetimes in generics that are never used
54     /// anywhere else.
55     ///
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.
59     ///
60     /// **Known problems:** None.
61     ///
62     /// **Example:**
63     /// ```rust
64     /// // Bad: unnecessary lifetimes
65     /// fn unused_lifetime<'a>(x: u8) {
66     ///     // ..
67     /// }
68     ///
69     /// // Good
70     /// fn no_lifetime(x: u8) {
71     ///     // ...
72     /// }
73     /// ```
74     pub EXTRA_UNUSED_LIFETIMES,
75     complexity,
76     "unused lifetimes in function definitions"
77 }
78
79 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
80
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);
85         }
86     }
87
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();
91             check_fn_inner(
92                 cx,
93                 &sig.decl,
94                 Some(id),
95                 &item.generics,
96                 item.span,
97                 report_extra_lifetimes,
98             );
99         }
100     }
101
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),
107             };
108             check_fn_inner(cx, &sig.decl, body, &item.generics, item.span, true);
109         }
110     }
111 }
112
113 /// The lifetime of a &-reference.
114 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
115 enum RefLt {
116     Unnamed,
117     Static,
118     Named(Symbol),
119 }
120
121 fn check_fn_inner<'tcx>(
122     cx: &LateContext<'tcx>,
123     decl: &'tcx FnDecl<'_>,
124     body: Option<BodyId>,
125     generics: &'tcx Generics<'_>,
126     span: Span,
127     report_extra_lifetimes: bool,
128 ) {
129     if in_macro(span) || has_where_lifetimes(cx, &generics.where_clause) {
130         return;
131     }
132
133     let types = generics
134         .params
135         .iter()
136         .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
137     for typ in types {
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(_))) {
142                 return;
143             }
144             if let GenericBound::Trait(ref trait_ref, _) = *bound {
145                 let params = &trait_ref
146                     .trait_ref
147                     .path
148                     .segments
149                     .last()
150                     .expect("a path must have at least one segment")
151                     .args;
152                 if let Some(ref params) = *params {
153                     let lifetimes = params.args.iter().filter_map(|arg| match arg {
154                         GenericArg::Lifetime(lt) => Some(lt),
155                         _ => None,
156                     });
157                     for bound in lifetimes {
158                         if bound.name != LifetimeName::Static && !bound.is_elided() {
159                             return;
160                         }
161                     }
162                 }
163             }
164         }
165     }
166     if could_use_elision(cx, decl, body, &generics.params) {
167         span_lint(
168             cx,
169             NEEDLESS_LIFETIMES,
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)",
173         );
174     }
175     if report_extra_lifetimes {
176         self::report_extra_lifetimes(cx, decl, generics);
177     }
178 }
179
180 fn could_use_elision<'tcx>(
181     cx: &LateContext<'tcx>,
182     func: &'tcx FnDecl<'_>,
183     body: Option<BodyId>,
184     named_generics: &'tcx [GenericParam<'_>],
185 ) -> bool {
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.
191
192     // check named LTs
193     let allowed_lts = allowed_lts_from(named_generics);
194
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);
198
199     // extract lifetimes in input argument types
200     for arg in func.inputs {
201         input_visitor.visit_ty(arg);
202     }
203     // extract lifetimes in output type
204     if let Return(ref ty) = func.output {
205         output_visitor.visit_ty(ty);
206     }
207     for lt in named_generics {
208         input_visitor.visit_generic_param(lt)
209     }
210
211     if input_visitor.abort() || output_visitor.abort() {
212         return false;
213     }
214
215     if allowed_lts
216         .intersection(
217             &input_visitor
218                 .nested_elision_site_lts
219                 .iter()
220                 .chain(output_visitor.nested_elision_site_lts.iter())
221                 .cloned()
222                 .filter(|v| matches!(v, RefLt::Named(_)))
223                 .collect(),
224         )
225         .next()
226         .is_some()
227     {
228         return false;
229     }
230
231     let input_lts = input_visitor.lts;
232     let output_lts = output_visitor.lts;
233
234     if let Some(body_id) = body {
235         let mut checker = BodyLifetimeChecker {
236             lifetimes_used_in_body: false,
237         };
238         checker.visit_expr(&cx.tcx.hir().body(body_id).value);
239         if checker.lifetimes_used_in_body {
240             return false;
241         }
242     }
243
244     // check for lifetimes from higher scopes
245     for lt in input_lts.iter().chain(output_lts.iter()) {
246         if !allowed_lts.contains(lt) {
247             return false;
248         }
249     }
250
251     // no input lifetimes? easy case!
252     if input_lts.is_empty() {
253         false
254     } else if output_lts.is_empty() {
255         // no output lifetimes, check distinctness of input lifetimes
256
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 {
260             return false;
261         }
262         // we have no output reference, so we only need all distinct lifetimes
263         input_lts.len() == unique_lifetimes(&input_lts)
264     } else {
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 {
268             return false;
269         }
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 */
276             }
277         } else {
278             false
279         }
280     }
281 }
282
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));
289             }
290         }
291     }
292     allowed_lts.insert(RefLt::Unnamed);
293     allowed_lts.insert(RefLt::Static);
294     allowed_lts
295 }
296
297 /// Number of unique lifetimes in the given vector.
298 #[must_use]
299 fn unique_lifetimes(lts: &[RefLt]) -> usize {
300     lts.iter().collect::<FxHashSet<_>>().len()
301 }
302
303 const CLOSURE_TRAIT_BOUNDS: [&[&str]; 3] = [&paths::FN, &paths::FN_MUT, &paths::FN_ONCE];
304
305 /// A visitor usable for `rustc_front::visit::walk_ty()`.
306 struct RefVisitor<'a, 'tcx> {
307     cx: &'a LateContext<'tcx>,
308     lts: Vec<RefLt>,
309     nested_elision_site_lts: Vec<RefLt>,
310     unelided_trait_object_lifetime: bool,
311 }
312
313 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
314     fn new(cx: &'a LateContext<'tcx>) -> Self {
315         Self {
316             cx,
317             lts: Vec::new(),
318             nested_elision_site_lts: Vec::new(),
319             unelided_trait_object_lifetime: false,
320         }
321     }
322
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);
331             } else {
332                 self.lts.push(RefLt::Named(lt.name.ident().name));
333             }
334         } else {
335             self.lts.push(RefLt::Unnamed);
336         }
337     }
338
339     fn all_lts(&self) -> Vec<RefLt> {
340         self.lts
341             .iter()
342             .chain(self.nested_elision_site_lts.iter())
343             .cloned()
344             .collect::<Vec<_>>()
345     }
346
347     fn abort(&self) -> bool {
348         self.unelided_trait_object_lifetime
349     }
350 }
351
352 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
353     type Map = Map<'tcx>;
354
355     // for lifetimes as parameters of generics
356     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
357         self.record(&Some(*lifetime));
358     }
359
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
363             .iter()
364             .any(|trait_path| trait_ref.trait_def_id() == get_trait_def_id(self.cx, trait_path))
365         {
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());
369         } else {
370             walk_poly_trait_ref(self, poly_tref, tbm);
371         }
372     }
373
374     fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
375         match ty.kind {
376             TyKind::OpaqueDef(item, _) => {
377                 let map = self.cx.tcx.hir();
378                 let item = map.item(item);
379                 walk_item(self, item);
380                 walk_ty(self, ty);
381             },
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());
386                 return;
387             },
388             TyKind::TraitObject(bounds, ref lt) => {
389                 if !lt.is_elided() {
390                     self.unelided_trait_object_lifetime = true;
391                 }
392                 for bound in bounds {
393                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
394                 }
395                 return;
396             },
397             _ => (),
398         }
399         walk_ty(self, ty);
400     }
401     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
402         NestedVisitorMap::None
403     }
404 }
405
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 {
410         match *predicate {
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.all_lts().is_empty() {
418                     return true;
419                 }
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);
425                 }
426                 // and check that all lifetimes are allowed
427                 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
428                     return true;
429                 }
430             },
431             WherePredicate::EqPredicate(ref pred) => {
432                 let mut visitor = RefVisitor::new(cx);
433                 walk_ty(&mut visitor, &pred.lhs_ty);
434                 walk_ty(&mut visitor, &pred.rhs_ty);
435                 if !visitor.lts.is_empty() {
436                     return true;
437                 }
438             },
439         }
440     }
441     false
442 }
443
444 struct LifetimeChecker {
445     map: FxHashMap<Symbol, Span>,
446 }
447
448 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
449     type Map = Map<'tcx>;
450
451     // for lifetimes as parameters of generics
452     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
453         self.map.remove(&lifetime.name.ident().name);
454     }
455
456     fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
457         // don't actually visit `<'a>` or `<'a: 'b>`
458         // we've already visited the `'a` declarations and
459         // don't want to spuriously remove them
460         // `'b` in `'a: 'b` is useless unless used elsewhere in
461         // a non-lifetime bound
462         if let GenericParamKind::Type { .. } = param.kind {
463             walk_generic_param(self, param)
464         }
465     }
466     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
467         NestedVisitorMap::None
468     }
469 }
470
471 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
472     let hs = generics
473         .params
474         .iter()
475         .filter_map(|par| match par.kind {
476             GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
477             _ => None,
478         })
479         .collect();
480     let mut checker = LifetimeChecker { map: hs };
481
482     walk_generics(&mut checker, generics);
483     walk_fn_decl(&mut checker, func);
484
485     for &v in checker.map.values() {
486         span_lint(
487             cx,
488             EXTRA_UNUSED_LIFETIMES,
489             v,
490             "this lifetime isn't used in the function definition",
491         );
492     }
493 }
494
495 struct BodyLifetimeChecker {
496     lifetimes_used_in_body: bool,
497 }
498
499 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
500     type Map = Map<'tcx>;
501
502     // for lifetimes as parameters of generics
503     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
504         if lifetime.name.ident().name != kw::Empty && lifetime.name.ident().name != kw::StaticLifetime {
505             self.lifetimes_used_in_body = true;
506         }
507     }
508
509     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
510         NestedVisitorMap::None
511     }
512 }