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