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