1 use syntax::ast::{Item, ItemKind, Ty, TyKind};
2 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
3 use utils::{in_macro, span_lint_and_then};
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) => for tup_ty in tup {
45 self.visit_type(&*tup_ty, cx);
47 // This is what we are looking for !
48 TyKind::Rptr(ref optional_lifetime, ref borrow_type) => {
49 // Match the 'static lifetime
50 if let Some(lifetime) = *optional_lifetime {
51 if let TyKind::Path(_, _) = borrow_type.ty.node {
52 // Verify that the path is a str
53 if lifetime.ident.name == "'static" {
54 let mut sug: String = String::new();
57 CONST_STATIC_LIFETIME,
59 "Constants have by default a `'static` lifetime",
61 db.span_suggestion(lifetime.span, "consider removing `'static`", sug);
67 self.visit_type(&*borrow_type.ty, cx);
69 TyKind::Slice(ref ty) => {
70 self.visit_type(ty, cx);
77 impl EarlyLintPass for StaticConst {
78 fn check_item(&mut self, cx: &EarlyContext, item: &Item) {
79 if !in_macro(item.span) {
80 // Match only constants...
81 if let ItemKind::Const(ref var_type, _) = item.node {
82 self.visit_type(var_type, cx);