]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
Resolve field, struct and function renaming
[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 ItemFn(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     generics.params.iter().for_each(|param| match param.kind {
105         GenericParamKind::Lifetime { .. } => {},
106         GenericParamKind::Type { .. } => {
107             for bound in &param.bounds {
108                 let mut visitor = RefVisitor::new(cx);
109                 walk_param_bound(&mut visitor, bound);
110                 if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
111                     return;
112                 }
113                 if let GenericBound::Trait(ref trait_ref, _) = *bound {
114                     let params = &trait_ref
115                         .trait_ref
116                         .path
117                         .segments
118                         .last()
119                         .expect("a path must have at least one segment")
120                         .args;
121                     if let Some(ref params) = *params {
122                         for bound in &params.lifetimes {
123                             if bound.name.name() != "'static" && !bound.is_elided() {
124                                 return;
125                             }
126                             bounds_lts.push(bound);
127                         }
128                     }
129                 }
130             }
131         },
132     });
133     if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
134         span_lint(
135             cx,
136             NEEDLESS_LIFETIMES,
137             span,
138             "explicit lifetimes given in parameter types where they could be elided",
139         );
140     }
141     report_extra_lifetimes(cx, decl, generics);
142 }
143
144 fn could_use_elision<'a, 'tcx: 'a>(
145     cx: &LateContext<'a, 'tcx>,
146     func: &'tcx FnDecl,
147     body: Option<BodyId>,
148     named_generics: &'tcx [GenericParam],
149     bounds_lts: Vec<&'tcx Lifetime>,
150 ) -> bool {
151     // There are two scenarios where elision works:
152     // * no output references, all input references have different LT
153     // * output references, exactly one input reference with same LT
154     // All lifetimes must be unnamed, 'static or defined without bounds on the
155     // level of the current item.
156
157     // check named LTs
158     let allowed_lts = allowed_lts_from(named_generics);
159
160     // these will collect all the lifetimes for references in arg/return types
161     let mut input_visitor = RefVisitor::new(cx);
162     let mut output_visitor = RefVisitor::new(cx);
163
164     // extract lifetimes in input argument types
165     for arg in &func.inputs {
166         input_visitor.visit_ty(arg);
167     }
168     // extract lifetimes in output type
169     if let Return(ref ty) = func.output {
170         output_visitor.visit_ty(ty);
171     }
172
173     let input_lts = match input_visitor.into_vec() {
174         Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
175         None => return false,
176     };
177     let output_lts = match output_visitor.into_vec() {
178         Some(val) => val,
179         None => return false,
180     };
181
182     if let Some(body_id) = body {
183         let mut checker = BodyLifetimeChecker {
184             lifetimes_used_in_body: false,
185         };
186         checker.visit_expr(&cx.tcx.hir.body(body_id).value);
187         if checker.lifetimes_used_in_body {
188             return false;
189         }
190     }
191
192     // check for lifetimes from higher scopes
193     for lt in input_lts.iter().chain(output_lts.iter()) {
194         if !allowed_lts.contains(lt) {
195             return false;
196         }
197     }
198
199     // no input lifetimes? easy case!
200     if input_lts.is_empty() {
201         false
202     } else if output_lts.is_empty() {
203         // no output lifetimes, check distinctness of input lifetimes
204
205         // only unnamed and static, ok
206         let unnamed_and_static = input_lts
207             .iter()
208             .all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
209         if unnamed_and_static {
210             return false;
211         }
212         // we have no output reference, so we only need all distinct lifetimes
213         input_lts.len() == unique_lifetimes(&input_lts)
214     } else {
215         // we have output references, so we need one input reference,
216         // and all output lifetimes must be the same
217         if unique_lifetimes(&output_lts) > 1 {
218             return false;
219         }
220         if input_lts.len() == 1 {
221             match (&input_lts[0], &output_lts[0]) {
222                 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
223                 (&RefLt::Named(_), &RefLt::Unnamed) => true,
224                 _ => false, /* already elided, different named lifetimes
225                              * or something static going on */
226             }
227         } else {
228             false
229         }
230     }
231 }
232
233 fn allowed_lts_from(named_generics: &[GenericParam]) -> HashSet<RefLt> {
234     let mut allowed_lts = HashSet::new();
235     for par in named_generics.iter() {
236         if let GenericParam::Lifetime(ref lt) = *par {
237             if lt.bounds.is_empty() {
238                 allowed_lts.insert(RefLt::Named(lt.lifetime.name.name()));
239             }
240         }
241     }
242     allowed_lts.insert(RefLt::Unnamed);
243     allowed_lts.insert(RefLt::Static);
244     allowed_lts
245 }
246
247 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
248     for lt in bounds_lts {
249         if lt.name.name() != "'static" {
250             vec.push(RefLt::Named(lt.name.name()));
251         }
252     }
253
254     vec
255 }
256
257 /// Number of unique lifetimes in the given vector.
258 fn unique_lifetimes(lts: &[RefLt]) -> usize {
259     lts.iter().collect::<HashSet<_>>().len()
260 }
261
262 /// A visitor usable for `rustc_front::visit::walk_ty()`.
263 struct RefVisitor<'a, 'tcx: 'a> {
264     cx: &'a LateContext<'a, 'tcx>,
265     lts: Vec<RefLt>,
266     abort: bool,
267 }
268
269 impl<'v, 't> RefVisitor<'v, 't> {
270     fn new(cx: &'v LateContext<'v, 't>) -> Self {
271         Self {
272             cx,
273             lts: Vec::new(),
274             abort: false,
275         }
276     }
277
278     fn record(&mut self, lifetime: &Option<Lifetime>) {
279         if let Some(ref lt) = *lifetime {
280             if lt.name.name() == "'static" {
281                 self.lts.push(RefLt::Static);
282             } else if lt.is_elided() {
283                 self.lts.push(RefLt::Unnamed);
284             } else {
285                 self.lts.push(RefLt::Named(lt.name.name()));
286             }
287         } else {
288             self.lts.push(RefLt::Unnamed);
289         }
290     }
291
292     fn into_vec(self) -> Option<Vec<RefLt>> {
293         if self.abort {
294             None
295         } else {
296             Some(self.lts)
297         }
298     }
299
300     fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
301         if let Some(ref last_path_segment) = last_path_segment(qpath).args {
302             if !last_path_segment.parenthesized && last_path_segment.lifetimes.is_empty() {
303                 let hir_id = self.cx.tcx.hir.node_to_hir_id(ty.id);
304                 match self.cx.tables.qpath_def(qpath, hir_id) {
305                     Def::TyAlias(def_id) | Def::Struct(def_id) => {
306                         let generics = self.cx.tcx.generics_of(def_id);
307                         for _ in generics.params.as_slice() {
308                             self.record(&None);
309                         }
310                     },
311                     Def::Trait(def_id) => {
312                         let trait_def = self.cx.tcx.trait_def(def_id);
313                         for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
314                             self.record(&None);
315                         }
316                     },
317                     _ => (),
318                 }
319             }
320         }
321     }
322 }
323
324 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
325     // for lifetimes as parameters of generics
326     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
327         self.record(&Some(*lifetime));
328     }
329
330     fn visit_ty(&mut self, ty: &'tcx Ty) {
331         match ty.node {
332             TyRptr(ref lt, _) if lt.is_elided() => {
333                 self.record(&None);
334             },
335             TyPath(ref path) => {
336                 self.collect_anonymous_lifetimes(path, ty);
337             },
338             TyImplTraitExistential(exist_ty_id, _, _) => {
339                 if let ItemExistential(ref exist_ty) = self.cx.tcx.hir.expect_item(exist_ty_id.id).node {
340                     for bound in &exist_ty.bounds {
341                         if let GenericBound::Outlives(_) = *bound {
342                             self.record(&None);
343                         }
344                     }
345                 }
346             }
347             TyTraitObject(ref bounds, ref lt) => {
348                 if !lt.is_elided() {
349                     self.abort = true;
350                 }
351                 for bound in bounds {
352                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
353                 }
354                 return;
355             },
356             _ => (),
357         }
358         walk_ty(self, ty);
359     }
360     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
361         NestedVisitorMap::None
362     }
363 }
364
365 /// Are any lifetimes mentioned in the `where` clause? If yes, we don't try to
366 /// reason about elision.
367 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
368     for predicate in &where_clause.predicates {
369         match *predicate {
370             WherePredicate::RegionPredicate(..) => return true,
371             WherePredicate::BoundPredicate(ref pred) => {
372                 // a predicate like F: Trait or F: for<'a> Trait<'a>
373                 let mut visitor = RefVisitor::new(cx);
374                 // walk the type F, it may not contain LT refs
375                 walk_ty(&mut visitor, &pred.bounded_ty);
376                 if !visitor.lts.is_empty() {
377                     return true;
378                 }
379                 // if the bounds define new lifetimes, they are fine to occur
380                 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
381                 // now walk the bounds
382                 for bound in pred.bounds.iter() {
383                     walk_param_bound(&mut visitor, bound);
384                 }
385                 // and check that all lifetimes are allowed
386                 match visitor.into_vec() {
387                     None => return false,
388                     Some(lts) => for lt in lts {
389                         if !allowed_lts.contains(&lt) {
390                             return true;
391                         }
392                     },
393                 }
394             },
395             WherePredicate::EqPredicate(ref pred) => {
396                 let mut visitor = RefVisitor::new(cx);
397                 walk_ty(&mut visitor, &pred.lhs_ty);
398                 walk_ty(&mut visitor, &pred.rhs_ty);
399                 if !visitor.lts.is_empty() {
400                     return true;
401                 }
402             },
403         }
404     }
405     false
406 }
407
408 struct LifetimeChecker {
409     map: HashMap<Name, Span>,
410 }
411
412 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
413     // for lifetimes as parameters of generics
414     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
415         self.map.remove(&lifetime.name.name());
416     }
417
418     fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
419         // don't actually visit `<'a>` or `<'a: 'b>`
420         // we've already visited the `'a` declarations and
421         // don't want to spuriously remove them
422         // `'b` in `'a: 'b` is useless unless used elsewhere in
423         // a non-lifetime bound
424         if let GenericParamKind::Type { .. } = param.kind {
425             walk_generic_param(self, param)
426         }
427     }
428     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
429         NestedVisitorMap::None
430     }
431 }
432
433 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
434     let hs = generics
435         .lifetimes()
436         .map(|lt| (lt.lifetime.name.name(), lt.lifetime.span))
437         .collect();
438     let mut checker = LifetimeChecker { map: hs };
439
440     walk_generics(&mut checker, generics);
441     walk_fn_decl(&mut checker, func);
442
443     for &v in checker.map.values() {
444         span_lint(cx, EXTRA_UNUSED_LIFETIMES, v, "this lifetime isn't used in the function definition");
445     }
446 }
447
448 struct BodyLifetimeChecker {
449     lifetimes_used_in_body: bool,
450 }
451
452 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
453     // for lifetimes as parameters of generics
454     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
455         if lifetime.name.name() != keywords::Invalid.name() && lifetime.name.name() != "'static" {
456             self.lifetimes_used_in_body = true;
457         }
458     }
459
460     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
461         NestedVisitorMap::None
462     }
463 }