From 4074c1f968d5bd37b3dec36bc21cbf656de65907 Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Wed, 12 Aug 2015 17:02:49 +0200 Subject: [PATCH] methods: lint against String.to_string (fixes #100) --- src/lib.rs | 1 + src/methods.rs | 10 +++++++++- tests/compile-fail/methods.rs | 4 ++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 7b47edaa4..3299debbe 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -83,5 +83,6 @@ pub fn plugin_registrar(reg: &mut Registry) { methods::OPTION_UNWRAP_USED, methods::RESULT_UNWRAP_USED, methods::STR_TO_STRING, + methods::STRING_TO_STRING, ]); } diff --git a/src/methods.rs b/src/methods.rs index f02e06640..a5b12e52b 100644 --- a/src/methods.rs +++ b/src/methods.rs @@ -13,10 +13,12 @@ declare_lint!(pub RESULT_UNWRAP_USED, Allow, "Warn on using unwrap() on a Result value"); declare_lint!(pub STR_TO_STRING, Warn, "Warn when a String could use to_owned() instead of to_string()"); +declare_lint!(pub STRING_TO_STRING, Warn, + "Warn when calling String.to_string()"); impl LintPass for MethodsPass { fn get_lints(&self) -> LintArray { - lint_array!(OPTION_UNWRAP_USED, RESULT_UNWRAP_USED, STR_TO_STRING) + lint_array!(OPTION_UNWRAP_USED, RESULT_UNWRAP_USED, STR_TO_STRING, STRING_TO_STRING) } fn check_expr(&mut self, cx: &Context, expr: &Expr) { @@ -41,6 +43,12 @@ impl LintPass for MethodsPass { if let ty::TyStr = *obj_ty { span_lint(cx, STR_TO_STRING, expr.span, "`str.to_owned()` is faster"); } + else if let ty::TyStruct(did, _) = *obj_ty { + if match_def_path(cx, did.did, &["collections", "string", "String"]) { + span_lint(cx, STRING_TO_STRING, expr.span, + "`String.to_string()` is a no-op") + } + } } } } diff --git a/tests/compile-fail/methods.rs b/tests/compile-fail/methods.rs index e989dffe5..facf03783 100755 --- a/tests/compile-fail/methods.rs +++ b/tests/compile-fail/methods.rs @@ -2,10 +2,14 @@ #![plugin(clippy)] #[deny(option_unwrap_used, result_unwrap_used)] +#[deny(str_to_string, string_to_string)] fn main() { let opt = Some(0); let _ = opt.unwrap(); //~ERROR let res: Result = Ok(0); let _ = res.unwrap(); //~ERROR + + let string = "str".to_string(); //~ERROR + let _again = string.to_string(); //~ERROR }