]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
fix bad suggestion on `numeric_literal`
[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, Ident, 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), None, 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                 None,
100                 &item.generics,
101                 item.span,
102                 report_extra_lifetimes,
103             );
104         }
105     }
106
107     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
108         if let TraitItemKind::Fn(ref sig, ref body) = item.kind {
109             let (body, trait_sig) = match *body {
110                 TraitFn::Required(sig) => (None, Some(sig)),
111                 TraitFn::Provided(id) => (Some(id), None),
112             };
113             check_fn_inner(cx, sig.decl, body, trait_sig, &item.generics, item.span, true);
114         }
115     }
116 }
117
118 /// The lifetime of a &-reference.
119 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
120 enum RefLt {
121     Unnamed,
122     Static,
123     Named(Symbol),
124 }
125
126 fn check_fn_inner<'tcx>(
127     cx: &LateContext<'tcx>,
128     decl: &'tcx FnDecl<'_>,
129     body: Option<BodyId>,
130     trait_sig: Option<&[Ident]>,
131     generics: &'tcx Generics<'_>,
132     span: Span,
133     report_extra_lifetimes: bool,
134 ) {
135     if span.from_expansion() || has_where_lifetimes(cx, &generics.where_clause) {
136         return;
137     }
138
139     let types = generics
140         .params
141         .iter()
142         .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
143     for typ in types {
144         for bound in typ.bounds {
145             let mut visitor = RefVisitor::new(cx);
146             walk_param_bound(&mut visitor, bound);
147             if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
148                 return;
149             }
150             if let GenericBound::Trait(ref trait_ref, _) = *bound {
151                 let params = &trait_ref
152                     .trait_ref
153                     .path
154                     .segments
155                     .last()
156                     .expect("a path must have at least one segment")
157                     .args;
158                 if let Some(params) = *params {
159                     let lifetimes = params.args.iter().filter_map(|arg| match arg {
160                         GenericArg::Lifetime(lt) => Some(lt),
161                         _ => None,
162                     });
163                     for bound in lifetimes {
164                         if bound.name != LifetimeName::Static && !bound.is_elided() {
165                             return;
166                         }
167                     }
168                 }
169             }
170         }
171     }
172     if could_use_elision(cx, decl, body, trait_sig, generics.params) {
173         span_lint(
174             cx,
175             NEEDLESS_LIFETIMES,
176             span.with_hi(decl.output.span().hi()),
177             "explicit lifetimes given in parameter types where they could be elided \
178              (or replaced with `'_` if needed by type declaration)",
179         );
180     }
181     if report_extra_lifetimes {
182         self::report_extra_lifetimes(cx, decl, generics);
183     }
184 }
185
186 // elision doesn't work for explicit self types, see rust-lang/rust#69064
187 fn explicit_self_type<'tcx>(cx: &LateContext<'tcx>, func: &FnDecl<'tcx>, ident: Option<Ident>) -> bool {
188     if_chain! {
189         if let Some(ident) = ident;
190         if ident.name == kw::SelfLower;
191         if !func.implicit_self.has_implicit_self();
192
193         if let Some(self_ty) = func.inputs.first();
194         then {
195             let mut visitor = RefVisitor::new(cx);
196             visitor.visit_ty(self_ty);
197
198             !visitor.all_lts().is_empty()
199         }
200         else {
201             false
202         }
203     }
204 }
205
206 fn could_use_elision<'tcx>(
207     cx: &LateContext<'tcx>,
208     func: &'tcx FnDecl<'_>,
209     body: Option<BodyId>,
210     trait_sig: Option<&[Ident]>,
211     named_generics: &'tcx [GenericParam<'_>],
212 ) -> bool {
213     // There are two scenarios where elision works:
214     // * no output references, all input references have different LT
215     // * output references, exactly one input reference with same LT
216     // All lifetimes must be unnamed, 'static or defined without bounds on the
217     // level of the current item.
218
219     // check named LTs
220     let allowed_lts = allowed_lts_from(named_generics);
221
222     // these will collect all the lifetimes for references in arg/return types
223     let mut input_visitor = RefVisitor::new(cx);
224     let mut output_visitor = RefVisitor::new(cx);
225
226     // extract lifetimes in input argument types
227     for arg in func.inputs {
228         input_visitor.visit_ty(arg);
229     }
230     // extract lifetimes in output type
231     if let Return(ty) = func.output {
232         output_visitor.visit_ty(ty);
233     }
234     for lt in named_generics {
235         input_visitor.visit_generic_param(lt);
236     }
237
238     if input_visitor.abort() || output_visitor.abort() {
239         return false;
240     }
241
242     if allowed_lts
243         .intersection(
244             &input_visitor
245                 .nested_elision_site_lts
246                 .iter()
247                 .chain(output_visitor.nested_elision_site_lts.iter())
248                 .cloned()
249                 .filter(|v| matches!(v, RefLt::Named(_)))
250                 .collect(),
251         )
252         .next()
253         .is_some()
254     {
255         return false;
256     }
257
258     let input_lts = input_visitor.lts;
259     let output_lts = output_visitor.lts;
260
261     if let Some(trait_sig) = trait_sig {
262         if explicit_self_type(cx, func, trait_sig.first().copied()) {
263             return false;
264         }
265     }
266
267     if let Some(body_id) = body {
268         let body = cx.tcx.hir().body(body_id);
269
270         let first_ident = body.params.first().and_then(|param| param.pat.simple_ident());
271         if explicit_self_type(cx, func, first_ident) {
272             return false;
273         }
274
275         let mut checker = BodyLifetimeChecker {
276             lifetimes_used_in_body: false,
277         };
278         checker.visit_expr(&body.value);
279         if checker.lifetimes_used_in_body {
280             return false;
281         }
282     }
283
284     // check for lifetimes from higher scopes
285     for lt in input_lts.iter().chain(output_lts.iter()) {
286         if !allowed_lts.contains(lt) {
287             return false;
288         }
289     }
290
291     // no input lifetimes? easy case!
292     if input_lts.is_empty() {
293         false
294     } else if output_lts.is_empty() {
295         // no output lifetimes, check distinctness of input lifetimes
296
297         // only unnamed and static, ok
298         let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
299         if unnamed_and_static {
300             return false;
301         }
302         // we have no output reference, so we only need all distinct lifetimes
303         input_lts.len() == unique_lifetimes(&input_lts)
304     } else {
305         // we have output references, so we need one input reference,
306         // and all output lifetimes must be the same
307         if unique_lifetimes(&output_lts) > 1 {
308             return false;
309         }
310         if input_lts.len() == 1 {
311             match (&input_lts[0], &output_lts[0]) {
312                 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
313                 (&RefLt::Named(_), &RefLt::Unnamed) => true,
314                 _ => false, /* already elided, different named lifetimes
315                              * or something static going on */
316             }
317         } else {
318             false
319         }
320     }
321 }
322
323 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
324     let mut allowed_lts = FxHashSet::default();
325     for par in named_generics.iter() {
326         if let GenericParamKind::Lifetime { .. } = par.kind {
327             if par.bounds.is_empty() {
328                 allowed_lts.insert(RefLt::Named(par.name.ident().name));
329             }
330         }
331     }
332     allowed_lts.insert(RefLt::Unnamed);
333     allowed_lts.insert(RefLt::Static);
334     allowed_lts
335 }
336
337 /// Number of unique lifetimes in the given vector.
338 #[must_use]
339 fn unique_lifetimes(lts: &[RefLt]) -> usize {
340     lts.iter().collect::<FxHashSet<_>>().len()
341 }
342
343 const CLOSURE_TRAIT_BOUNDS: [LangItem; 3] = [LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
344
345 /// A visitor usable for `rustc_front::visit::walk_ty()`.
346 struct RefVisitor<'a, 'tcx> {
347     cx: &'a LateContext<'tcx>,
348     lts: Vec<RefLt>,
349     nested_elision_site_lts: Vec<RefLt>,
350     unelided_trait_object_lifetime: bool,
351 }
352
353 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
354     fn new(cx: &'a LateContext<'tcx>) -> Self {
355         Self {
356             cx,
357             lts: Vec::new(),
358             nested_elision_site_lts: Vec::new(),
359             unelided_trait_object_lifetime: false,
360         }
361     }
362
363     fn record(&mut self, lifetime: &Option<Lifetime>) {
364         if let Some(ref lt) = *lifetime {
365             if lt.name == LifetimeName::Static {
366                 self.lts.push(RefLt::Static);
367             } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
368                 // Fresh lifetimes generated should be ignored.
369             } else if lt.is_elided() {
370                 self.lts.push(RefLt::Unnamed);
371             } else {
372                 self.lts.push(RefLt::Named(lt.name.ident().name));
373             }
374         } else {
375             self.lts.push(RefLt::Unnamed);
376         }
377     }
378
379     fn all_lts(&self) -> Vec<RefLt> {
380         self.lts
381             .iter()
382             .chain(self.nested_elision_site_lts.iter())
383             .cloned()
384             .collect::<Vec<_>>()
385     }
386
387     fn abort(&self) -> bool {
388         self.unelided_trait_object_lifetime
389     }
390 }
391
392 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
393     type Map = Map<'tcx>;
394
395     // for lifetimes as parameters of generics
396     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
397         self.record(&Some(*lifetime));
398     }
399
400     fn visit_poly_trait_ref(&mut self, poly_tref: &'tcx PolyTraitRef<'tcx>, tbm: TraitBoundModifier) {
401         let trait_ref = &poly_tref.trait_ref;
402         if CLOSURE_TRAIT_BOUNDS.iter().any(|&item| {
403             self.cx
404                 .tcx
405                 .lang_items()
406                 .require(item)
407                 .map_or(false, |id| Some(id) == trait_ref.trait_def_id())
408         }) {
409             let mut sub_visitor = RefVisitor::new(self.cx);
410             sub_visitor.visit_trait_ref(trait_ref);
411             self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
412         } else {
413             walk_poly_trait_ref(self, poly_tref, tbm);
414         }
415     }
416
417     fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
418         match ty.kind {
419             TyKind::OpaqueDef(item, bounds) => {
420                 let map = self.cx.tcx.hir();
421                 let item = map.item(item);
422                 walk_item(self, item);
423                 walk_ty(self, ty);
424                 self.lts.extend(bounds.iter().filter_map(|bound| match bound {
425                     GenericArg::Lifetime(l) => Some(RefLt::Named(l.name.ident().name)),
426                     _ => None,
427                 }));
428             },
429             TyKind::BareFn(&BareFnTy { decl, .. }) => {
430                 let mut sub_visitor = RefVisitor::new(self.cx);
431                 sub_visitor.visit_fn_decl(decl);
432                 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
433                 return;
434             },
435             TyKind::TraitObject(bounds, ref lt, _) => {
436                 if !lt.is_elided() {
437                     self.unelided_trait_object_lifetime = true;
438                 }
439                 for bound in bounds {
440                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
441                 }
442                 return;
443             },
444             _ => (),
445         }
446         walk_ty(self, ty);
447     }
448     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
449         NestedVisitorMap::None
450     }
451 }
452
453 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
454 /// reason about elision.
455 fn has_where_lifetimes<'tcx>(cx: &LateContext<'tcx>, where_clause: &'tcx WhereClause<'_>) -> bool {
456     for predicate in where_clause.predicates {
457         match *predicate {
458             WherePredicate::RegionPredicate(..) => return true,
459             WherePredicate::BoundPredicate(ref pred) => {
460                 // a predicate like F: Trait or F: for<'a> Trait<'a>
461                 let mut visitor = RefVisitor::new(cx);
462                 // walk the type F, it may not contain LT refs
463                 walk_ty(&mut visitor, pred.bounded_ty);
464                 if !visitor.all_lts().is_empty() {
465                     return true;
466                 }
467                 // if the bounds define new lifetimes, they are fine to occur
468                 let allowed_lts = allowed_lts_from(pred.bound_generic_params);
469                 // now walk the bounds
470                 for bound in pred.bounds.iter() {
471                     walk_param_bound(&mut visitor, bound);
472                 }
473                 // and check that all lifetimes are allowed
474                 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
475                     return true;
476                 }
477             },
478             WherePredicate::EqPredicate(ref pred) => {
479                 let mut visitor = RefVisitor::new(cx);
480                 walk_ty(&mut visitor, pred.lhs_ty);
481                 walk_ty(&mut visitor, pred.rhs_ty);
482                 if !visitor.lts.is_empty() {
483                     return true;
484                 }
485             },
486         }
487     }
488     false
489 }
490
491 struct LifetimeChecker {
492     map: FxHashMap<Symbol, Span>,
493 }
494
495 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
496     type Map = Map<'tcx>;
497
498     // for lifetimes as parameters of generics
499     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
500         self.map.remove(&lifetime.name.ident().name);
501     }
502
503     fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
504         // don't actually visit `<'a>` or `<'a: 'b>`
505         // we've already visited the `'a` declarations and
506         // don't want to spuriously remove them
507         // `'b` in `'a: 'b` is useless unless used elsewhere in
508         // a non-lifetime bound
509         if let GenericParamKind::Type { .. } = param.kind {
510             walk_generic_param(self, param);
511         }
512     }
513     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
514         NestedVisitorMap::None
515     }
516 }
517
518 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
519     let hs = generics
520         .params
521         .iter()
522         .filter_map(|par| match par.kind {
523             GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
524             _ => None,
525         })
526         .collect();
527     let mut checker = LifetimeChecker { map: hs };
528
529     walk_generics(&mut checker, generics);
530     walk_fn_decl(&mut checker, func);
531
532     for &v in checker.map.values() {
533         span_lint(
534             cx,
535             EXTRA_UNUSED_LIFETIMES,
536             v,
537             "this lifetime isn't used in the function definition",
538         );
539     }
540 }
541
542 struct BodyLifetimeChecker {
543     lifetimes_used_in_body: bool,
544 }
545
546 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
547     type Map = Map<'tcx>;
548
549     // for lifetimes as parameters of generics
550     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
551         if lifetime.name.ident().name != kw::Empty && lifetime.name.ident().name != kw::StaticLifetime {
552             self.lifetimes_used_in_body = true;
553         }
554     }
555
556     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
557         NestedVisitorMap::None
558     }
559 }