]> git.lizzy.rs Git - rust.git/commitdiff
methods: lint against String.to_string (fixes #100)
authorGeorg Brandl <georg@python.org>
Wed, 12 Aug 2015 15:02:49 +0000 (17:02 +0200)
committerGeorg Brandl <georg@python.org>
Wed, 12 Aug 2015 15:03:13 +0000 (17:03 +0200)
src/lib.rs
src/methods.rs
tests/compile-fail/methods.rs

index 7b47edaa496597c9076e44279a711a48eaed9841..3299debbe0db339c92d97559f40e1cf77dad9a3b 100755 (executable)
@@ -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,
                                            ]);
 }
index f02e06640923657bc8c84fee37924e98478b6c7e..a5b12e52bdf5be5723eb492b48149a26d4c6ab0f 100644 (file)
               "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 @@ fn check_expr(&mut self, cx: &Context, expr: &Expr) {
                 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")
+                    }
+                }
             }
         }
     }
index e989dffe5a774c8087e6592e3251b2597d12b260..facf03783926ac79843c90bc3906ade9c58fca0d 100755 (executable)
@@ -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<i32, ()> = Ok(0);
     let _ = res.unwrap();  //~ERROR
+
+    let string = "str".to_string();  //~ERROR
+    let _again = string.to_string();  //~ERROR
 }