]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
Doctests: Fix all complexity lint docs
[rust.git] / clippy_lints / src / lifetimes.rs
1 use matches::matches;
2 use rustc::hir::def::{DefKind, Res};
3 use rustc::hir::intravisit::*;
4 use rustc::hir::*;
5 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use syntax::source_map::Span;
9 use syntax::symbol::kw;
10
11 use crate::reexport::*;
12 use crate::utils::{last_path_segment, span_lint};
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for lifetime annotations which can be removed by
16     /// relying on lifetime elision.
17     ///
18     /// **Why is this bad?** The additional lifetimes make the code look more
19     /// complicated, while there is nothing out of the ordinary going on. Removing
20     /// them leads to more readable code.
21     ///
22     /// **Known problems:** Potential false negatives: we bail out if the function
23     /// has a `where` clause where lifetimes are mentioned.
24     ///
25     /// **Example:**
26     /// ```rust
27     /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {
28     ///     x
29     /// }
30     /// ```
31     pub NEEDLESS_LIFETIMES,
32     complexity,
33     "using explicit lifetimes for references in function arguments when elision rules \
34      would allow omitting them"
35 }
36
37 declare_clippy_lint! {
38     /// **What it does:** Checks for lifetimes in generics that are never used
39     /// anywhere else.
40     ///
41     /// **Why is this bad?** The additional lifetimes make the code look more
42     /// complicated, while there is nothing out of the ordinary going on. Removing
43     /// them leads to more readable code.
44     ///
45     /// **Known problems:** None.
46     ///
47     /// **Example:**
48     /// ```rust
49     /// fn unused_lifetime<'a>(x: u8) {
50     ///     // ..
51     /// }
52     /// ```
53     pub EXTRA_UNUSED_LIFETIMES,
54     complexity,
55     "unused lifetimes in function definitions"
56 }
57
58 declare_lint_pass!(Lifetimes => [NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES]);
59
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Lifetimes {
61     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
62         if let ItemKind::Fn(ref decl, _, ref generics, id) = item.node {
63             check_fn_inner(cx, decl, Some(id), generics, item.span);
64         }
65     }
66
67     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
68         if let ImplItemKind::Method(ref sig, id) = item.node {
69             check_fn_inner(cx, &sig.decl, Some(id), &item.generics, item.span);
70         }
71     }
72
73     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
74         if let TraitItemKind::Method(ref sig, ref body) = item.node {
75             let body = match *body {
76                 TraitMethod::Required(_) => None,
77                 TraitMethod::Provided(id) => Some(id),
78             };
79             check_fn_inner(cx, &sig.decl, body, &item.generics, item.span);
80         }
81     }
82 }
83
84 /// The lifetime of a &-reference.
85 #[derive(PartialEq, Eq, Hash, Debug)]
86 enum RefLt {
87     Unnamed,
88     Static,
89     Named(Name),
90 }
91
92 fn check_fn_inner<'a, 'tcx>(
93     cx: &LateContext<'a, 'tcx>,
94     decl: &'tcx FnDecl,
95     body: Option<BodyId>,
96     generics: &'tcx Generics,
97     span: Span,
98 ) {
99     if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
100         return;
101     }
102
103     let mut bounds_lts = Vec::new();
104     let types = generics.params.iter().filter(|param| match param.kind {
105         GenericParamKind::Type { .. } => true,
106         _ => false,
107     });
108     for typ in types {
109         for bound in &typ.bounds {
110             let mut visitor = RefVisitor::new(cx);
111             walk_param_bound(&mut visitor, bound);
112             if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
113                 return;
114             }
115             if let GenericBound::Trait(ref trait_ref, _) = *bound {
116                 let params = &trait_ref
117                     .trait_ref
118                     .path
119                     .segments
120                     .last()
121                     .expect("a path must have at least one segment")
122                     .args;
123                 if let Some(ref params) = *params {
124                     let lifetimes = params.args.iter().filter_map(|arg| match arg {
125                         GenericArg::Lifetime(lt) => Some(lt),
126                         _ => None,
127                     });
128                     for bound in lifetimes {
129                         if bound.name != LifetimeName::Static && !bound.is_elided() {
130                             return;
131                         }
132                         bounds_lts.push(bound);
133                     }
134                 }
135             }
136         }
137     }
138     if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
139         span_lint(
140             cx,
141             NEEDLESS_LIFETIMES,
142             span,
143             "explicit lifetimes given in parameter types where they could be elided \
144              (or replaced with `'_` if needed by type declaration)",
145         );
146     }
147     report_extra_lifetimes(cx, decl, generics);
148 }
149
150 fn could_use_elision<'a, 'tcx>(
151     cx: &LateContext<'a, 'tcx>,
152     func: &'tcx FnDecl,
153     body: Option<BodyId>,
154     named_generics: &'tcx [GenericParam],
155     bounds_lts: Vec<&'tcx Lifetime>,
156 ) -> bool {
157     // There are two scenarios where elision works:
158     // * no output references, all input references have different LT
159     // * output references, exactly one input reference with same LT
160     // All lifetimes must be unnamed, 'static or defined without bounds on the
161     // level of the current item.
162
163     // check named LTs
164     let allowed_lts = allowed_lts_from(named_generics);
165
166     // these will collect all the lifetimes for references in arg/return types
167     let mut input_visitor = RefVisitor::new(cx);
168     let mut output_visitor = RefVisitor::new(cx);
169
170     // extract lifetimes in input argument types
171     for arg in &func.inputs {
172         input_visitor.visit_ty(arg);
173     }
174     // extract lifetimes in output type
175     if let Return(ref ty) = func.output {
176         output_visitor.visit_ty(ty);
177     }
178
179     let input_lts = match input_visitor.into_vec() {
180         Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
181         None => return false,
182     };
183     let output_lts = match output_visitor.into_vec() {
184         Some(val) => val,
185         None => return false,
186     };
187
188     if let Some(body_id) = body {
189         let mut checker = BodyLifetimeChecker {
190             lifetimes_used_in_body: false,
191         };
192         checker.visit_expr(&cx.tcx.hir().body(body_id).value);
193         if checker.lifetimes_used_in_body {
194             return false;
195         }
196     }
197
198     // check for lifetimes from higher scopes
199     for lt in input_lts.iter().chain(output_lts.iter()) {
200         if !allowed_lts.contains(lt) {
201             return false;
202         }
203     }
204
205     // no input lifetimes? easy case!
206     if input_lts.is_empty() {
207         false
208     } else if output_lts.is_empty() {
209         // no output lifetimes, check distinctness of input lifetimes
210
211         // only unnamed and static, ok
212         let unnamed_and_static = input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
213         if unnamed_and_static {
214             return false;
215         }
216         // we have no output reference, so we only need all distinct lifetimes
217         input_lts.len() == unique_lifetimes(&input_lts)
218     } else {
219         // we have output references, so we need one input reference,
220         // and all output lifetimes must be the same
221         if unique_lifetimes(&output_lts) > 1 {
222             return false;
223         }
224         if input_lts.len() == 1 {
225             match (&input_lts[0], &output_lts[0]) {
226                 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
227                 (&RefLt::Named(_), &RefLt::Unnamed) => true,
228                 _ => false, /* already elided, different named lifetimes
229                              * or something static going on */
230             }
231         } else {
232             false
233         }
234     }
235 }
236
237 fn allowed_lts_from(named_generics: &[GenericParam]) -> FxHashSet<RefLt> {
238     let mut allowed_lts = FxHashSet::default();
239     for par in named_generics.iter() {
240         if let GenericParamKind::Lifetime { .. } = par.kind {
241             if par.bounds.is_empty() {
242                 allowed_lts.insert(RefLt::Named(par.name.ident().name));
243             }
244         }
245     }
246     allowed_lts.insert(RefLt::Unnamed);
247     allowed_lts.insert(RefLt::Static);
248     allowed_lts
249 }
250
251 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
252     for lt in bounds_lts {
253         if lt.name != LifetimeName::Static {
254             vec.push(RefLt::Named(lt.name.ident().name));
255         }
256     }
257
258     vec
259 }
260
261 /// Number of unique lifetimes in the given vector.
262 fn unique_lifetimes(lts: &[RefLt]) -> usize {
263     lts.iter().collect::<FxHashSet<_>>().len()
264 }
265
266 /// A visitor usable for `rustc_front::visit::walk_ty()`.
267 struct RefVisitor<'a, 'tcx> {
268     cx: &'a LateContext<'a, 'tcx>,
269     lts: Vec<RefLt>,
270     abort: bool,
271 }
272
273 impl<'v, 't> RefVisitor<'v, 't> {
274     fn new(cx: &'v LateContext<'v, 't>) -> Self {
275         Self {
276             cx,
277             lts: Vec::new(),
278             abort: false,
279         }
280     }
281
282     fn record(&mut self, lifetime: &Option<Lifetime>) {
283         if let Some(ref lt) = *lifetime {
284             if lt.name == LifetimeName::Static {
285                 self.lts.push(RefLt::Static);
286             } else if let LifetimeName::Param(ParamName::Fresh(_)) = lt.name {
287                 // Fresh lifetimes generated should be ignored.
288             } else if lt.is_elided() {
289                 self.lts.push(RefLt::Unnamed);
290             } else {
291                 self.lts.push(RefLt::Named(lt.name.ident().name));
292             }
293         } else {
294             self.lts.push(RefLt::Unnamed);
295         }
296     }
297
298     fn into_vec(self) -> Option<Vec<RefLt>> {
299         if self.abort {
300             None
301         } else {
302             Some(self.lts)
303         }
304     }
305
306     fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
307         if let Some(ref last_path_segment) = last_path_segment(qpath).args {
308             if !last_path_segment.parenthesized
309                 && !last_path_segment.args.iter().any(|arg| match arg {
310                     GenericArg::Lifetime(_) => true,
311                     _ => false,
312                 })
313             {
314                 let hir_id = ty.hir_id;
315                 match self.cx.tables.qpath_res(qpath, hir_id) {
316                     Res::Def(DefKind::TyAlias, def_id) | Res::Def(DefKind::Struct, def_id) => {
317                         let generics = self.cx.tcx.generics_of(def_id);
318                         for _ in generics.params.as_slice() {
319                             self.record(&None);
320                         }
321                     },
322                     Res::Def(DefKind::Trait, def_id) => {
323                         let trait_def = self.cx.tcx.trait_def(def_id);
324                         for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
325                             self.record(&None);
326                         }
327                     },
328                     _ => (),
329                 }
330             }
331         }
332     }
333 }
334
335 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
336     // for lifetimes as parameters of generics
337     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
338         self.record(&Some(*lifetime));
339     }
340
341     fn visit_ty(&mut self, ty: &'tcx Ty) {
342         match ty.node {
343             TyKind::Rptr(ref lt, _) if lt.is_elided() => {
344                 self.record(&None);
345             },
346             TyKind::Path(ref path) => {
347                 self.collect_anonymous_lifetimes(path, ty);
348             },
349             TyKind::Def(item, _) => {
350                 let map = self.cx.tcx.hir();
351                 if let ItemKind::Existential(ref exist_ty) = map.expect_item(item.id).node {
352                     for bound in &exist_ty.bounds {
353                         if let GenericBound::Outlives(_) = *bound {
354                             self.record(&None);
355                         }
356                     }
357                 } else {
358                     unreachable!()
359                 }
360                 walk_ty(self, ty);
361             },
362             TyKind::TraitObject(ref bounds, ref lt) => {
363                 if !lt.is_elided() {
364                     self.abort = true;
365                 }
366                 for bound in bounds {
367                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
368                 }
369                 return;
370             },
371             _ => (),
372         }
373         walk_ty(self, ty);
374     }
375     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
376         NestedVisitorMap::None
377     }
378 }
379
380 /// Are any lifetimes mentioned in the `where` clause? If so, we don't try to
381 /// reason about elision.
382 fn has_where_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
383     for predicate in &where_clause.predicates {
384         match *predicate {
385             WherePredicate::RegionPredicate(..) => return true,
386             WherePredicate::BoundPredicate(ref pred) => {
387                 // a predicate like F: Trait or F: for<'a> Trait<'a>
388                 let mut visitor = RefVisitor::new(cx);
389                 // walk the type F, it may not contain LT refs
390                 walk_ty(&mut visitor, &pred.bounded_ty);
391                 if !visitor.lts.is_empty() {
392                     return true;
393                 }
394                 // if the bounds define new lifetimes, they are fine to occur
395                 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
396                 // now walk the bounds
397                 for bound in pred.bounds.iter() {
398                     walk_param_bound(&mut visitor, bound);
399                 }
400                 // and check that all lifetimes are allowed
401                 match visitor.into_vec() {
402                     None => return false,
403                     Some(lts) => {
404                         for lt in lts {
405                             if !allowed_lts.contains(&lt) {
406                                 return true;
407                             }
408                         }
409                     },
410                 }
411             },
412             WherePredicate::EqPredicate(ref pred) => {
413                 let mut visitor = RefVisitor::new(cx);
414                 walk_ty(&mut visitor, &pred.lhs_ty);
415                 walk_ty(&mut visitor, &pred.rhs_ty);
416                 if !visitor.lts.is_empty() {
417                     return true;
418                 }
419             },
420         }
421     }
422     false
423 }
424
425 struct LifetimeChecker {
426     map: FxHashMap<Name, Span>,
427 }
428
429 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
430     // for lifetimes as parameters of generics
431     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
432         self.map.remove(&lifetime.name.ident().name);
433     }
434
435     fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
436         // don't actually visit `<'a>` or `<'a: 'b>`
437         // we've already visited the `'a` declarations and
438         // don't want to spuriously remove them
439         // `'b` in `'a: 'b` is useless unless used elsewhere in
440         // a non-lifetime bound
441         if let GenericParamKind::Type { .. } = param.kind {
442             walk_generic_param(self, param)
443         }
444     }
445     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
446         NestedVisitorMap::None
447     }
448 }
449
450 fn report_extra_lifetimes<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
451     let hs = generics
452         .params
453         .iter()
454         .filter_map(|par| match par.kind {
455             GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
456             _ => None,
457         })
458         .collect();
459     let mut checker = LifetimeChecker { map: hs };
460
461     walk_generics(&mut checker, generics);
462     walk_fn_decl(&mut checker, func);
463
464     for &v in checker.map.values() {
465         span_lint(
466             cx,
467             EXTRA_UNUSED_LIFETIMES,
468             v,
469             "this lifetime isn't used in the function definition",
470         );
471     }
472 }
473
474 struct BodyLifetimeChecker {
475     lifetimes_used_in_body: bool,
476 }
477
478 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
479     // for lifetimes as parameters of generics
480     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
481         if lifetime.name.ident().name != kw::Invalid && lifetime.name.ident().name != kw::StaticLifetime {
482             self.lifetimes_used_in_body = true;
483         }
484     }
485
486     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
487         NestedVisitorMap::None
488     }
489 }