aboutsummaryrefslogtreecommitdiffstats
path: root/components/plugins/lints/str_to_string.rs
diff options
context:
space:
mode:
authorRohan Prinja <rohan.prinja@gmail.com>2014-12-31 19:36:13 +0530
committerRohan Prinja <rohan.prinja@gmail.com>2015-01-01 13:50:55 +0530
commit7ac58f202f44bebf1021ff523a3ac913dcfe0b4c (patch)
tree5a2c525e6cb7bacaf7a5037f29f42c9d0cec3e0d /components/plugins/lints/str_to_string.rs
parent0da57abec6014f8a6edde9781598053deab996c7 (diff)
downloadservo-7ac58f202f44bebf1021ff523a3ac913dcfe0b4c.tar.gz
servo-7ac58f202f44bebf1021ff523a3ac913dcfe0b4c.zip
break up lints.rs into separate files
Diffstat (limited to 'components/plugins/lints/str_to_string.rs')
-rw-r--r--components/plugins/lints/str_to_string.rs48
1 files changed, 48 insertions, 0 deletions
diff --git a/components/plugins/lints/str_to_string.rs b/components/plugins/lints/str_to_string.rs
new file mode 100644
index 00000000000..79c2d917139
--- /dev/null
+++ b/components/plugins/lints/str_to_string.rs
@@ -0,0 +1,48 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+use syntax::ast;
+use rustc::lint::{Context, LintPass, LintArray};
+use rustc::middle::ty::expr_ty;
+use rustc::middle::ty;
+use rustc::middle::typeck::astconv::AstConv;
+
+declare_lint!(STR_TO_STRING, Deny,
+ "Warn when a String could use into_string() instead of to_string()")
+
+/// Prefer str.into_string() over str.to_string()
+///
+/// The latter creates a `Formatter` and is 5x slower than the former
+pub struct StrToStringPass;
+
+impl LintPass for StrToStringPass {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(STR_TO_STRING)
+ }
+
+ fn check_expr(&mut self, cx: &Context, expr: &ast::Expr) {
+ match expr.node {
+ ast::ExprMethodCall(ref method, _, ref args)
+ if method.node.as_str() == "to_string"
+ && is_str(cx, &*args[0]) => {
+ cx.span_lint(STR_TO_STRING, expr.span,
+ "str.into_string() is more efficient than str.to_string(), please use it instead");
+ },
+ _ => ()
+ }
+
+ fn is_str(cx: &Context, expr: &ast::Expr) -> bool {
+ fn walk_ty<'t>(ty: ty::t) -> ty::t {
+ match ty::get(ty).sty {
+ ty::ty_ptr(ref tm) | ty::ty_rptr(_, ref tm) => walk_ty(tm.ty),
+ _ => ty
+ }
+ }
+ match ty::get(walk_ty(expr_ty(cx.tcx, expr))).sty {
+ ty::ty_str => true,
+ _ => false
+ }
+ }
+ }
+}