1 //! This LintPass catches both string addition and string addition + assignment
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
7 use rustc::middle::ty::TypeVariants::TyStruct;
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};
15 pub STRING_ADD_ASSIGN,
17 "Warn on `x = x + ..` where x is a `String`"
23 impl LintPass for StringAdd {
24 fn get_lints(&self) -> LintArray {
25 lint_array!(STRING_ADD_ASSIGN)
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.")
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"])
45 fn is_add(src: &Expr, target: &Expr) -> bool {
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),