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.
11 use crate::syntax::ast::*;
12 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::utils::{in_macro, snippet, span_lint_and_then};
15 use crate::rustc_errors::Applicability;
17 /// **What it does:** Checks for constants with an explicit `'static` lifetime.
19 /// **Why is this bad?** Adding `'static` to every reference can create very
20 /// complicated types.
22 /// **Known problems:** None.
26 /// const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =
29 /// This code can be rewritten as
31 /// const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]
33 declare_clippy_lint! {
34 pub CONST_STATIC_LIFETIME,
36 "Using explicit `'static` lifetime for constants when elision rules would allow omitting them."
39 pub struct StaticConst;
41 impl LintPass for StaticConst {
42 fn get_lints(&self) -> LintArray {
43 lint_array!(CONST_STATIC_LIFETIME)
48 // Recursively visit types
49 fn visit_type(&mut self, ty: &Ty, cx: &EarlyContext<'_>) {
51 // Be careful of nested structures (arrays and tuples)
52 TyKind::Array(ref ty, _) => {
53 self.visit_type(&*ty, cx);
55 TyKind::Tup(ref tup) => for tup_ty in tup {
56 self.visit_type(&*tup_ty, cx);
58 // This is what we are looking for !
59 TyKind::Rptr(ref optional_lifetime, ref borrow_type) => {
60 // Match the 'static lifetime
61 if let Some(lifetime) = *optional_lifetime {
62 match borrow_type.ty.node {
63 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Array(..) |
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)