1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
11 use crate::rustc::{declare_tool_lint, lint_array};
12 use crate::rustc_errors::Applicability;
13 use crate::syntax::ast::*;
14 use crate::utils::{in_macro, snippet, span_lint_and_then};
16 /// **What it does:** Checks for constants with an explicit `'static` lifetime.
18 /// **Why is this bad?** Adding `'static` to every reference can create very
19 /// complicated types.
21 /// **Known problems:** None.
25 /// const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =
28 /// This code can be rewritten as
30 /// const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]
32 declare_clippy_lint! {
33 pub CONST_STATIC_LIFETIME,
35 "Using explicit `'static` lifetime for constants when elision rules would allow omitting them."
38 pub struct StaticConst;
40 impl LintPass for StaticConst {
41 fn get_lints(&self) -> LintArray {
42 lint_array!(CONST_STATIC_LIFETIME)
47 // Recursively visit types
48 fn visit_type(&mut self, ty: &Ty, cx: &EarlyContext<'_>) {
50 // Be careful of nested structures (arrays and tuples)
51 TyKind::Array(ref ty, _) => {
52 self.visit_type(&*ty, cx);
54 TyKind::Tup(ref tup) => {
56 self.visit_type(&*tup_ty, cx);
59 // This is what we are looking for !
60 TyKind::Rptr(ref optional_lifetime, ref borrow_type) => {
61 // Match the 'static lifetime
62 if let Some(lifetime) = *optional_lifetime {
63 match borrow_type.ty.node {
64 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Array(..) | TyKind::Tup(..) => {
65 if lifetime.ident.name == "'static" {
66 let snip = snippet(cx, borrow_type.ty.span, "<type>");
67 let sugg = format!("&{}", snip);
70 CONST_STATIC_LIFETIME,
72 "Constants have by default a `'static` lifetime",
74 db.span_suggestion_with_applicability(
76 "consider removing `'static`",
78 Applicability::MachineApplicable, //snippet
87 self.visit_type(&*borrow_type.ty, cx);
89 TyKind::Slice(ref ty) => {
90 self.visit_type(ty, cx);
97 impl EarlyLintPass for StaticConst {
98 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
99 if !in_macro(item.span) {
100 // Match only constants...
101 if let ItemKind::Const(ref var_type, _) = item.node {
102 self.visit_type(var_type, cx);
107 // Don't check associated consts because `'static` cannot be elided on those (issue #2438)