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