1 use syntax::ast::{Item, ItemKind, TyKind, Ty};
2 use rustc::lint::{LintPass, EarlyLintPass, LintArray, EarlyContext};
3 use utils::{span_lint_and_then, in_macro};
5 /// **What it does:** Checks for constants with an explicit `'static` lifetime.
7 /// **Why is this bad?** Adding `'static` to every reference can create very
10 /// **Known problems:** None.
14 /// const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =
17 /// This code can be rewritten as
19 /// const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]
23 pub CONST_STATIC_LIFETIME,
25 "Using explicit `'static` lifetime for constants when elision rules would allow omitting them."
28 pub struct StaticConst;
30 impl LintPass for StaticConst {
31 fn get_lints(&self) -> LintArray {
32 lint_array!(CONST_STATIC_LIFETIME)
37 // Recursively visit types
38 fn visit_type(&mut self, ty: &Ty, cx: &EarlyContext) {
40 // Be careful of nested structures (arrays and tuples)
41 TyKind::Array(ref ty, _) => {
42 self.visit_type(&*ty, cx);
44 TyKind::Tup(ref tup) => {
46 self.visit_type(&*tup_ty, cx);
49 // This is what we are looking for !
50 TyKind::Rptr(ref optional_lifetime, ref borrow_type) => {
51 // Match the 'static lifetime
52 if let Some(lifetime) = *optional_lifetime {
53 if let TyKind::Path(_, _) = borrow_type.ty.node {
54 // Verify that the path is a str
55 if lifetime.ident.name == "'static" {
56 let mut sug: String = String::new();
57 span_lint_and_then(cx,
58 CONST_STATIC_LIFETIME,
60 "Constants have by default a `'static` lifetime",
61 |db| {db.span_suggestion(lifetime.span,"consider removing `'static`",sug);});
65 self.visit_type(&*borrow_type.ty, cx);
67 TyKind::Slice(ref ty) => {
68 self.visit_type(ty, cx);
75 impl EarlyLintPass for StaticConst {
76 fn check_item(&mut self, cx: &EarlyContext, item: &Item) {
77 if !in_macro(item.span) {
78 // Match only constants...
79 if let ItemKind::Const(ref var_type, _) = item.node {
80 self.visit_type(var_type, cx);