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