]> git.lizzy.rs Git - rust.git/blob - src/strings.rs
add known problems
[rust.git] / src / strings.rs
1 //! This lint 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::hir::*;
7 use rustc::lint::*;
8 use syntax::codemap::Spanned;
9 use utils::SpanlessEq;
10 use utils::{match_type, paths, span_lint, span_lint_and_then, walk_ptrs_ty, get_parent_expr};
11
12 /// **What it does:** This lint matches code of the form `x = x + y` (without `let`!).
13 ///
14 /// **Why is this bad?** It's not really bad, but some people think that the `.push_str(_)` method is more readable.
15 ///
16 /// **Known problems:** None.
17 ///
18 /// **Example:**
19 ///
20 /// ```
21 /// let mut x = "Hello".to_owned();
22 /// x = x + ", World";
23 /// ```
24 declare_lint! {
25     pub STRING_ADD_ASSIGN,
26     Allow,
27     "using `x = x + ..` where x is a `String`; suggests using `push_str()` instead"
28 }
29
30 /// **What it does:** The `string_add` lint matches all instances of `x + _` where `x` is of type `String`, but only if [`string_add_assign`](#string_add_assign) does *not* match.
31 ///
32 /// **Why is this bad?** It's not bad in and of itself. However, this particular `Add` implementation is asymmetric (the other operand need not be `String`, but `x` does), while addition as mathematically defined is symmetric, also the `String::push_str(_)` function is a perfectly good replacement. Therefore some dislike it and wish not to have it in their code.
33 ///
34 /// That said, other people think that String addition, having a long tradition in other languages is actually fine, which is why we decided to make this particular lint `allow` by default.
35 ///
36 /// **Known problems:** None
37 ///
38 /// **Example:**
39 ///
40 /// ```
41 /// let x = "Hello".to_owned();
42 /// x + ", World"
43 /// ```
44 declare_lint! {
45     pub STRING_ADD,
46     Allow,
47     "using `x + ..` where x is a `String`; suggests using `push_str()` instead"
48 }
49
50 /// **What it does:** This lint matches the `as_bytes` method called on string
51 /// literals that contain only ascii characters.
52 ///
53 /// **Why is this bad?** Byte string literals (e.g. `b"foo"`) can be used instead. They are shorter but less discoverable than `as_bytes()`.
54 ///
55 /// **Example:**
56 ///
57 /// ```
58 /// let bs = "a byte string".as_bytes();
59 /// ```
60 declare_lint! {
61     pub STRING_LIT_AS_BYTES,
62     Warn,
63     "calling `as_bytes` on a string literal; suggests using a byte string literal instead"
64 }
65
66 #[derive(Copy, Clone)]
67 pub struct StringAdd;
68
69 impl LintPass for StringAdd {
70     fn get_lints(&self) -> LintArray {
71         lint_array!(STRING_ADD, STRING_ADD_ASSIGN)
72     }
73 }
74
75 impl LateLintPass for StringAdd {
76     fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
77         if let ExprBinary(Spanned { node: BiAdd, .. }, ref left, _) = e.node {
78             if is_string(cx, left) {
79                 if let Allow = cx.current_level(STRING_ADD_ASSIGN) {
80                     // the string_add_assign is allow, so no duplicates
81                 } else {
82                     let parent = get_parent_expr(cx, e);
83                     if let Some(ref p) = parent {
84                         if let ExprAssign(ref target, _) = p.node {
85                             // avoid duplicate matches
86                             if SpanlessEq::new(cx).eq_expr(target, left) {
87                                 return;
88                             }
89                         }
90                     }
91                 }
92                 span_lint(cx,
93                           STRING_ADD,
94                           e.span,
95                           "you added something to a string. Consider using `String::push_str()` instead");
96             }
97         } else if let ExprAssign(ref target, ref src) = e.node {
98             if is_string(cx, target) && is_add(cx, src, target) {
99                 span_lint(cx,
100                           STRING_ADD_ASSIGN,
101                           e.span,
102                           "you assigned the result of adding something to this string. Consider using \
103                            `String::push_str()` instead");
104             }
105         }
106     }
107 }
108
109 fn is_string(cx: &LateContext, e: &Expr) -> bool {
110     match_type(cx, walk_ptrs_ty(cx.tcx.expr_ty(e)), &paths::STRING)
111 }
112
113 fn is_add(cx: &LateContext, src: &Expr, target: &Expr) -> bool {
114     match src.node {
115         ExprBinary(Spanned { node: BiAdd, .. }, ref left, _) => SpanlessEq::new(cx).eq_expr(target, left),
116         ExprBlock(ref block) => {
117             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
118         }
119         _ => false,
120     }
121 }
122
123 #[derive(Copy, Clone)]
124 pub struct StringLitAsBytes;
125
126 impl LintPass for StringLitAsBytes {
127     fn get_lints(&self) -> LintArray {
128         lint_array!(STRING_LIT_AS_BYTES)
129     }
130 }
131
132 impl LateLintPass for StringLitAsBytes {
133     fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
134         use std::ascii::AsciiExt;
135         use syntax::ast::LitKind;
136         use utils::{snippet, in_macro};
137
138         if let ExprMethodCall(ref name, _, ref args) = e.node {
139             if name.node.as_str() == "as_bytes" {
140                 if let ExprLit(ref lit) = args[0].node {
141                     if let LitKind::Str(ref lit_content, _) = lit.node {
142                         if lit_content.chars().all(|c| c.is_ascii()) && !in_macro(cx, args[0].span) {
143                             span_lint_and_then(cx,
144                                                STRING_LIT_AS_BYTES,
145                                                e.span,
146                                                "calling `as_bytes()` on a string literal",
147                                                |db| {
148                                                    let sugg = format!("b{}", snippet(cx, args[0].span, r#""foo""#));
149                                                    db.span_suggestion(e.span,
150                                                                       "consider using a byte string literal instead",
151                                                                       sugg);
152                                                });
153
154                         }
155                     }
156                 }
157             }
158         }
159     }
160 }