]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
use get_diagnostic_name for checking macro_call
[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::nested_filter::{self as hir_nested_filter, NestedFilter};
5 use rustc_hir::intravisit::{
6     walk_fn_decl, walk_generic_param, walk_generics, walk_impl_item_ref, walk_item, walk_param_bound,
7     walk_poly_trait_ref, walk_trait_ref, walk_ty, Visitor,
8 };
9 use rustc_hir::FnRetTy::Return;
10 use rustc_hir::{
11     BareFnTy, BodyId, FnDecl, GenericArg, GenericBound, GenericParam, GenericParamKind, Generics, Impl, ImplItem,
12     ImplItemKind, Item, ItemKind, LangItem, Lifetime, LifetimeName, ParamName, PolyTraitRef, PredicateOrigin,
13     TraitBoundModifier, TraitFn, TraitItem, TraitItemKind, Ty, TyKind, WherePredicate,
14 };
15 use rustc_lint::{LateContext, LateLintPass};
16 use rustc_middle::hir::nested_filter as middle_nested_filter;
17 use rustc_session::{declare_lint_pass, declare_tool_lint};
18 use rustc_span::source_map::Span;
19 use rustc_span::symbol::{kw, Ident, Symbol};
20
21 declare_clippy_lint! {
22     /// ### What it does
23     /// Checks for lifetime annotations which can be removed by
24     /// relying on lifetime elision.
25     ///
26     /// ### Why is this bad?
27     /// The additional lifetimes make the code look more
28     /// complicated, while there is nothing out of the ordinary going on. Removing
29     /// them leads to more readable code.
30     ///
31     /// ### Known problems
32     /// - We bail out if the function has a `where` clause where lifetimes
33     /// are mentioned due to potential false positives.
34     /// - Lifetime bounds such as `impl Foo + 'a` and `T: 'a` must be elided with the
35     /// placeholder notation `'_` because the fully elided notation leaves the type bound to `'static`.
36     ///
37     /// ### Example
38     /// ```rust
39     /// // Unnecessary lifetime annotations
40     /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
41     ///     x
42     /// }
43     /// ```
44     ///
45     /// Use instead:
46     /// ```rust
47     /// fn elided(x: &u8, y: u8) -> &u8 {
48     ///     x
49     /// }
50     /// ```
51     #[clippy::version = "pre 1.29.0"]
52     pub NEEDLESS_LIFETIMES,
53     complexity,
54     "using explicit lifetimes for references in function arguments when elision rules \
55      would allow omitting them"
56 }
57
58 declare_clippy_lint! {
59     /// ### What it does
60     /// Checks for lifetimes in generics that are never used
61     /// anywhere else.
62     ///
63     /// ### Why is this bad?
64     /// The additional lifetimes make the code look more
65     /// complicated, while there is nothing out of the ordinary going on. Removing
66     /// them leads to more readable code.
67     ///
68     /// ### Example
69     /// ```rust
70     /// // unnecessary lifetimes
71     /// fn unused_lifetime<'a>(x: u8) {
72     ///     // ..
73     /// }
74     /// ```
75     ///
76     /// Use instead:
77     /// ```rust
78     /// fn no_lifetime(x: u8) {
79     ///     // ...
80     /// }
81     /// ```
82     #[clippy::version = "pre 1.29.0"]
83     pub EXTRA_UNUSED_LIFETIMES,
84     complexity,
85     "unused lifetimes in function definitions"
86 }
87
88 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
89
90 impl<'tcx> LateLintPass<'tcx> for Lifetimes {
91     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
92         if let ItemKind::Fn(ref sig, generics, id) = item.kind {
93             check_fn_inner(cx, sig.decl, Some(id), None, generics, item.span, true);
94         } else if let ItemKind::Impl(impl_) = item.kind {
95             report_extra_impl_lifetimes(cx, impl_);
96         }
97     }
98
99     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
100         if let ImplItemKind::Fn(ref sig, id) = item.kind {
101             let report_extra_lifetimes = trait_ref_of_method(cx, item.def_id).is_none();
102             check_fn_inner(
103                 cx,
104                 sig.decl,
105                 Some(id),
106                 None,
107                 item.generics,
108                 item.span,
109                 report_extra_lifetimes,
110             );
111         }
112     }
113
114     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
115         if let TraitItemKind::Fn(ref sig, ref body) = item.kind {
116             let (body, trait_sig) = match *body {
117                 TraitFn::Required(sig) => (None, Some(sig)),
118                 TraitFn::Provided(id) => (Some(id), None),
119             };
120             check_fn_inner(cx, sig.decl, body, trait_sig, item.generics, item.span, true);
121         }
122     }
123 }
124
125 /// The lifetime of a &-reference.
126 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
127 enum RefLt {
128     Unnamed,
129     Static,
130     Named(Symbol),
131 }
132
133 fn check_fn_inner<'tcx>(
134     cx: &LateContext<'tcx>,
135     decl: &'tcx FnDecl<'_>,
136     body: Option<BodyId>,
137     trait_sig: Option<&[Ident]>,
138     generics: &'tcx Generics<'_>,
139     span: Span,
140     report_extra_lifetimes: bool,
141 ) {
142     if span.from_expansion() || has_where_lifetimes(cx, generics) {
143         return;
144     }
145
146     let types = generics
147         .params
148         .iter()
149         .filter(|param| matches!(param.kind, GenericParamKind::Type { .. }));
150     for typ in types {
151         for pred in generics.bounds_for_param(cx.tcx.hir().local_def_id(typ.hir_id)) {
152             if pred.origin == PredicateOrigin::WhereClause {
153                 // has_where_lifetimes checked that this predicate contains no lifetime.
154                 continue;
155             }
156
157             for bound in pred.bounds {
158                 let mut visitor = RefVisitor::new(cx);
159                 walk_param_bound(&mut visitor, bound);
160                 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
161                     return;
162                 }
163                 if let GenericBound::Trait(ref trait_ref, _) = *bound {
164                     let params = &trait_ref
165                         .trait_ref
166                         .path
167                         .segments
168                         .last()
169                         .expect("a path must have at least one segment")
170                         .args;
171                     if let Some(params) = *params {
172                         let lifetimes = params.args.iter().filter_map(|arg| match arg {
173                             GenericArg::Lifetime(lt) => Some(lt),
174                             _ => None,
175                         });
176                         for bound in lifetimes {
177                             if bound.name != LifetimeName::Static && !bound.is_elided() {
178                                 return;
179                             }
180                         }
181                     }
182                 }
183             }
184         }
185     }
186     if could_use_elision(cx, decl, body, trait_sig, generics.params) {
187         span_lint(
188             cx,
189             NEEDLESS_LIFETIMES,
190             span.with_hi(decl.output.span().hi()),
191             "explicit lifetimes given in parameter types where they could be elided \
192              (or replaced with `'_` if needed by type declaration)",
193         );
194     }
195     if report_extra_lifetimes {
196         self::report_extra_lifetimes(cx, decl, generics);
197     }
198 }
199
200 // elision doesn't work for explicit self types, see rust-lang/rust#69064
201 fn explicit_self_type<'tcx>(cx: &LateContext<'tcx>, func: &FnDecl<'tcx>, ident: Option<Ident>) -> bool {
202     if_chain! {
203         if let Some(ident) = ident;
204         if ident.name == kw::SelfLower;
205         if !func.implicit_self.has_implicit_self();
206
207         if let Some(self_ty) = func.inputs.first();
208         then {
209             let mut visitor = RefVisitor::new(cx);
210             visitor.visit_ty(self_ty);
211
212             !visitor.all_lts().is_empty()
213         } else {
214             false
215         }
216     }
217 }
218
219 fn could_use_elision<'tcx>(
220     cx: &LateContext<'tcx>,
221     func: &'tcx FnDecl<'_>,
222     body: Option<BodyId>,
223     trait_sig: Option<&[Ident]>,
224     named_generics: &'tcx [GenericParam<'_>],
225 ) -> bool {
226     // There are two scenarios where elision works:
227     // * no output references, all input references have different LT
228     // * output references, exactly one input reference with same LT
229     // All lifetimes must be unnamed, 'static or defined without bounds on the
230     // level of the current item.
231
232     // check named LTs
233     let allowed_lts = allowed_lts_from(named_generics);
234
235     // these will collect all the lifetimes for references in arg/return types
236     let mut input_visitor = RefVisitor::new(cx);
237     let mut output_visitor = RefVisitor::new(cx);
238
239     // extract lifetimes in input argument types
240     for arg in func.inputs {
241         input_visitor.visit_ty(arg);
242     }
243     // extract lifetimes in output type
244     if let Return(ty) = func.output {
245         output_visitor.visit_ty(ty);
246     }
247     for lt in named_generics {
248         input_visitor.visit_generic_param(lt);
249     }
250
251     if input_visitor.abort() || output_visitor.abort() {
252         return false;
253     }
254
255     if allowed_lts
256         .intersection(
257             &input_visitor
258                 .nested_elision_site_lts
259                 .iter()
260                 .chain(output_visitor.nested_elision_site_lts.iter())
261                 .cloned()
262                 .filter(|v| matches!(v, RefLt::Named(_)))
263                 .collect(),
264         )
265         .next()
266         .is_some()
267     {
268         return false;
269     }
270
271     let input_lts = input_visitor.lts;
272     let output_lts = output_visitor.lts;
273
274     if let Some(trait_sig) = trait_sig {
275         if explicit_self_type(cx, func, trait_sig.first().copied()) {
276             return false;
277         }
278     }
279
280     if let Some(body_id) = body {
281         let body = cx.tcx.hir().body(body_id);
282
283         let first_ident = body.params.first().and_then(|param| param.pat.simple_ident());
284         if explicit_self_type(cx, func, first_ident) {
285             return false;
286         }
287
288         let mut checker = BodyLifetimeChecker {
289             lifetimes_used_in_body: false,
290         };
291         checker.visit_expr(&body.value);
292         if checker.lifetimes_used_in_body {
293             return false;
294         }
295     }
296
297     // check for lifetimes from higher scopes
298     for lt in input_lts.iter().chain(output_lts.iter()) {
299         if !allowed_lts.contains(lt) {
300             return false;
301         }
302     }
303
304     // no input lifetimes? easy case!
305     if input_lts.is_empty() {
306         false
307     } else if output_lts.is_empty() {
308         // no output lifetimes, check distinctness of input lifetimes
309
310         // only unnamed and static, ok
311         let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
312         if unnamed_and_static {
313             return false;
314         }
315         // we have no output reference, so we only need all distinct lifetimes
316         input_lts.len() == unique_lifetimes(&input_lts)
317     } else {
318         // we have output references, so we need one input reference,
319         // and all output lifetimes must be the same
320         if unique_lifetimes(&output_lts) > 1 {
321             return false;
322         }
323         if input_lts.len() == 1 {
324             match (&input_lts[0], &output_lts[0]) {
325                 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
326                 (&RefLt::Named(_), &RefLt::Unnamed) => true,
327                 _ => false, /* already elided, different named lifetimes
328                              * or something static going on */
329             }
330         } else {
331             false
332         }
333     }
334 }
335
336 fn allowed_lts_from(named_generics: &[GenericParam<'_>]) -> FxHashSet<RefLt> {
337     let mut allowed_lts = FxHashSet::default();
338     for par in named_generics.iter() {
339         if let GenericParamKind::Lifetime { .. } = par.kind {
340             allowed_lts.insert(RefLt::Named(par.name.ident().name));
341         }
342     }
343     allowed_lts.insert(RefLt::Unnamed);
344     allowed_lts.insert(RefLt::Static);
345     allowed_lts
346 }
347
348 /// Number of unique lifetimes in the given vector.
349 #[must_use]
350 fn unique_lifetimes(lts: &[RefLt]) -> usize {
351     lts.iter().collect::<FxHashSet<_>>().len()
352 }
353
354 const CLOSURE_TRAIT_BOUNDS: [LangItem; 3] = [LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
355
356 /// A visitor usable for `rustc_front::visit::walk_ty()`.
357 struct RefVisitor<'a, 'tcx> {
358     cx: &'a LateContext<'tcx>,
359     lts: Vec<RefLt>,
360     nested_elision_site_lts: Vec<RefLt>,
361     unelided_trait_object_lifetime: bool,
362 }
363
364 impl<'a, 'tcx> RefVisitor<'a, 'tcx> {
365     fn new(cx: &'a LateContext<'tcx>) -> Self {
366         Self {
367             cx,
368             lts: Vec::new(),
369             nested_elision_site_lts: Vec::new(),
370             unelided_trait_object_lifetime: false,
371         }
372     }
373
374     fn record(&mut self, lifetime: &Option<Lifetime>) {
375         if let Some(ref lt) = *lifetime {
376             if lt.name == LifetimeName::Static {
377                 self.lts.push(RefLt::Static);
378             } else if let LifetimeName::Param(_, ParamName::Fresh) = lt.name {
379                 // Fresh lifetimes generated should be ignored.
380             } else if lt.is_elided() {
381                 self.lts.push(RefLt::Unnamed);
382             } else {
383                 self.lts.push(RefLt::Named(lt.name.ident().name));
384             }
385         } else {
386             self.lts.push(RefLt::Unnamed);
387         }
388     }
389
390     fn all_lts(&self) -> Vec<RefLt> {
391         self.lts
392             .iter()
393             .chain(self.nested_elision_site_lts.iter())
394             .cloned()
395             .collect::<Vec<_>>()
396     }
397
398     fn abort(&self) -> bool {
399         self.unelided_trait_object_lifetime
400     }
401 }
402
403 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
404     // for lifetimes as parameters of generics
405     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
406         self.record(&Some(*lifetime));
407     }
408
409     fn visit_poly_trait_ref(&mut self, poly_tref: &'tcx PolyTraitRef<'tcx>, tbm: TraitBoundModifier) {
410         let trait_ref = &poly_tref.trait_ref;
411         if CLOSURE_TRAIT_BOUNDS.iter().any(|&item| {
412             self.cx
413                 .tcx
414                 .lang_items()
415                 .require(item)
416                 .map_or(false, |id| Some(id) == trait_ref.trait_def_id())
417         }) {
418             let mut sub_visitor = RefVisitor::new(self.cx);
419             sub_visitor.visit_trait_ref(trait_ref);
420             self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
421         } else {
422             walk_poly_trait_ref(self, poly_tref, tbm);
423         }
424     }
425
426     fn visit_ty(&mut self, ty: &'tcx Ty<'_>) {
427         match ty.kind {
428             TyKind::OpaqueDef(item, bounds) => {
429                 let map = self.cx.tcx.hir();
430                 let item = map.item(item);
431                 walk_item(self, item);
432                 walk_ty(self, ty);
433                 self.lts.extend(bounds.iter().filter_map(|bound| match bound {
434                     GenericArg::Lifetime(l) => Some(RefLt::Named(l.name.ident().name)),
435                     _ => None,
436                 }));
437             },
438             TyKind::BareFn(&BareFnTy { decl, .. }) => {
439                 let mut sub_visitor = RefVisitor::new(self.cx);
440                 sub_visitor.visit_fn_decl(decl);
441                 self.nested_elision_site_lts.append(&mut sub_visitor.all_lts());
442                 return;
443             },
444             TyKind::TraitObject(bounds, ref lt, _) => {
445                 if !lt.is_elided() {
446                     self.unelided_trait_object_lifetime = true;
447                 }
448                 for bound in bounds {
449                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
450                 }
451                 return;
452             },
453             _ => (),
454         }
455         walk_ty(self, ty);
456     }
457 }
458
459 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
460 /// reason about elision.
461 fn has_where_lifetimes<'tcx>(cx: &LateContext<'tcx>, generics: &'tcx Generics<'_>) -> bool {
462     for predicate in generics.predicates {
463         match *predicate {
464             WherePredicate::RegionPredicate(..) => return true,
465             WherePredicate::BoundPredicate(ref pred) => {
466                 // a predicate like F: Trait or F: for<'a> Trait<'a>
467                 let mut visitor = RefVisitor::new(cx);
468                 // walk the type F, it may not contain LT refs
469                 walk_ty(&mut visitor, pred.bounded_ty);
470                 if !visitor.all_lts().is_empty() {
471                     return true;
472                 }
473                 // if the bounds define new lifetimes, they are fine to occur
474                 let allowed_lts = allowed_lts_from(pred.bound_generic_params);
475                 // now walk the bounds
476                 for bound in pred.bounds.iter() {
477                     walk_param_bound(&mut visitor, bound);
478                 }
479                 // and check that all lifetimes are allowed
480                 if visitor.all_lts().iter().any(|it| !allowed_lts.contains(it)) {
481                     return true;
482                 }
483             },
484             WherePredicate::EqPredicate(ref pred) => {
485                 let mut visitor = RefVisitor::new(cx);
486                 walk_ty(&mut visitor, pred.lhs_ty);
487                 walk_ty(&mut visitor, pred.rhs_ty);
488                 if !visitor.lts.is_empty() {
489                     return true;
490                 }
491             },
492         }
493     }
494     false
495 }
496
497 struct LifetimeChecker<'cx, 'tcx, F> {
498     cx: &'cx LateContext<'tcx>,
499     map: FxHashMap<Symbol, Span>,
500     phantom: std::marker::PhantomData<F>,
501 }
502
503 impl<'cx, 'tcx, F> LifetimeChecker<'cx, 'tcx, F> {
504     fn new(cx: &'cx LateContext<'tcx>, map: FxHashMap<Symbol, Span>) -> LifetimeChecker<'cx, 'tcx, F> {
505         Self {
506             cx,
507             map,
508             phantom: std::marker::PhantomData,
509         }
510     }
511 }
512
513 impl<'cx, 'tcx, F> Visitor<'tcx> for LifetimeChecker<'cx, 'tcx, F>
514 where
515     F: NestedFilter<'tcx>,
516 {
517     type Map = rustc_middle::hir::map::Map<'tcx>;
518     type NestedFilter = F;
519
520     // for lifetimes as parameters of generics
521     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
522         self.map.remove(&lifetime.name.ident().name);
523     }
524
525     fn visit_generic_param(&mut self, param: &'tcx GenericParam<'_>) {
526         // don't actually visit `<'a>` or `<'a: 'b>`
527         // we've already visited the `'a` declarations and
528         // don't want to spuriously remove them
529         // `'b` in `'a: 'b` is useless unless used elsewhere in
530         // a non-lifetime bound
531         if let GenericParamKind::Type { .. } = param.kind {
532             walk_generic_param(self, param);
533         }
534     }
535
536     fn nested_visit_map(&mut self) -> Self::Map {
537         self.cx.tcx.hir()
538     }
539 }
540
541 fn report_extra_lifetimes<'tcx>(cx: &LateContext<'tcx>, func: &'tcx FnDecl<'_>, generics: &'tcx Generics<'_>) {
542     let hs = generics
543         .params
544         .iter()
545         .filter_map(|par| match par.kind {
546             GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
547             _ => None,
548         })
549         .collect();
550     let mut checker = LifetimeChecker::<hir_nested_filter::None>::new(cx, hs);
551
552     walk_generics(&mut checker, generics);
553     walk_fn_decl(&mut checker, func);
554
555     for &v in checker.map.values() {
556         span_lint(
557             cx,
558             EXTRA_UNUSED_LIFETIMES,
559             v,
560             "this lifetime isn't used in the function definition",
561         );
562     }
563 }
564
565 fn report_extra_impl_lifetimes<'tcx>(cx: &LateContext<'tcx>, impl_: &'tcx Impl<'_>) {
566     let hs = impl_
567         .generics
568         .params
569         .iter()
570         .filter_map(|par| match par.kind {
571             GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
572             _ => None,
573         })
574         .collect();
575     let mut checker = LifetimeChecker::<middle_nested_filter::All>::new(cx, hs);
576
577     walk_generics(&mut checker, impl_.generics);
578     if let Some(ref trait_ref) = impl_.of_trait {
579         walk_trait_ref(&mut checker, trait_ref);
580     }
581     walk_ty(&mut checker, impl_.self_ty);
582     for item in impl_.items {
583         walk_impl_item_ref(&mut checker, item);
584     }
585
586     for &v in checker.map.values() {
587         span_lint(cx, EXTRA_UNUSED_LIFETIMES, v, "this lifetime isn't used in the impl");
588     }
589 }
590
591 struct BodyLifetimeChecker {
592     lifetimes_used_in_body: bool,
593 }
594
595 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
596     // for lifetimes as parameters of generics
597     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
598         if lifetime.name.ident().name != kw::Empty && lifetime.name.ident().name != kw::StaticLifetime {
599             self.lifetimes_used_in_body = true;
600         }
601     }
602 }