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