Skip to content

Commit e7949d0

Browse files
committed
Warn when using a 'static lifetime bound
Previously a `'static` lifetime bound would result in an `undeclared lifetime` error when compiling, even though it could be considered valid. However, it is unnecessary to use it as a lifetime bound so we present the user with a warning instead and suggest using the `'static` lifetime directly, in place of the lifetime parameter.
1 parent 1ae1a19 commit e7949d0

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/librustc/middle/resolve_lifetime.rs

+12-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use syntax::ast;
2929
use syntax::attr;
3030
use syntax::ptr::P;
3131
use syntax::symbol::keywords;
32-
use syntax_pos::Span;
32+
use syntax_pos::{mk_sp, Span};
3333
use errors::DiagnosticBuilder;
3434
use util::nodemap::{NodeMap, NodeSet, FxHashSet, FxHashMap, DefIdMap};
3535
use rustc_back::slice;
@@ -1464,7 +1464,17 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
14641464
self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime);
14651465

14661466
for bound in &lifetime_i.bounds {
1467-
self.resolve_lifetime_ref(bound);
1467+
if !bound.is_static() {
1468+
self.resolve_lifetime_ref(bound);
1469+
} else {
1470+
self.insert_lifetime(bound, Region::Static);
1471+
let full_span = mk_sp(lifetime_i.lifetime.span.lo, bound.span.hi);
1472+
self.sess.struct_span_warn(full_span,
1473+
&format!("unnecessary lifetime parameter `{}`", lifetime_i.lifetime.name))
1474+
.help(&format!("you can use the `'static` lifetime directly, in place \
1475+
of `{}`", lifetime_i.lifetime.name))
1476+
.emit();
1477+
}
14681478
}
14691479
}
14701480
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
fn f<'a: 'static>(_: &'a i32) {} //~WARN unnecessary lifetime parameter `'a`
12+
13+
fn main() {
14+
let x = 0;
15+
f(&x); //~ERROR does not live long enough
16+
}

0 commit comments

Comments
 (0)