]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
rustup to rustc 1.16.0-nightly (c07a6ae77 2017-01-17)
[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 {
234                 self.lts.push(RefLt::Named(lt.name));
235             }
236         } else {
237             self.lts.push(RefLt::Unnamed);
238         }
239     }
240
241     fn into_vec(self) -> Vec<RefLt> {
242         self.lts
243     }
244
245     fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
246         let last_path_segment = &last_path_segment(qpath).parameters;
247         if let AngleBracketedParameters(ref params) = *last_path_segment {
248             if params.lifetimes.is_empty() {
249                 match self.cx.tables.qpath_def(qpath, ty.id) {
250                     Def::TyAlias(def_id) |
251                     Def::Struct(def_id) => {
252                         let generics = self.cx.tcx.item_generics(def_id);
253                         for _ in generics.regions.as_slice() {
254                             self.record(&None);
255                         }
256                     },
257                     Def::Trait(def_id) => {
258                         let trait_def = self.cx.tcx.trait_defs.borrow()[&def_id];
259                         for _ in &self.cx.tcx.item_generics(trait_def.def_id).regions {
260                             self.record(&None);
261                         }
262                     },
263                     _ => (),
264                 }
265             }
266         }
267     }
268 }
269
270 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
271     // for lifetimes as parameters of generics
272     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
273         self.record(&Some(*lifetime));
274     }
275
276     fn visit_ty(&mut self, ty: &'tcx Ty) {
277         match ty.node {
278             TyRptr(None, _) => {
279                 self.record(&None);
280             },
281             TyPath(ref path) => {
282                 self.collect_anonymous_lifetimes(path, ty);
283             },
284             TyImplTrait(ref param_bounds) => {
285                 for bound in param_bounds {
286                     if let RegionTyParamBound(_) = *bound {
287                         self.record(&None);
288                     }
289                 }
290             },
291             _ => (),
292         }
293         walk_ty(self, ty);
294     }
295     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
296         NestedVisitorMap::None
297     }
298 }
299
300 /// Are any lifetimes mentioned in the `where` clause? If yes, we don't try to
301 /// reason about elision.
302 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
303     for predicate in &where_clause.predicates {
304         match *predicate {
305             WherePredicate::RegionPredicate(..) => return true,
306             WherePredicate::BoundPredicate(ref pred) => {
307                 // a predicate like F: Trait or F: for<'a> Trait<'a>
308                 let mut visitor = RefVisitor::new(cx);
309                 // walk the type F, it may not contain LT refs
310                 walk_ty(&mut visitor, &pred.bounded_ty);
311                 if !visitor.lts.is_empty() {
312                     return true;
313                 }
314                 // if the bounds define new lifetimes, they are fine to occur
315                 let allowed_lts = allowed_lts_from(&pred.bound_lifetimes);
316                 // now walk the bounds
317                 for bound in pred.bounds.iter() {
318                     walk_ty_param_bound(&mut visitor, bound);
319                 }
320                 // and check that all lifetimes are allowed
321                 for lt in visitor.into_vec() {
322                     if !allowed_lts.contains(&lt) {
323                         return true;
324                     }
325                 }
326             },
327             WherePredicate::EqPredicate(ref pred) => {
328                 let mut visitor = RefVisitor::new(cx);
329                 walk_ty(&mut visitor, &pred.lhs_ty);
330                 walk_ty(&mut visitor, &pred.rhs_ty);
331                 if !visitor.lts.is_empty() {
332                     return true;
333                 }
334             },
335         }
336     }
337     false
338 }
339
340 struct LifetimeChecker {
341     map: HashMap<Name, Span>,
342 }
343
344 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
345     // for lifetimes as parameters of generics
346     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
347         self.map.remove(&lifetime.name);
348     }
349
350     fn visit_lifetime_def(&mut self, _: &'tcx LifetimeDef) {
351         // don't actually visit `<'a>` or `<'a: 'b>`
352         // we've already visited the `'a` declarations and
353         // don't want to spuriously remove them
354         // `'b` in `'a: 'b` is useless unless used elsewhere in
355         // a non-lifetime bound
356     }
357     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
358         NestedVisitorMap::None
359     }
360 }
361
362 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
363     let hs = generics.lifetimes
364         .iter()
365         .map(|lt| (lt.lifetime.name, lt.lifetime.span))
366         .collect();
367     let mut checker = LifetimeChecker { map: hs };
368
369     walk_generics(&mut checker, generics);
370     walk_fn_decl(&mut checker, func);
371
372     for &v in checker.map.values() {
373         span_lint(cx, UNUSED_LIFETIMES, v, "this lifetime isn't used in the function definition");
374     }
375 }