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