3 use rustc::hir::def::Def;
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};
10 /// **What it does:** Checks for lifetime annotations which can be removed by
11 /// relying on lifetime elision.
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.
17 /// **Known problems:** Potential false negatives: we bail out if the function
18 /// has a `where` clause where lifetimes are mentioned.
22 /// fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 { x }
25 pub NEEDLESS_LIFETIMES,
27 "using explicit lifetimes for references in function arguments when elision rules \
28 would allow omitting them"
31 /// **What it does:** Checks for lifetimes in generics that are never used
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.
38 /// **Known problems:** None.
42 /// fn unused_lifetime<'a>(x: u8) { .. }
47 "unused lifetimes in function definitions"
51 pub struct LifetimePass;
53 impl LintPass for LifetimePass {
54 fn get_lints(&self) -> LintArray {
55 lint_array!(NEEDLESS_LIFETIMES, UNUSED_LIFETIMES)
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);
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);
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);
79 /// The lifetime of a &-reference.
80 #[derive(PartialEq, Eq, Hash, Debug)]
87 fn bound_lifetimes(bound: &TyParamBound) -> HirVec<&Lifetime> {
88 if let TraitTyParamBound(ref trait_ref, _) = *bound {
93 .expect("a path must have at least one segment")
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) {
106 let bounds_lts = generics.ty_params
108 .flat_map(|typ| typ.bounds.iter().flat_map(bound_lifetimes));
110 if could_use_elision(cx, decl, &generics.lifetimes, bounds_lts) {
114 "explicit lifetimes given in parameter types where they could be elided");
116 report_extra_lifetimes(cx, decl, generics);
119 fn could_use_elision<'a, 'tcx: 'a, T: Iterator<Item = &'tcx Lifetime>>(
120 cx: &LateContext<'a, 'tcx>,
122 named_lts: &'tcx [LifetimeDef],
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.
132 let allowed_lts = allowed_lts_from(named_lts);
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);
138 // extract lifetimes in input argument types
139 for arg in &func.inputs {
140 input_visitor.visit_ty(arg);
142 // extract lifetimes in output type
143 if let Return(ref ty) = func.output {
144 output_visitor.visit_ty(ty);
147 let input_lts = lts_from_bounds(input_visitor.into_vec(), bounds_lts);
148 let output_lts = output_visitor.into_vec();
150 // check for lifetimes from higher scopes
151 for lt in input_lts.iter().chain(output_lts.iter()) {
152 if !allowed_lts.contains(lt) {
157 // no input lifetimes? easy case!
158 if input_lts.is_empty() {
160 } else if output_lts.is_empty() {
161 // no output lifetimes, check distinctness of input lifetimes
163 // only unnamed and static, ok
164 if input_lts.iter().all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static) {
167 // we have no output reference, so we only need all distinct lifetimes
168 input_lts.len() == unique_lifetimes(&input_lts)
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 {
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
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));
195 allowed_lts.insert(RefLt::Unnamed);
196 allowed_lts.insert(RefLt::Static);
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));
210 /// Number of unique lifetimes in the given vector.
211 fn unique_lifetimes(lts: &[RefLt]) -> usize {
212 lts.iter().collect::<HashSet<_>>().len()
215 /// A visitor usable for `rustc_front::visit::walk_ty()`.
216 struct RefVisitor<'a, 'tcx: 'a> {
217 cx: &'a LateContext<'a, 'tcx>,
221 impl<'v, 't> RefVisitor<'v, 't> {
222 fn new(cx: &'v LateContext<'v, 't>) -> RefVisitor<'v, 't> {
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);
236 self.lts.push(RefLt::Named(lt.name));
239 self.lts.push(RefLt::Unnamed);
243 fn into_vec(self) -> Vec<RefLt> {
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() {
259 Def::Trait(def_id) => {
260 let trait_def = self.cx.tcx.maps.trait_def.borrow()[&def_id];
261 for _ in &self.cx.tcx.item_generics(trait_def.def_id).regions {
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));
278 fn visit_ty(&mut self, ty: &'tcx Ty) {
280 TyRptr(ref lt, _) if lt.is_elided() => {
283 TyPath(ref path) => {
284 self.collect_anonymous_lifetimes(path, ty);
286 TyImplTrait(ref param_bounds) => {
287 for bound in param_bounds {
288 if let RegionTyParamBound(_) = *bound {
293 TyTraitObject(ref bounds, ref lt) => {
295 self.record(&Some(*lt));
297 for bound in bounds {
298 self.visit_poly_trait_ref(bound, TraitBoundModifier::None);
306 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
307 NestedVisitorMap::None
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 {
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() {
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);
331 // and check that all lifetimes are allowed
332 for lt in visitor.into_vec() {
333 if !allowed_lts.contains(<) {
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() {
351 struct LifetimeChecker {
352 map: HashMap<Name, Span>,
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);
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
368 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
369 NestedVisitorMap::None
373 fn report_extra_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, func: &'tcx FnDecl, generics: &'tcx Generics) {
374 let hs = generics.lifetimes
376 .map(|lt| (lt.lifetime.name, lt.lifetime.span))
378 let mut checker = LifetimeChecker { map: hs };
380 walk_generics(&mut checker, generics);
381 walk_fn_decl(&mut checker, func);
383 for &v in checker.map.values() {
384 span_lint(cx, UNUSED_LIFETIMES, v, "this lifetime isn't used in the function definition");