2 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
3 use rustc::{declare_lint, lint_array};
4 use crate::utils::{in_macro, snippet, span_lint_and_then};
6 /// **What it does:** Checks for constants with an explicit `'static` lifetime.
8 /// **Why is this bad?** Adding `'static` to every reference can create very
11 /// **Known problems:** None.
15 /// const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =
18 /// This code can be rewritten as
20 /// const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]
22 declare_clippy_lint! {
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 match borrow_type.ty.node {
52 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Array(..) |
54 if lifetime.ident.name == "'static" {
55 let snip = snippet(cx, borrow_type.ty.span, "<type>");
56 let sugg = format!("&{}", snip);
59 CONST_STATIC_LIFETIME,
61 "Constants have by default a `'static` lifetime",
63 db.span_suggestion(ty.span, "consider removing `'static`", sugg);
71 self.visit_type(&*borrow_type.ty, cx);
73 TyKind::Slice(ref ty) => {
74 self.visit_type(ty, cx);
81 impl EarlyLintPass for StaticConst {
82 fn check_item(&mut self, cx: &EarlyContext, item: &Item) {
83 if !in_macro(item.span) {
84 // Match only constants...
85 if let ItemKind::Const(ref var_type, _) = item.node {
86 self.visit_type(var_type, cx);
91 // Don't check associated consts because `'static` cannot be elided on those (issue #2438)