Skip to content

Implementation of the const_static_lifetime lint. #2151

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Oct 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion clippy_lints/src/approx_const.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ declare_lint! {
}

// Tuples are of the form (constant, name, min_digits)
const KNOWN_CONSTS: &'static [(f64, &'static str, usize)] = &[
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't make unrelated formatting changes

const KNOWN_CONSTS: &[(f64, &str, usize)] = &[
(f64::E, "E", 4),
(f64::FRAC_1_PI, "FRAC_1_PI", 4),
(f64::FRAC_1_SQRT_2, "FRAC_1_SQRT_2", 5),
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/block_in_if_condition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ impl<'a, 'tcx: 'a> Visitor<'tcx> for ExVisitor<'a, 'tcx> {
}
}

const BRACED_EXPR_MESSAGE: &'static str = "omit braces around single expression condition";
const COMPLEX_BLOCK_MESSAGE: &'static str = "in an 'if' condition, avoid complex blocks or closures with blocks; \
const BRACED_EXPR_MESSAGE: &str = "omit braces around single expression condition";
const COMPLEX_BLOCK_MESSAGE: &str = "in an 'if' condition, avoid complex blocks or closures with blocks; \
instead, move the block or closure higher and bind it with a 'let'";

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BlockInIfCondition {
Expand Down
84 changes: 84 additions & 0 deletions clippy_lints/src/const_static_lifetime.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
use syntax::ast::{Item, ItemKind, TyKind, Ty};
use rustc::lint::{LintPass, EarlyLintPass, LintArray, EarlyContext};
use utils::{span_lint_and_then, in_macro};

/// **What it does:** Checks for constants with an explicit `'static` lifetime.
///
/// **Why is this bad?** Adding `'static` to every reference can create very
/// complicated types.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =
/// &[...]
/// ```
/// This code can be rewritten as
/// ```rust
/// const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]
/// ```

declare_lint! {
pub CONST_STATIC_LIFETIME,
Warn,
"Using explicit `'static` lifetime for constants when elision rules would allow omitting them."
}

pub struct StaticConst;

impl LintPass for StaticConst {
fn get_lints(&self) -> LintArray {
lint_array!(CONST_STATIC_LIFETIME)
}
}

impl StaticConst {
// Recursively visit types
fn visit_type(&mut self, ty: &Ty, cx: &EarlyContext) {
match ty.node {
// Be carefull of nested structures (arrays and tuples)
TyKind::Array(ref ty, _) => {
self.visit_type(&*ty, cx);
},
TyKind::Tup(ref tup) => {
for tup_ty in tup {
self.visit_type(&*tup_ty, cx);
}
},
// This is what we are looking for !
TyKind::Rptr(ref optional_lifetime, ref borrow_type) => {
// Match the 'static lifetime
if let Some(lifetime) = *optional_lifetime {
if let TyKind::Path(_, _) = borrow_type.ty.node {
// Verify that the path is a str
if lifetime.ident.name == "'static" {
let mut sug: String = String::new();
span_lint_and_then(cx,
CONST_STATIC_LIFETIME,
lifetime.span,
"Constants have by default a `'static` lifetime",
|db| {db.span_suggestion(lifetime.span,"consider removing `'static`",sug);});
}
}
}
self.visit_type(&*borrow_type.ty, cx);
},
TyKind::Slice(ref ty) => {
self.visit_type(ty, cx);
},
_ => {},
}
}
}

impl EarlyLintPass for StaticConst {
fn check_item(&mut self, cx: &EarlyContext, item: &Item) {
if !in_macro(item.span) {
// Match only constants...
if let ItemKind::Const(ref var_type, _) = item.node {
self.visit_type(var_type, cx);
}
}
}
}
2 changes: 1 addition & 1 deletion clippy_lints/src/doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ impl<'a> Iterator for Parser<'a> {
#[allow(cast_possible_truncation)]
pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
// one-line comments lose their prefix
const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"];
const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
for prefix in ONELINERS {
if comment.starts_with(*prefix) {
let doc = &comment[prefix.len()..];
Expand Down
3 changes: 3 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ pub mod block_in_if_condition;
pub mod booleans;
pub mod bytecount;
pub mod collapsible_if;
pub mod const_static_lifetime;
pub mod copies;
pub mod cyclomatic_complexity;
pub mod derive;
Expand Down Expand Up @@ -339,6 +340,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
reg.register_late_lint_pass(box invalid_ref::InvalidRef);
reg.register_late_lint_pass(box identity_conversion::IdentityConversion::default());
reg.register_late_lint_pass(box types::ImplicitHasher);
reg.register_early_lint_pass(box const_static_lifetime::StaticConst);

reg.register_lint_group("clippy_restrictions", vec![
arithmetic::FLOAT_ARITHMETIC,
Expand All @@ -349,6 +351,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {

reg.register_lint_group("clippy_pedantic", vec![
booleans::NONMINIMAL_BOOL,
const_static_lifetime::CONST_STATIC_LIFETIME,
empty_enum::EMPTY_ENUM,
enum_glob_use::ENUM_GLOB_USE,
enum_variants::PUB_ENUM_VARIANT_NAMES,
Expand Down
6 changes: 3 additions & 3 deletions clippy_lints/src/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1531,7 +1531,7 @@ enum Convention {
}

#[cfg_attr(rustfmt, rustfmt_skip)]
const CONVENTIONS: [(Convention, &'static [SelfKind]); 6] = [
const CONVENTIONS: [(Convention, &[SelfKind]); 6] = [
(Convention::Eq("new"), &[SelfKind::No]),
(Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
(Convention::StartsWith("from_"), &[SelfKind::No]),
Expand All @@ -1541,7 +1541,7 @@ const CONVENTIONS: [(Convention, &'static [SelfKind]); 6] = [
];

#[cfg_attr(rustfmt, rustfmt_skip)]
const TRAIT_METHODS: [(&'static str, usize, SelfKind, OutType, &'static str); 30] = [
const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
Expand Down Expand Up @@ -1575,7 +1575,7 @@ const TRAIT_METHODS: [(&'static str, usize, SelfKind, OutType, &'static str); 30
];

#[cfg_attr(rustfmt, rustfmt_skip)]
const PATTERN_METHODS: [(&'static str, usize); 17] = [
const PATTERN_METHODS: [(&str, usize); 17] = [
("contains", 1),
("starts_with", 1),
("ends_with", 1),
Expand Down
8 changes: 4 additions & 4 deletions clippy_lints/src/needless_continue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,15 +252,15 @@ struct LintData<'a> {
block_stmts: &'a [ast::Stmt],
}

const MSG_REDUNDANT_ELSE_BLOCK: &'static str = "This else block is redundant.\n";
const MSG_REDUNDANT_ELSE_BLOCK: &str = "This else block is redundant.\n";

const MSG_ELSE_BLOCK_NOT_NEEDED: &'static str = "There is no need for an explicit `else` block for this `if` \
const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "There is no need for an explicit `else` block for this `if` \
expression\n";

const DROP_ELSE_BLOCK_AND_MERGE_MSG: &'static str = "Consider dropping the else clause and merging the code that \
const DROP_ELSE_BLOCK_AND_MERGE_MSG: &str = "Consider dropping the else clause and merging the code that \
follows (in the loop) with the if block, like so:\n";

const DROP_ELSE_BLOCK_MSG: &'static str = "Consider dropping the else clause, and moving out the code in the else \
const DROP_ELSE_BLOCK_MSG: &str = "Consider dropping the else clause, and moving out the code in the else \
block, like so:\n";


Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/non_expressive_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ struct SimilarNamesLocalVisitor<'a, 'tcx: 'a> {
// this list contains lists of names that are allowed to be similar
// the assumption is that no name is ever contained in multiple lists.
#[cfg_attr(rustfmt, rustfmt_skip)]
const WHITELIST: &'static [&'static [&'static str]] = &[
const WHITELIST: &[&[&str]] = &[
&["parsed", "parser"],
&["lhs", "rhs"],
&["tx", "rx"],
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/utils/conf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ define_Conf! {
/// Search for the configuration file.
pub fn lookup_conf_file() -> io::Result<Option<path::PathBuf>> {
/// Possible filename to search for.
const CONFIG_FILE_NAMES: [&'static str; 2] = [".clippy.toml", "clippy.toml"];
const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];

let mut current = try!(env::current_dir());

Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/utils/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
/// See also [the reference][reference-types] for a list of such types.
///
/// [reference-types]: https://doc.rust-lang.org/reference.html#types
pub const BUILTIN_TYPES: &'static [&'static str] = &[
pub const BUILTIN_TYPES: &[&str] = &[
"i8",
"u8",
"i16",
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ pub fn match_def_path(tcx: TyCtxt, def_id: DefId, path: &[&str]) -> bool {

impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
fn root_mode(&self) -> &ty::item_path::RootMode {
const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
const ABSOLUTE: &ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
ABSOLUTE
}

Expand Down
Loading