]> git.lizzy.rs Git - rust.git/blob - src/strings.rs
Merge branch 'pr-78'
[rust.git] / src / strings.rs
1 //! This LintPass catches both string addition and string addition + assignment
2 //! 
3 //! Note that since we have two lints where one subsumes the other, we try to
4 //! disable the subsumed lint unless it has a higher level
5
6 use rustc::lint::*;
7 use rustc::middle::ty::TypeVariants::TyStruct;
8 use syntax::ast::*;
9 use syntax::codemap::{Span, Spanned};
10 use eq_op::is_exp_equal;
11 use misc::walk_ty;
12 use types::match_ty_unwrap;
13 use utils::{match_def_path, span_lint};
14
15 declare_lint! {
16     pub STRING_ADD_ASSIGN,
17     Warn,
18     "Warn on `x = x + ..` where x is a `String`"
19 }
20
21 #[derive(Copy,Clone)]
22 pub struct StringAdd;
23
24 impl LintPass for StringAdd {
25     fn get_lints(&self) -> LintArray {
26         lint_array!(STRING_ADD_ASSIGN)
27     }
28     
29     fn check_expr(&mut self, cx: &Context, e: &Expr) {
30         if let &ExprAssign(ref target, ref  src) = &e.node {
31             if is_string(cx, target) && is_add(src, target) { 
32                 span_lint(cx, STRING_ADD_ASSIGN, e.span, 
33                     "You assign the result of adding something to this string. \
34                     Consider using `String::push_str(..) instead.")
35             }
36         }
37     }
38 }
39
40 fn is_string(cx: &Context, e: &Expr) -> bool {
41     if let TyStruct(did, _) = walk_ty(cx.tcx.expr_ty(e)).sty {
42         match_def_path(cx, did.did, &["std", "string", "String"])
43     } else { false }
44 }
45
46 fn is_add(src: &Expr, target: &Expr) -> bool {
47     match &src.node {
48         &ExprBinary(Spanned{ node: BiAdd, .. }, ref left, _) =>
49             is_exp_equal(target, left),
50         &ExprBlock(ref block) => block.stmts.is_empty() && 
51             block.expr.as_ref().map_or(false, |expr| is_add(&*expr, target)),
52         &ExprParen(ref expr) => is_add(&*expr, target),
53         _ => false
54     }
55 }