1 use crate::utils::{snippet, span_lint_and_then};
2 use rustc::declare_lint_pass;
3 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
4 use rustc_errors::Applicability;
5 use rustc_session::declare_tool_lint;
9 /// **What it does:** Checks for constants and statics with an explicit `'static` lifetime.
11 /// **Why is this bad?** Adding `'static` to every reference can create very
12 /// complicated types.
14 /// **Known problems:** None.
18 /// const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =
20 /// static FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =
23 /// This code can be rewritten as
25 /// const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]
26 /// static FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]
28 pub REDUNDANT_STATIC_LIFETIMES,
30 "Using explicit `'static` lifetime for constants or statics when elision rules would allow omitting them."
33 declare_lint_pass!(RedundantStaticLifetimes => [REDUNDANT_STATIC_LIFETIMES]);
35 impl RedundantStaticLifetimes {
36 // Recursively visit types
37 fn visit_type(&mut self, ty: &Ty, cx: &EarlyContext<'_>, reason: &str) {
39 // Be careful of nested structures (arrays and tuples)
40 TyKind::Array(ref ty, _) => {
41 self.visit_type(&*ty, cx, reason);
43 TyKind::Tup(ref tup) => {
45 self.visit_type(&*tup_ty, cx, reason);
48 // This is what we are looking for !
49 TyKind::Rptr(ref optional_lifetime, ref borrow_type) => {
50 // Match the 'static lifetime
51 if let Some(lifetime) = *optional_lifetime {
52 match borrow_type.ty.kind {
53 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Array(..) | TyKind::Tup(..) => {
54 if lifetime.ident.name == rustc_span::symbol::kw::StaticLifetime {
55 let snip = snippet(cx, borrow_type.ty.span, "<type>");
56 let sugg = format!("&{}", snip);
57 span_lint_and_then(cx, REDUNDANT_STATIC_LIFETIMES, lifetime.ident.span, reason, |db| {
60 "consider removing `'static`",
62 Applicability::MachineApplicable, //snippet
70 self.visit_type(&*borrow_type.ty, cx, reason);
72 TyKind::Slice(ref ty) => {
73 self.visit_type(ty, cx, reason);
80 impl EarlyLintPass for RedundantStaticLifetimes {
81 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
82 if !item.span.from_expansion() {
83 if let ItemKind::Const(ref var_type, _) = item.kind {
84 self.visit_type(var_type, cx, "Constants have by default a `'static` lifetime");
85 // Don't check associated consts because `'static` cannot be elided on those (issue
89 if let ItemKind::Static(ref var_type, _, _) = item.kind {
90 self.visit_type(var_type, cx, "Statics have by default a `'static` lifetime");