check for str type of .to_owned() callee

This commit is contained in:
llogiq 2015-05-21 16:37:38 +02:00
parent 5b1287f017
commit 4b1c72c949
1 changed files with 10 additions and 4 deletions

View File

@ -235,11 +235,12 @@ impl LintPass for CmpOwned {
fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
match &expr.node {
&ExprMethodCall(Spanned{node: ref ident, ..}, _, _) => {
&ExprMethodCall(Spanned{node: ref ident, ..}, _, ref args) => {
let name = ident.as_str();
if name == "to_string" || name == "to_owned" {
if name == "to_string" ||
name == "to_owned" && is_str_arg(cx, args) {
cx.span_lint(CMP_OWNED, expr.span, &format!(
"this creates an owned instance just for comparison.
"this creates an owned instance just for comparison. \
Consider using {}.as_slice() to compare without allocation",
cx.sess().codemap().span_to_snippet(other_span).unwrap_or(
"..".to_string())))
@ -250,7 +251,7 @@ fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
if path.segments.iter().zip(["String", "from_str"].iter()).all(
|(seg, name)| &seg.identifier.as_str() == name) {
cx.span_lint(CMP_OWNED, expr.span, &format!(
"this creates an owned instance just for comparison.
"this creates an owned instance just for comparison. \
Consider using {}.as_slice() to compare without allocation",
cx.sess().codemap().span_to_snippet(other_span).unwrap_or(
"..".to_string())))
@ -260,3 +261,8 @@ fn check_to_owned(cx: &Context, expr: &Expr, other_span: Span) {
_ => ()
}
}
fn is_str_arg(cx: &Context, args: &[P<Expr>]) -> bool {
args.len() == 1 && if let ty_str =
walk_ty(expr_ty(cx.tcx, &*args[0])).sty { true } else { false }
}