]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/strings.rs
Auto merge of #3824 - phansch:adding_lints, r=phansch
[rust.git] / clippy_lints / src / strings.rs
1 use crate::utils::SpanlessEq;
2 use crate::utils::{get_parent_expr, is_allowed, match_type, paths, span_lint, span_lint_and_sugg, walk_ptrs_ty};
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_errors::Applicability;
7 use syntax::source_map::Spanned;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for string appends of the form `x = x + y` (without
11     /// `let`!).
12     ///
13     /// **Why is this bad?** It's not really bad, but some people think that the
14     /// `.push_str(_)` method is more readable.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     ///
20     /// ```rust
21     /// let mut x = "Hello".to_owned();
22     /// x = x + ", World";
23     /// ```
24     pub STRING_ADD_ASSIGN,
25     pedantic,
26     "using `x = x + ..` where x is a `String` instead of `push_str()`"
27 }
28
29 declare_clippy_lint! {
30     /// **What it does:** Checks for all instances of `x + _` where `x` is of type
31     /// `String`, but only if [`string_add_assign`](#string_add_assign) does *not*
32     /// match.
33     ///
34     /// **Why is this bad?** It's not bad in and of itself. However, this particular
35     /// `Add` implementation is asymmetric (the other operand need not be `String`,
36     /// but `x` does), while addition as mathematically defined is symmetric, also
37     /// the `String::push_str(_)` function is a perfectly good replacement.
38     /// Therefore some dislike it and wish not to have it in their code.
39     ///
40     /// That said, other people think that string addition, having a long tradition
41     /// in other languages is actually fine, which is why we decided to make this
42     /// particular lint `allow` by default.
43     ///
44     /// **Known problems:** None.
45     ///
46     /// **Example:**
47     ///
48     /// ```rust
49     /// let x = "Hello".to_owned();
50     /// x + ", World"
51     /// ```
52     pub STRING_ADD,
53     restriction,
54     "using `x + ..` where x is a `String` instead of `push_str()`"
55 }
56
57 declare_clippy_lint! {
58     /// **What it does:** Checks for the `as_bytes` method called on string literals
59     /// that contain only ASCII characters.
60     ///
61     /// **Why is this bad?** Byte string literals (e.g. `b"foo"`) can be used
62     /// instead. They are shorter but less discoverable than `as_bytes()`.
63     ///
64     /// **Known Problems:** None.
65     ///
66     /// **Example:**
67     /// ```rust
68     /// let bs = "a byte string".as_bytes();
69     /// ```
70     pub STRING_LIT_AS_BYTES,
71     style,
72     "calling `as_bytes` on a string literal instead of using a byte string literal"
73 }
74
75 #[derive(Copy, Clone)]
76 pub struct StringAdd;
77
78 impl LintPass for StringAdd {
79     fn get_lints(&self) -> LintArray {
80         lint_array!(STRING_ADD, STRING_ADD_ASSIGN)
81     }
82
83     fn name(&self) -> &'static str {
84         "StringAdd"
85     }
86 }
87
88 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd {
89     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
90         if let ExprKind::Binary(
91             Spanned {
92                 node: BinOpKind::Add, ..
93             },
94             ref left,
95             _,
96         ) = e.node
97         {
98             if is_string(cx, left) {
99                 if !is_allowed(cx, STRING_ADD_ASSIGN, e.hir_id) {
100                     let parent = get_parent_expr(cx, e);
101                     if let Some(p) = parent {
102                         if let ExprKind::Assign(ref target, _) = p.node {
103                             // avoid duplicate matches
104                             if SpanlessEq::new(cx).eq_expr(target, left) {
105                                 return;
106                             }
107                         }
108                     }
109                 }
110                 span_lint(
111                     cx,
112                     STRING_ADD,
113                     e.span,
114                     "you added something to a string. Consider using `String::push_str()` instead",
115                 );
116             }
117         } else if let ExprKind::Assign(ref target, ref src) = e.node {
118             if is_string(cx, target) && is_add(cx, src, target) {
119                 span_lint(
120                     cx,
121                     STRING_ADD_ASSIGN,
122                     e.span,
123                     "you assigned the result of adding something to this string. Consider using \
124                      `String::push_str()` instead",
125                 );
126             }
127         }
128     }
129 }
130
131 fn is_string(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
132     match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(e)), &paths::STRING)
133 }
134
135 fn is_add(cx: &LateContext<'_, '_>, src: &Expr, target: &Expr) -> bool {
136     match src.node {
137         ExprKind::Binary(
138             Spanned {
139                 node: BinOpKind::Add, ..
140             },
141             ref left,
142             _,
143         ) => SpanlessEq::new(cx).eq_expr(target, left),
144         ExprKind::Block(ref block, _) => {
145             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
146         },
147         _ => false,
148     }
149 }
150
151 #[derive(Copy, Clone)]
152 pub struct StringLitAsBytes;
153
154 impl LintPass for StringLitAsBytes {
155     fn get_lints(&self) -> LintArray {
156         lint_array!(STRING_LIT_AS_BYTES)
157     }
158
159     fn name(&self) -> &'static str {
160         "StringLiteralAsBytes"
161     }
162 }
163
164 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringLitAsBytes {
165     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
166         use crate::utils::{in_macro, snippet, snippet_with_applicability};
167         use syntax::ast::{LitKind, StrStyle};
168
169         if let ExprKind::MethodCall(ref path, _, ref args) = e.node {
170             if path.ident.name == "as_bytes" {
171                 if let ExprKind::Lit(ref lit) = args[0].node {
172                     if let LitKind::Str(ref lit_content, style) = lit.node {
173                         let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
174                         let expanded = if let StrStyle::Raw(n) = style {
175                             let term = (0..n).map(|_| '#').collect::<String>();
176                             format!("r{0}\"{1}\"{0}", term, lit_content.as_str())
177                         } else {
178                             format!("\"{}\"", lit_content.as_str())
179                         };
180                         let mut applicability = Applicability::MachineApplicable;
181                         if callsite.starts_with("include_str!") {
182                             span_lint_and_sugg(
183                                 cx,
184                                 STRING_LIT_AS_BYTES,
185                                 e.span,
186                                 "calling `as_bytes()` on `include_str!(..)`",
187                                 "consider using `include_bytes!(..)` instead",
188                                 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen(
189                                     "include_str",
190                                     "include_bytes",
191                                     1,
192                                 ),
193                                 applicability,
194                             );
195                         } else if callsite == expanded
196                             && lit_content.as_str().chars().all(|c| c.is_ascii())
197                             && !in_macro(args[0].span)
198                         {
199                             span_lint_and_sugg(
200                                 cx,
201                                 STRING_LIT_AS_BYTES,
202                                 e.span,
203                                 "calling `as_bytes()` on a string literal",
204                                 "consider using a byte string literal instead",
205                                 format!(
206                                     "b{}",
207                                     snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)
208                                 ),
209                                 applicability,
210                             );
211                         }
212                     }
213                 }
214             }
215         }
216     }
217 }