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