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