]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lifetimes.rs
Switch to declare_tool_lint macro
[rust.git] / clippy_lints / src / lifetimes.rs
1 use crate::reexport::*;
2 use matches::matches;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, LintContext};
4 use rustc::{declare_tool_lint, lint_array};
5 use rustc::hir::def::Def;
6 use rustc::hir::*;
7 use rustc::hir::intravisit::*;
8 use std::collections::{HashMap, HashSet};
9 use syntax::source_map::Span;
10 use crate::utils::{last_path_segment, span_lint};
11 use syntax::symbol::keywords;
12
13 /// **What it does:** Checks for lifetime annotations which can be removed by
14 /// relying on lifetime elision.
15 ///
16 /// **Why is this bad?** The additional lifetimes make the code look more
17 /// complicated, while there is nothing out of the ordinary going on. Removing
18 /// them leads to more readable code.
19 ///
20 /// **Known problems:** Potential false negatives: we bail out if the function
21 /// has a `where` clause where lifetimes are mentioned.
22 ///
23 /// **Example:**
24 /// ```rust
25 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 { x }
26 /// ```
27 declare_clippy_lint! {
28     pub NEEDLESS_LIFETIMES,
29     complexity,
30     "using explicit lifetimes for references in function arguments when elision rules \
31      would allow omitting them"
32 }
33
34 /// **What it does:** Checks for lifetimes in generics that are never used
35 /// anywhere else.
36 ///
37 /// **Why is this bad?** The additional lifetimes make the code look more
38 /// complicated, while there is nothing out of the ordinary going on. Removing
39 /// them leads to more readable code.
40 ///
41 /// **Known problems:** None.
42 ///
43 /// **Example:**
44 /// ```rust
45 /// fn unused_lifetime<'a>(x: u8) { .. }
46 /// ```
47 declare_clippy_lint! {
48     pub EXTRA_UNUSED_LIFETIMES,
49     complexity,
50     "unused lifetimes in function definitions"
51 }
52
53 #[derive(Copy, Clone)]
54 pub struct LifetimePass;
55
56 impl LintPass for LifetimePass {
57     fn get_lints(&self) -> LintArray {
58         lint_array!(NEEDLESS_LIFETIMES, EXTRA_UNUSED_LIFETIMES)
59     }
60 }
61
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LifetimePass {
63     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
64         if let ItemKind::Fn(ref decl, _, ref generics, id) = item.node {
65             check_fn_inner(cx, decl, Some(id), generics, item.span);
66         }
67     }
68
69     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
70         if let ImplItemKind::Method(ref sig, id) = item.node {
71             check_fn_inner(cx, &sig.decl, Some(id), &item.generics, item.span);
72         }
73     }
74
75     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
76         if let TraitItemKind::Method(ref sig, ref body) = item.node {
77             let body = match *body {
78                 TraitMethod::Required(_) => None,
79                 TraitMethod::Provided(id) => Some(id),
80             };
81             check_fn_inner(cx, &sig.decl, body, &item.generics, item.span);
82         }
83     }
84 }
85
86 /// The lifetime of a &-reference.
87 #[derive(PartialEq, Eq, Hash, Debug)]
88 enum RefLt {
89     Unnamed,
90     Static,
91     Named(Name),
92 }
93
94 fn check_fn_inner<'a, 'tcx>(
95     cx: &LateContext<'a, 'tcx>,
96     decl: &'tcx FnDecl,
97     body: Option<BodyId>,
98     generics: &'tcx Generics,
99     span: Span,
100 ) {
101     if in_external_macro(cx.sess(), span) || has_where_lifetimes(cx, &generics.where_clause) {
102         return;
103     }
104
105     let mut bounds_lts = Vec::new();
106     let types = generics.params.iter().filter_map(|param| match param.kind {
107         GenericParamKind::Type { .. } => Some(param),
108         GenericParamKind::Lifetime { .. } => None,
109     });
110     for typ in types {
111         for bound in &typ.bounds {
112             let mut visitor = RefVisitor::new(cx);
113             walk_param_bound(&mut visitor, bound);
114             if visitor.lts.iter().any(|lt| matches!(lt, RefLt::Named(_))) {
115                 return;
116             }
117             if let GenericBound::Trait(ref trait_ref, _) = *bound {
118                 let params = &trait_ref
119                     .trait_ref
120                     .path
121                     .segments
122                     .last()
123                     .expect("a path must have at least one segment")
124                     .args;
125                 if let Some(ref params) = *params {
126                     let lifetimes = params.args.iter().filter_map(|arg| match arg {
127                         GenericArg::Lifetime(lt) => Some(lt),
128                         GenericArg::Type(_) => None,
129                     });
130                     for bound in lifetimes {
131                         if bound.name != LifetimeName::Static && !bound.is_elided() {
132                             return;
133                         }
134                         bounds_lts.push(bound);
135                     }
136                 }
137             }
138         }
139     }
140     if could_use_elision(cx, decl, body, &generics.params, bounds_lts) {
141         span_lint(
142             cx,
143             NEEDLESS_LIFETIMES,
144             span,
145             "explicit lifetimes given in parameter types where they could be elided",
146         );
147     }
148     report_extra_lifetimes(cx, decl, generics);
149 }
150
151 fn could_use_elision<'a, 'tcx: 'a>(
152     cx: &LateContext<'a, 'tcx>,
153     func: &'tcx FnDecl,
154     body: Option<BodyId>,
155     named_generics: &'tcx [GenericParam],
156     bounds_lts: Vec<&'tcx Lifetime>,
157 ) -> bool {
158     // There are two scenarios where elision works:
159     // * no output references, all input references have different LT
160     // * output references, exactly one input reference with same LT
161     // All lifetimes must be unnamed, 'static or defined without bounds on the
162     // level of the current item.
163
164     // check named LTs
165     let allowed_lts = allowed_lts_from(named_generics);
166
167     // these will collect all the lifetimes for references in arg/return types
168     let mut input_visitor = RefVisitor::new(cx);
169     let mut output_visitor = RefVisitor::new(cx);
170
171     // extract lifetimes in input argument types
172     for arg in &func.inputs {
173         input_visitor.visit_ty(arg);
174     }
175     // extract lifetimes in output type
176     if let Return(ref ty) = func.output {
177         output_visitor.visit_ty(ty);
178     }
179
180     let input_lts = match input_visitor.into_vec() {
181         Some(lts) => lts_from_bounds(lts, bounds_lts.into_iter()),
182         None => return false,
183     };
184     let output_lts = match output_visitor.into_vec() {
185         Some(val) => val,
186         None => return false,
187     };
188
189     if let Some(body_id) = body {
190         let mut checker = BodyLifetimeChecker {
191             lifetimes_used_in_body: false,
192         };
193         checker.visit_expr(&cx.tcx.hir.body(body_id).value);
194         if checker.lifetimes_used_in_body {
195             return false;
196         }
197     }
198
199     // check for lifetimes from higher scopes
200     for lt in input_lts.iter().chain(output_lts.iter()) {
201         if !allowed_lts.contains(lt) {
202             return false;
203         }
204     }
205
206     // no input lifetimes? easy case!
207     if input_lts.is_empty() {
208         false
209     } else if output_lts.is_empty() {
210         // no output lifetimes, check distinctness of input lifetimes
211
212         // only unnamed and static, ok
213         let unnamed_and_static = input_lts
214             .iter()
215             .all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
216         if unnamed_and_static {
217             return false;
218         }
219         // we have no output reference, so we only need all distinct lifetimes
220         input_lts.len() == unique_lifetimes(&input_lts)
221     } else {
222         // we have output references, so we need one input reference,
223         // and all output lifetimes must be the same
224         if unique_lifetimes(&output_lts) > 1 {
225             return false;
226         }
227         if input_lts.len() == 1 {
228             match (&input_lts[0], &output_lts[0]) {
229                 (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
230                 (&RefLt::Named(_), &RefLt::Unnamed) => true,
231                 _ => false, /* already elided, different named lifetimes
232                              * or something static going on */
233             }
234         } else {
235             false
236         }
237     }
238 }
239
240 fn allowed_lts_from(named_generics: &[GenericParam]) -> HashSet<RefLt> {
241     let mut allowed_lts = HashSet::new();
242     for par in named_generics.iter() {
243         if let GenericParamKind::Lifetime { .. } = par.kind {
244             if par.bounds.is_empty() {
245                 allowed_lts.insert(RefLt::Named(par.name.ident().name));
246             }
247         }
248     }
249     allowed_lts.insert(RefLt::Unnamed);
250     allowed_lts.insert(RefLt::Static);
251     allowed_lts
252 }
253
254 fn lts_from_bounds<'a, T: Iterator<Item = &'a Lifetime>>(mut vec: Vec<RefLt>, bounds_lts: T) -> Vec<RefLt> {
255     for lt in bounds_lts {
256         if lt.name != LifetimeName::Static {
257             vec.push(RefLt::Named(lt.name.ident().name));
258         }
259     }
260
261     vec
262 }
263
264 /// Number of unique lifetimes in the given vector.
265 fn unique_lifetimes(lts: &[RefLt]) -> usize {
266     lts.iter().collect::<HashSet<_>>().len()
267 }
268
269 /// A visitor usable for `rustc_front::visit::walk_ty()`.
270 struct RefVisitor<'a, 'tcx: 'a> {
271     cx: &'a LateContext<'a, 'tcx>,
272     lts: Vec<RefLt>,
273     abort: bool,
274 }
275
276 impl<'v, 't> RefVisitor<'v, 't> {
277     fn new(cx: &'v LateContext<'v, 't>) -> Self {
278         Self {
279             cx,
280             lts: Vec::new(),
281             abort: false,
282         }
283     }
284
285     fn record(&mut self, lifetime: &Option<Lifetime>) {
286         if let Some(ref lt) = *lifetime {
287             if lt.name == LifetimeName::Static {
288                 self.lts.push(RefLt::Static);
289             } else if lt.is_elided() {
290                 self.lts.push(RefLt::Unnamed);
291             } else {
292                 self.lts.push(RefLt::Named(lt.name.ident().name));
293             }
294         } else {
295             self.lts.push(RefLt::Unnamed);
296         }
297     }
298
299     fn into_vec(self) -> Option<Vec<RefLt>> {
300         if self.abort {
301             None
302         } else {
303             Some(self.lts)
304         }
305     }
306
307     fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
308         if let Some(ref last_path_segment) = last_path_segment(qpath).args {
309             if !last_path_segment.parenthesized
310                 && !last_path_segment.args.iter().any(|arg| match arg {
311                     GenericArg::Lifetime(_) => true,
312                     GenericArg::Type(_) => false,
313                 }) {
314                 let hir_id = self.cx.tcx.hir.node_to_hir_id(ty.id);
315                 match self.cx.tables.qpath_def(qpath, hir_id) {
316                     Def::TyAlias(def_id) | Def::Struct(def_id) => {
317                         let generics = self.cx.tcx.generics_of(def_id);
318                         for _ in generics.params.as_slice() {
319                             self.record(&None);
320                         }
321                     },
322                     Def::Trait(def_id) => {
323                         let trait_def = self.cx.tcx.trait_def(def_id);
324                         for _ in &self.cx.tcx.generics_of(trait_def.def_id).params {
325                             self.record(&None);
326                         }
327                     },
328                     _ => (),
329                 }
330             }
331         }
332     }
333 }
334
335 impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
336     // for lifetimes as parameters of generics
337     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
338         self.record(&Some(*lifetime));
339     }
340
341     fn visit_ty(&mut self, ty: &'tcx Ty) {
342         match ty.node {
343             TyKind::Rptr(ref lt, _) if lt.is_elided() => {
344                 self.record(&None);
345             },
346             TyKind::Path(ref path) => {
347                 if let QPath::Resolved(_, ref path) = *path {
348                     if let Def::Existential(def_id) = path.def {
349                         let node_id = self.cx.tcx.hir.as_local_node_id(def_id).unwrap();
350                         if let ItemKind::Existential(ref exist_ty) = self.cx.tcx.hir.expect_item(node_id).node {
351                             for bound in &exist_ty.bounds {
352                                 if let GenericBound::Outlives(_) = *bound {
353                                     self.record(&None);
354                                 }
355                             }
356                         } else {
357                             unreachable!()
358                         }
359                         walk_ty(self, ty);
360                         return;
361                     }
362                 }
363                 self.collect_anonymous_lifetimes(path, ty);
364             }
365             TyKind::TraitObject(ref bounds, ref lt) => {
366                 if !lt.is_elided() {
367                     self.abort = true;
368                 }
369                 for bound in bounds {
370                     self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
371                 }
372                 return;
373             },
374             _ => (),
375         }
376         walk_ty(self, ty);
377     }
378     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
379         NestedVisitorMap::None
380     }
381 }
382
383 /// Are any lifetimes mentioned in the `where` clause? If yes, we don't try to
384 /// reason about elision.
385 fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &'tcx WhereClause) -> bool {
386     for predicate in &where_clause.predicates {
387         match *predicate {
388             WherePredicate::RegionPredicate(..) => return true,
389             WherePredicate::BoundPredicate(ref pred) => {
390                 // a predicate like F: Trait or F: for<'a> Trait<'a>
391                 let mut visitor = RefVisitor::new(cx);
392                 // walk the type F, it may not contain LT refs
393                 walk_ty(&mut visitor, &pred.bounded_ty);
394                 if !visitor.lts.is_empty() {
395                     return true;
396                 }
397                 // if the bounds define new lifetimes, they are fine to occur
398                 let allowed_lts = allowed_lts_from(&pred.bound_generic_params);
399                 // now walk the bounds
400                 for bound in pred.bounds.iter() {
401                     walk_param_bound(&mut visitor, bound);
402                 }
403                 // and check that all lifetimes are allowed
404                 match visitor.into_vec() {
405                     None => return false,
406                     Some(lts) => for lt in lts {
407                         if !allowed_lts.contains(&lt) {
408                             return true;
409                         }
410                     },
411                 }
412             },
413             WherePredicate::EqPredicate(ref pred) => {
414                 let mut visitor = RefVisitor::new(cx);
415                 walk_ty(&mut visitor, &pred.lhs_ty);
416                 walk_ty(&mut visitor, &pred.rhs_ty);
417                 if !visitor.lts.is_empty() {
418                     return true;
419                 }
420             },
421         }
422     }
423     false
424 }
425
426 struct LifetimeChecker {
427     map: HashMap<Name, Span>,
428 }
429
430 impl<'tcx> Visitor<'tcx> for LifetimeChecker {
431     // for lifetimes as parameters of generics
432     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
433         self.map.remove(&lifetime.name.ident().name);
434     }
435
436     fn visit_generic_param(&mut self, param: &'tcx GenericParam) {
437         // don't actually visit `<'a>` or `<'a: 'b>`
438         // we've already visited the `'a` declarations and
439         // don't want to spuriously remove them
440         // `'b` in `'a: 'b` is useless unless used elsewhere in
441         // a non-lifetime bound
442         if let GenericParamKind::Type { .. } = param.kind {
443             walk_generic_param(self, param)
444         }
445     }
446     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
447         NestedVisitorMap::None
448     }
449 }
450
451 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
452     let hs = generics.params.iter()
453         .filter_map(|par| match par.kind {
454             GenericParamKind::Lifetime { .. } => Some((par.name.ident().name, par.span)),
455             _ => None,
456         })
457         .collect();
458     let mut checker = LifetimeChecker { map: hs };
459
460     walk_generics(&mut checker, generics);
461     walk_fn_decl(&mut checker, func);
462
463     for &v in checker.map.values() {
464         span_lint(cx, EXTRA_UNUSED_LIFETIMES, v, "this lifetime isn't used in the function definition");
465     }
466 }
467
468 struct BodyLifetimeChecker {
469     lifetimes_used_in_body: bool,
470 }
471
472 impl<'tcx> Visitor<'tcx> for BodyLifetimeChecker {
473     // for lifetimes as parameters of generics
474     fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) {
475         if lifetime.name.ident().name != keywords::Invalid.name() && lifetime.name.ident().name != "'static" {
476             self.lifetimes_used_in_body = true;
477         }
478     }
479
480     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
481         NestedVisitorMap::None
482     }
483 }