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