]> git.lizzy.rs Git - rust.git/blob - src/strings.rs
b6bc7654e4792453e8475f32c0cba7fe723f1b05
[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 types::match_ty_unwrap;
12 use utils::{match_def_path, span_lint, walk_ptrs_ty};
13
14 declare_lint! {
15     pub STRING_ADD_ASSIGN,
16     Warn,
17     "Warn on `x = x + ..` where x is a `String`"
18 }
19
20 #[derive(Copy,Clone)]
21 pub struct StringAdd;
22
23 impl LintPass for StringAdd {
24     fn get_lints(&self) -> LintArray {
25         lint_array!(STRING_ADD_ASSIGN)
26     }
27
28     fn check_expr(&mut self, cx: &Context, e: &Expr) {
29         if let &ExprAssign(ref target, ref  src) = &e.node {
30             if is_string(cx, target) && is_add(src, target) {
31                 span_lint(cx, STRING_ADD_ASSIGN, e.span,
32                     "You assign the result of adding something to this string. \
33                     Consider using `String::push_str(..) instead.")
34             }
35         }
36     }
37 }
38
39 fn is_string(cx: &Context, e: &Expr) -> bool {
40     if let TyStruct(did, _) = walk_ptrs_ty(cx.tcx.expr_ty(e)).sty {
41         match_def_path(cx, did.did, &["std", "string", "String"])
42     } else { false }
43 }
44
45 fn is_add(src: &Expr, target: &Expr) -> bool {
46     match &src.node {
47         &ExprBinary(Spanned{ node: BiAdd, .. }, ref left, _) =>
48             is_exp_equal(target, left),
49         &ExprBlock(ref block) => block.stmts.is_empty() &&
50             block.expr.as_ref().map_or(false, |expr| is_add(&*expr, target)),
51         &ExprParen(ref expr) => is_add(&*expr, target),
52         _ => false
53     }
54 }