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