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;
12 use types::match_ty_unwrap;
13 use utils::{match_def_path, span_lint};
16 pub STRING_ADD_ASSIGN,
18 "Warn on `x = x + ..` where x is a `String`"
24 impl LintPass for StringAdd {
25 fn get_lints(&self) -> LintArray {
26 lint_array!(STRING_ADD_ASSIGN)
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.")
40 fn is_string(cx: &Context, e: &Expr) -> bool {
41 if let TyStruct(def_id, _) = walk_ty(cx.tcx.expr_ty(e)).sty {
42 match_def_path(cx, def_id, &["std", "string", "String"])
46 fn is_add(src: &Expr, target: &Expr) -> bool {
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),