]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
Merge pull request #1506 from bood/master
[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
10 /// **What it does:** Checks for lifetime annotations which can be removed by
11 /// relying on lifetime elision.
12 ///
13 /// **Why is this bad?** The additional lifetimes make the code look more
14 /// complicated, while there is nothing out of the ordinary going on. Removing
15 /// them leads to more readable code.
16 ///
17 /// **Known problems:** Potential false negatives: we bail out if the function
18 /// has a `where` clause where lifetimes are mentioned.
19 ///
20 /// **Example:**
21 /// ```rust
22 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 { x }
23 /// ```
24 declare_lint! {
25     pub NEEDLESS_LIFETIMES,
26     Warn,
27     "using explicit lifetimes for references in function arguments when elision rules \
28      would allow omitting them"
29 }
30
31 /// **What it does:** Checks for lifetimes in generics that are never used
32 /// anywhere else.
33 ///
34 /// **Why is this bad?** The additional lifetimes make the code look more
35 /// complicated, while there is nothing out of the ordinary going on. Removing
36 /// them leads to more readable code.
37 ///
38 /// **Known problems:** None.
39 ///
40 /// **Example:**
41 /// ```rust
42 /// fn unused_lifetime<'a>(x: u8) { .. }
43 /// ```
44 declare_lint! {
45     pub UNUSED_LIFETIMES,
46     Warn,
47     "unused lifetimes in function definitions"
48 }
49
50 #[derive(Copy,Clone)]
51 pub struct LifetimePass;
52
53 impl LintPass for LifetimePass {
54     fn get_lints(&self) -> LintArray {
55         lint_array!(NEEDLESS_LIFETIMES, UNUSED_LIFETIMES)
56     }
57 }
58
59 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LifetimePass {
60     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
61         if let ItemFn(ref decl, _, _, _, ref generics, _) = item.node {
62             check_fn_inner(cx, decl, generics, item.span);
63         }
64     }
65
66     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
67         if let ImplItemKind::Method(ref sig, _) = item.node {
68             check_fn_inner(cx, &sig.decl, &sig.generics, item.span);
69         }
70     }
71
72     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
73         if let TraitItemKind::Method(ref sig, _) = item.node {
74             check_fn_inner(cx, &sig.decl, &sig.generics, item.span);
75         }
76     }
77 }
78
79 /// The lifetime of a &-reference.
80 #[derive(PartialEq, Eq, Hash, Debug)]
81 enum RefLt {
82     Unnamed,
83     Static,
84     Named(Name),
85 }
86
87 fn bound_lifetimes(bound: &TyParamBound) -> HirVec<&Lifetime> {
88     if let TraitTyParamBound(ref trait_ref, _) = *bound {
89         trait_ref.trait_ref
90             .path
91             .segments
92             .last()
93             .expect("a path must have at least one segment")
94             .parameters
95             .lifetimes()
96     } else {
97         HirVec::new()
98     }
99 }
100
101 fn check_fn_inner<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl, generics: &'tcx Generics, span: Span) {
102     if in_external_macro(cx, span) || has_where_lifetimes(cx, &generics.where_clause) {
103         return;
104     }
105
106     let bounds_lts = generics.ty_params
107         .iter()
108         .flat_map(|typ| typ.bounds.iter().flat_map(bound_lifetimes));
109
110     if could_use_elision(cx, decl, &generics.lifetimes, bounds_lts) {
111         span_lint(cx,
112                   NEEDLESS_LIFETIMES,
113                   span,
114                   "explicit lifetimes given in parameter types where they could be elided");
115     }
116     report_extra_lifetimes(cx, decl, generics);
117 }
118
119 fn could_use_elision<'a, 'tcx: 'a, T: Iterator<Item = &'tcx Lifetime>>(
120     cx: &LateContext<'a, 'tcx>,
121     func: &'tcx FnDecl,
122     named_lts: &'tcx [LifetimeDef],
123     bounds_lts: T
124 ) -> bool {
125     // There are two scenarios where elision works:
126     // * no output references, all input references have different LT
127     // * output references, exactly one input reference with same LT
128     // All lifetimes must be unnamed, 'static or defined without bounds on the
129     // level of the current item.
130
131     // check named LTs
132     let allowed_lts = allowed_lts_from(named_lts);
133
134     // these will collect all the lifetimes for references in arg/return types
135     let mut input_visitor = RefVisitor::new(cx);
136     let mut output_visitor = RefVisitor::new(cx);
137
138     // extract lifetimes in input argument types
139     for arg in &func.inputs {
140         input_visitor.visit_ty(arg);
141     }
142     // extract lifetimes in output type
143     if let Return(ref ty) = func.output {
144         output_visitor.visit_ty(ty);
145     }
146
147     let input_lts = lts_from_bounds(input_visitor.into_vec(), bounds_lts);
148     let output_lts = output_visitor.into_vec();
149
150     // check for lifetimes from higher scopes
151     for lt in input_lts.iter().chain(output_lts.iter()) {
152         if !allowed_lts.contains(lt) {
153             return false;
154         }
155     }
156
157     // no input lifetimes? easy case!
158     if input_lts.is_empty() {
159         false
160     } else if output_lts.is_empty() {
161         // no output lifetimes, check distinctness of input lifetimes
162
163         // only unnamed and static, ok
164         if input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static) {
165             return false;
166         }
167         // we have no output reference, so we only need all distinct lifetimes
168         input_lts.len() == unique_lifetimes(&input_lts)
169     } else {
170         // we have output references, so we need one input reference,
171         // and all output lifetimes must be the same
172         if unique_lifetimes(&output_lts) > 1 {
173             return false;
174         }
175         if input_lts.len() == 1 {
176             match (&input_lts[0], &output_lts[0]) {
177                 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
178                 (&RefLt::Named(_), &RefLt::Unnamed) => true,
179                 _ => false, // already elided, different named lifetimes
180                 // or something static going on
181             }
182         } else {
183             false
184         }
185     }
186 }
187
188 fn allowed_lts_from(named_lts: &[LifetimeDef]) -> HashSet<RefLt> {
189     let mut allowed_lts = HashSet::new();
190     for lt in named_lts {
191         if lt.bounds.is_empty() {
192             allowed_lts.insert(RefLt::Named(lt.lifetime.name));
193         }
194     }
195     allowed_lts.insert(RefLt::Unnamed);
196     allowed_lts.insert(RefLt::Static);
197     allowed_lts
198 }
199
200 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
201     for lt in bounds_lts {
202         if &*lt.name.as_str() != "'static" {
203             vec.push(RefLt::Named(lt.name));
204         }
205     }
206
207     vec
208 }
209
210 /// Number of unique lifetimes in the given vector.
211 fn unique_lifetimes(lts: &[RefLt]) -> usize {
212     lts.iter().collect::<HashSet<_>>().len()
213 }
214
215 /// A visitor usable for `rustc_front::visit::walk_ty()`.
216 struct RefVisitor<'a, 'tcx: 'a> {
217     cx: &'a LateContext<'a, 'tcx>,
218     lts: Vec<RefLt>,
219 }
220
221 impl<'v, 't> RefVisitor<'v, 't> {
222     fn new(cx: &'v LateContext<'v, 't>) -> RefVisitor<'v, 't> {
223         RefVisitor {
224             cx: cx,
225             lts: Vec::new(),
226         }
227     }
228
229     fn record(&mut self, lifetime: &Option<Lifetime>) {
230         if let Some(ref lt) = *lifetime {
231             if &*lt.name.as_str() == "'static" {
232                 self.lts.push(RefLt::Static);
233             } else if lt.is_elided() {
234                 self.lts.push(RefLt::Unnamed);
235             } else {
236                 self.lts.push(RefLt::Named(lt.name));
237             }
238         } else {
239             self.lts.push(RefLt::Unnamed);
240         }
241     }
242
243     fn into_vec(self) -> Vec<RefLt> {
244         self.lts
245     }
246
247     fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
248         let last_path_segment = &last_path_segment(qpath).parameters;
249         if let AngleBracketedParameters(ref params) = *last_path_segment {
250             if params.lifetimes.is_empty() {
251                 match self.cx.tables.qpath_def(qpath, ty.id) {
252                     Def::TyAlias(def_id) |
253                     Def::Struct(def_id) => {
254                         let generics = self.cx.tcx.item_generics(def_id);
255                         for _ in generics.regions.as_slice() {
256                             self.record(&None);
257                         }
258                     },
259                     Def::Trait(def_id) => {
260                         let trait_def = self.cx.tcx.trait_defs.borrow()[&def_id];
261                         for _ in &self.cx.tcx.item_generics(trait_def.def_id).regions {
262                             self.record(&None);
263                         }
264                     },
265                     _ => (),
266                 }
267             }
268         }
269     }
270 }
271
272 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
273     // for lifetimes as parameters of generics
274     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
275         self.record(&Some(*lifetime));
276     }
277
278     fn visit_ty(&mut self, ty: &'tcx Ty) {
279         match ty.node {
280             TyRptr(ref lt, _) if lt.is_elided() => {
281                 self.record(&None);
282             },
283             TyPath(ref path) => {
284                 self.collect_anonymous_lifetimes(path, ty);
285             },
286             TyImplTrait(ref param_bounds) => {
287                 for bound in param_bounds {
288                     if let RegionTyParamBound(_) = *bound {
289                         self.record(&None);
290                     }
291                 }
292             },
293             TyTraitObject(ref bounds, ref lt) => {
294                 if !lt.is_elided() {
295                     self.record(&Some(*lt));
296                 }
297                 for bound in bounds {
298                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
299                 }
300                 return;
301             },
302             _ => (),
303         }
304         walk_ty(self, ty);
305     }
306     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
307         NestedVisitorMap::None
308     }
309 }
310
311 /// Are any lifetimes mentioned in the `where` clause? If yes, we don't try to
312 /// reason about elision.
313 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
314     for predicate in &where_clause.predicates {
315         match *predicate {
316             WherePredicate::RegionPredicate(..) => return true,
317             WherePredicate::BoundPredicate(ref pred) => {
318                 // a predicate like F: Trait or F: for<'a> Trait<'a>
319                 let mut visitor = RefVisitor::new(cx);
320                 // walk the type F, it may not contain LT refs
321                 walk_ty(&mut visitor, &pred.bounded_ty);
322                 if !visitor.lts.is_empty() {
323                     return true;
324                 }
325                 // if the bounds define new lifetimes, they are fine to occur
326                 let allowed_lts = allowed_lts_from(&pred.bound_lifetimes);
327                 // now walk the bounds
328                 for bound in pred.bounds.iter() {
329                     walk_ty_param_bound(&mut visitor, bound);
330                 }
331                 // and check that all lifetimes are allowed
332                 for lt in visitor.into_vec() {
333                     if !allowed_lts.contains(&lt) {
334                         return true;
335                     }
336                 }
337             },
338             WherePredicate::EqPredicate(ref pred) => {
339                 let mut visitor = RefVisitor::new(cx);
340                 walk_ty(&mut visitor, &pred.lhs_ty);
341                 walk_ty(&mut visitor, &pred.rhs_ty);
342                 if !visitor.lts.is_empty() {
343                     return true;
344                 }
345             },
346         }
347     }
348     false
349 }
350
351 struct LifetimeChecker {
352     map: HashMap<Name, Span>,
353 }
354
355 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
356     // for lifetimes as parameters of generics
357     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
358         self.map.remove(&lifetime.name);
359     }
360
361     fn visit_lifetime_def(&mut self, _: &'tcx LifetimeDef) {
362         // don't actually visit `<'a>` or `<'a: 'b>`
363         // we've already visited the `'a` declarations and
364         // don't want to spuriously remove them
365         // `'b` in `'a: 'b` is useless unless used elsewhere in
366         // a non-lifetime bound
367     }
368     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
369         NestedVisitorMap::None
370     }
371 }
372
373 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
374     let hs = generics.lifetimes
375         .iter()
376         .map(|lt| (lt.lifetime.name, lt.lifetime.span))
377         .collect();
378     let mut checker = LifetimeChecker { map: hs };
379
380     walk_generics(&mut checker, generics);
381     walk_fn_decl(&mut checker, func);
382
383     for &v in checker.map.values() {
384         span_lint(cx, UNUSED_LIFETIMES, v, "this lifetime isn't used in the function definition");
385     }
386 }