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